---
title: "How do I create an API endpoint in the Next.js App Router?"
description: "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."
url: https://www.danny.engineering/answer/nextjs/how-do-i-create-an-api-endpoint-in-the-nextjs-app-router
author: Danny
published: 2026-11-27T00:00:00.000Z
updated: 2026-11-27T20:30:00.000Z
tags: ["Next.js"]
---

# How do I create an API endpoint in the Next.js App Router?

## 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`.


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


## 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`.


```typescript
// app/api/todos/route.ts
import type { NextRequest } from 'next/server';
import { db } from '@/lib/db';

export async function GET(request: NextRequest) {
  const status = request.nextUrl.searchParams.get('status') ?? 'open';
  const todos = await db.todo.findMany({ where: { status } });
  return Response.json(todos);
}

export async function POST(request: Request) {
  const body = await request.json();

  if (typeof body.title !== 'string' || body.title.length === 0) {
    return Response.json({ error: 'title is required' }, { status: 400 });
  }

  const todo = await db.todo.create({ data: { title: body.title } });
  return Response.json(todo, { status: 201 });
}
```


### 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.


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


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.


```typescript
import { cookies, headers } from 'next/headers';

export async function GET() {
  const session = (await cookies()).get('session');
  const agent = (await headers()).get('user-agent');

  if (!session) {
    return Response.json({ error: 'Not signed in' }, { status: 401 });
  }

  return Response.json({ agent });
}
```


### 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.


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


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.

## Related reading

- [Next.js: route.js](https://nextjs.org/docs/app/api-reference/file-conventions/route)
- [Next.js: NextRequest](https://nextjs.org/docs/app/api-reference/functions/next-request)
- [MDN: Response](https://developer.mozilla.org/docs/Web/API/Response)
