Route handlers

Intermediate · 6 min

Build HTTP endpoints with route.ts, read params and the request, and see how GET handlers are cached, static, or dynamic with and without Cache Components.

Before thisServer Actions basicsDynamic routes and params

Codevolution · 6 min

Route handlers

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by CodevolutionReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • A route.ts file in the app directory defines an HTTP endpoint by exporting functions named after methods: GET, POST, PUT, PATCH, DELETE, HEAD, and OPTIONS.
  • A route.ts cannot share a segment with a page.tsx, because each file takes over every HTTP verb for its route.
  • Reach for a route handler when something other than your own React UI needs an endpoint, such as a webhook, a mobile app, or a third-party client.
  • Without Cache Components GET handlers are not cached by default; with Cache Components a GET handler is prerendered if it uses no request or uncached data, and runs at request time otherwise.
  • In a dynamic route, params is a promise: type the context with RouteContext and await ctx.params.

An endpoint, not a page

A page returns UI. Sometimes you need to return data: a JSON list for a mobile app, a webhook receiver for a payment provider, a file download. A route handler is the App Router’s answer. It is a route.ts file that exports a function per HTTP method.

// app/api/items/route.ts
export async function GET(request: Request) {
  return Response.json({ items: [] })
}

export async function POST(request: Request) {
  const body = await request.json()
  // validate, then create
  return Response.json({ ok: true }, { status: 201 })
}

It uses the standard web Request and Response. Next.js adds NextRequest and NextResponse with helpers for cookies, URL parsing, and redirects. Supported methods are GET, POST, PUT, PATCH, DELETE, HEAD, and OPTIONS; anything else gets 405 Method Not Allowed.

Route handlers and pages do not share a segment

Each route.ts or page.tsx takes over every verb for its segment, so they cannot live side by side. app/page.tsx plus app/route.ts is a conflict. app/page.tsx plus app/api/route.ts is fine. Route handlers also do not take part in layouts or client-side navigation.

Dynamic segments

params is a promise in 16. The global RouteContext helper types it from the path:

// app/users/[id]/route.ts
import type { NextRequest } from 'next/server'

export async function GET(_req: NextRequest, ctx: RouteContext<'/users/[id]'>) {
  const { id } = await ctx.params
  return Response.json({ id })
}

The helper’s types are generated during next dev, next build, or next typegen.

Caching: two models

Without Cache Components: route handlers are not cached by default. You can opt a GET in with export const dynamic = 'force-static'. Other methods are never cached. I built a plain GET handler with cacheComponents off on 16.4.6, and the route table showed it as ƒ (dynamic).

With Cache Components: a GET handler follows the same rules as a page. If it needs no request data and no uncached data, it is prerendered at build time. If it calls Math.random(), headers(), a database, or a network request, it runs at request time. I built two handlers: one returning a constant (○, static) and one returning Math.random() (ƒ, dynamic). To include uncached data in a static response, put it behind use cache. The docs add that use cache cannot be used directly in the handler body, so extract the work into a helper function:

import { cacheLife } from 'next/cache'

export async function GET() {
  return Response.json(await getProducts())
}

async function getProducts() {
  'use cache'
  cacheLife('hours')
  return db.query('SELECT * FROM products')
}

Handlers are also where on-demand revalidation for external events lives. A CMS webhook can hit a handler that calls revalidateTag('posts', 'max'); updateTag is not available there.

Memoization does not apply

Handlers are not part of the React tree, so fetch memoization does not happen. If two helpers in one handler call the same URL, it goes out twice unless you coordinate it yourself.

Handler or Server Action?

Server Actions are for mutations triggered from your own React UI; they are POST only and tied to a page. A route handler is a general HTTP endpoint. Use a handler when the caller is not your component tree, you need other methods (such as GET for a client library or OPTIONS for CORS), or you are receiving webhooks. For forms in your own UI, an action is usually less code. Whichever you choose, check authentication in it; both are reachable by direct requests.

The earlier client-side data fetching lesson used a handler as the endpoint for an SWR autocomplete; that is a typical fit.

What the video covers

Codevolution’s Next.js 15 tutorial covers route handlers by its chapters: an introduction, setting up your first handler, organizing handlers, handling route conflicts, and a summary with advanced examples. It was made for 15, so it predates the Cache Components behavior and the RouteContext helper described above.

Where this fits

Handlers receive every request that matches their path, but something may need to look at the request before it gets that far. Next: the proxy file.

Check yourself

  1. 01Why can't app/users/route.ts and app/users/page.tsx coexist?

    Each route.ts or page.tsx file takes over all HTTP verbs for its segment, so the two would conflict, and the fix is to put the handler on a different path such as app/api/users/route.ts.

  2. 02When should you prefer a route handler over a Server Action?

    When the caller is not your own React UI, such as a webhook, a mobile client, or a third party, or when you need a GET or other method, since actions are POST-only and designed for mutations from your own forms.

  3. 03With Cache Components on, what makes a GET route handler static or dynamic?

    It follows the same model as a page: if it touches no request data or uncached work it is prerendered at build time, and if it calls things like Math.random(), headers(), or a database it runs at request time unless that data is cached with use cache.

  4. 04How do you read a dynamic segment inside a route handler in Next.js 16?

    Await ctx.params, because params is a promise, typing the context with RouteContext for the route path.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark