I am struggling with Next.js 13’s app
routing. It always gives me a 404 Not Found when I try to access fromPostmann for example.
I have this file structure:
And for example, one of my API files is:
import { PrismaClient } from '@prisma/client';
const prisma = new PrismaClient();
export default async function all(req, res) {
if (req.method !== 'GET') {
return res.status(405).json({ error: 'Method not allowed' });
}
try {
// Get all admins using Prisma
const admins = await prisma.admin.findMany();
return res.status(200).json(admins);
}
catch (error) {
return res.status(500).json({ error: 'Failed to get admins' });
}
}
When I send a GET localhost:3000/api/admin/all
it always responds with a 404. Couldn’t find where is the error.
I tried other file or folder namings. Calling from my own app, using the curl command, or using Postman. My other API routes give the same 404.
2
Answers
An API Route should be in a file called
route.js
. Meaningapp/api/admin/all.js
should beapp/api/admin/route.js
. Also, the functions inside should use a specific definition:GET
, can be replaced withPOST
,PUT
,PATCH
, etc. In your case, it would be:In addition to Youssouf’s answer (which I found very helpful), if you have problems getting the content of
request.body
, useconst body = await request.json()
to get the body.https://developer.mozilla.org/en-US/docs/Web/API/Request/json