Routing

Route Handlers

Route Handlers let you set up custom Request handlers for specific routes using Web Request and Response APIs.

NOTE!

Route handlers are like api routes in pages directory.

Convention of Route Handlers

  • They are defined with route.js/ts files.
  • They can be nested but can't be sibling of a page.js/ts.
  • They support all 7 HTTP methods (GET,POST,PATCH,PUT,DELETE,HEAD,OPTIONS).
  • They have NextRequest and NextResponse helper objects for advances use cases.
  • They do not participate in layouts or client-side navigation like pages.

Behavior

Route Handlers are cached only when using the GET method with the Response object. We must revalidate our cached data after its mutation.

// app/items/route.ts
export async function GET() {
  const res = await fetch('https://data.mongodb-api.com/...', {
    headers: {
      'Content-Type': 'application/json',
      'API-Key': process.env.DATA_API_KEY,
    },
  })
  const data = await res.json()

  return Response.json({ data })
}
Previous
Get Started