▲ 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 });
}

Common Errors & Troubleshooting

  • 404 when calling /api/hello — the file must be named exactly route.js (not page.js) inside app/api/hello/. A route folder can have a page.js (a webpage) or a route.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 token reading the request body — calling request.json() on a request with no body, or the wrong Content-Type, throws. Make sure the client actually sends Content-Type: application/json along with a JSON body.