More Next.js answers

by Danny
Published 2 min read

In the App Router, API endpoints are Route Handlers: a route.ts file that exports functions named after HTTP methods and uses the standard Request and Response APIs.

The short answer

#

Create a route.ts file inside the app folder and export a function for each HTTP method you want to handle. The folder path becomes the URL, so app/api/hello/route.ts answers requests to /api/hello.


_10
// app/api/hello/route.ts
_10
export async function GET() {
_10
return Response.json({ message: 'Hello' });
_10
}

Why it happens

#

The Pages Router used pages/api/*.ts files with a Node-style req and res. The App Router has no pages/api folder. Instead it uses Route Handlers, which are built on the web standard Request and Response objects, the same ones you use with fetch. Any folder in app can hold a route.ts. The api prefix is only a convention.

Supported method names are GET, POST, PUT, PATCH, DELETE, HEAD and OPTIONS. If you do not define OPTIONS, Next.js answers it for you with the right Allow header. A request for any other method gets a 405 response.

How to fix it

#

Handle reads and writes

Read query strings from request.nextUrl.searchParams and the body with request.json() or request.formData(). Return a status with the second argument to Response.json.


_20
// app/api/todos/route.ts
_20
import type { NextRequest } from 'next/server';
_20
import { db } from '@/lib/db';
_20
_20
export async function GET(request: NextRequest) {
_20
const status = request.nextUrl.searchParams.get('status') ?? 'open';
_20
const todos = await db.todo.findMany({ where: { status } });
_20
return Response.json(todos);
_20
}
_20
_20
export async function POST(request: Request) {
_20
const body = await request.json();
_20
_20
if (typeof body.title !== 'string' || body.title.length === 0) {
_20
return Response.json({ error: 'title is required' }, { status: 400 });
_20
}
_20
_20
const todo = await db.todo.create({ data: { title: body.title } });
_20
return Response.json(todo, { status: 201 });
_20
}

Use dynamic segments

Put the handler in a folder with square brackets. The second argument holds params, which is a Promise from Next.js 15 onwards.


_10
// app/api/todos/[id]/route.ts
_10
export async function DELETE(
_10
request: Request,
_10
{ params }: { params: Promise<{ id: string }> }
_10
) {
_10
const { id } = await params;
_10
await db.todo.delete({ where: { id } });
_10
return new Response(null, { status: 204 });
_10
}

If you run next dev, next build or next typegen, a global RouteContext type is generated, so you can write ctx: RouteContext<'/api/todos/[id]'> and get typed params without writing the type yourself.

Read cookies and headers

Use cookies() and headers() from next/headers. Both are async.


_12
import { cookies, headers } from 'next/headers';
_12
_12
export async function GET() {
_12
const session = (await cookies()).get('session');
_12
const agent = (await headers()).get('user-agent');
_12
_12
if (!session) {
_12
return Response.json({ error: 'Not signed in' }, { status: 401 });
_12
}
_12
_12
return Response.json({ agent });
_12
}

Return something other than JSON

A Route Handler can return any Response: text, XML, a file or a stream. Set the Content-Type header yourself.


_10
// app/feed.xml/route.ts
_10
export async function GET() {
_10
const xml = await buildFeed();
_10
return new Response(xml, { headers: { 'Content-Type': 'application/xml' } });
_10
}

For sitemaps, robots files, icons and Open Graph images, prefer the built-in metadata files, which are Route Handlers with extra help.

Consider a Server Action for your own forms

If the only caller is a form or button in your own app, a Server Action is often simpler: no URL, no manual fetch, and it works with useActionState. Keep Route Handlers for webhooks, mobile apps, third parties and anything that needs a public URL.

Common pitfalls

#
  • A page and a route in the same folder. page.tsx and route.ts cannot sit in the same route segment. Move the API to its own path.
  • Expecting GET to be cached. Since Next.js 15, GET handlers run on every request by default. Opt into caching with export const revalidate = 60 or, with Cache Components on, by moving the data work into a 'use cache' function.
  • Fetching your own API from a Server Component. This adds a needless HTTP round trip and fails at build time when the server is not running. Call the data function directly instead.
  • Using the old req and res API. There is no res.status().json(). Return a Response instead.
  • Forgetting CORS. Browsers on other origins need Access-Control-Allow-Origin and friends. Set them on the response, or for many routes in next.config headers or proxy.ts.
  • Calling redirect inside try. redirect() works in a Route Handler, but it throws to do its job, so keep it outside try blocks.
#

Was this resource helpful?