▲ Next.js Tutorial
← PrevNext →
API Routes in Next.js
Build backend endpoints inside your Next.js app.
API Routes in Next.js
Next.js lets you write backend endpoints in the same project as your frontend, using Route Handlers.
// app/api/hello/route.js
export async function GET() {
return Response.json({ message: "Hello from the API!" });
}
Visiting /api/hello returns:
{ "message": "Hello from the API!" }
Handling POST Requests
// app/api/contact/route.js
export async function POST(request) {
const body = await request.json();
// ...save body.email somewhere...
return Response.json({ ok: true });
}
Dynamic API Routes
Just like pages, API routes support dynamic segments:
// app/api/users/[id]/route.js
export async function GET(request, { params }) {
const { id } = await params;
return Response.json({ id });
}
Advertisement728 x 90
Common Errors & Troubleshooting
- 404 when calling
/api/hello— the file must be named exactlyroute.js(notpage.js) insideapp/api/hello/. A route folder can have apage.js(a webpage) or aroute.js(an API endpoint), but not both in the same folder. 405 Method Not Allowed— only the HTTP methods you explicitly export (GET,POST, etc.) are handled; calling the endpoint with a method you didn't export a function for returns a 405.SyntaxError: Unexpected tokenreading the request body — callingrequest.json()on a request with no body, or the wrongContent-Type, throws. Make sure the client actually sendsContent-Type: application/jsonalong with a JSON body.
Advertisement320 x 100