Routing

Route Handlers in Next.js

Convention of Route Handlers

  • Route handlers are like api routes in pages directory.
  • 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 })
}
```import { ArticleLayout } from '@/components/ArticleLayout'
import { DocsLayout } from '@/components/learned/DocsLayout'
import { DocsLayout } from '@/components/learned/DocsLayout'
import { DocsLayout } from '@/components/learned/DocsLayout'
import { DocsLayout } from '@/components/learned/DocsLayout'
import { DocsLayout } from '@/components/learned/DocsLayout'

Select any topic to explore👇

JsDocs

Master JavaScript here.

Writing is in progress🧑‍💻

TsDcos

Kill TypeScript here.

Writing is in progress🧑‍💻

ReactDocs

Your don't know React.js yet.

Writing is in progress🧑‍💻

NextDocs

Learn more about Next.js here.

Writing is in progress🧑‍💻

Disclaimer!

This is currently a work in progress, so I'd greatly appreciate it if you could let me know should you encounter any mistakes. Thank you! 🙏
Previous
Get Started