0% found this document useful (0 votes)
12 views7 pages

Getting Started - Route Handlers and Middleware - Next - Js

Uploaded by

q7qcyfbxwb
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views7 pages

Getting Started - Route Handlers and Middleware - Next - Js

Uploaded by

q7qcyfbxwb
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

2025/9/5 14:45 Getting Started: Route Handlers and Middleware | Next.

js

Menu

App Router Getting Started Route Handlers and Middleware

Copy page

Route Handlers and Middleware


Route Handlers
Route Handlers allow you to create custom request handlers for a given route using the
Web Request and Response APIs.

Good to know: Route Handlers are only available inside the app directory. They are the equivalent
of API Routes inside the pages directory meaning you do not need to use API Routes and Route
Handlers together.

Convention
Route Handlers are defined in a route.js|ts file inside the app directory:

app/api/route.ts TypeScript

https://nextjs.org/docs/app/getting-started/route-handlers-and-middleware 1/7
2025/9/5 14:45 Getting Started: Route Handlers and Middleware | Next.js

export async function GET(request: Request) {}

Route Handlers can be nested anywhere inside the app directory, similar to page.js and
layout.js . But there cannot be a route.js file at the same route segment level as
page.js .

Supported HTTP Methods


The following HTTP methods are supported: GET , POST , PUT , PATCH , DELETE , HEAD ,
and OPTIONS . If an unsupported method is called, Next.js will return a
405 Method Not Allowed response.

Extended NextRequest and NextResponse APIs


In addition to supporting the native Request and Response APIs, Next.js extends them
with NextRequest and NextResponse to provide convenient helpers for advanced use
cases.

Caching
Route Handlers are not cached by default. You can, however, opt into caching for GET
methods. Other supported HTTP methods are not cached. To cache a GET method, use a
route config option such as export const dynamic = 'force-static' in your Route
Handler file.

app/items/route.ts TypeScript

https://nextjs.org/docs/app/getting-started/route-handlers-and-middleware 2/7
2025/9/5 14:45 Getting Started: Route Handlers and Middleware | Next.js

export const dynamic = 'force-static'

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 })


}

Good to know: Other supported HTTP methods are not cached, even if they are placed alongside a
GET method that is cached, in the same file.

Special Route Handlers


Special Route Handlers like sitemap.ts , opengraph-image.tsx , and icon.tsx , and
other metadata files remain static by default unless they use Dynamic APIs or dynamic
config options.

Route Resolution
You can consider a route the lowest level routing primitive.

- They do not participate in layouts or client-side navigations like page .


- There cannot be a route.js file at the same route as page.js .

Page Route Result

app/page.js app/route.js Conflict

app/page.js app/api/route.js Valid

app/[user]/page.js app/api/route.js Valid

Each route.js or page.js file takes over all HTTP verbs for that route.

https://nextjs.org/docs/app/getting-started/route-handlers-and-middleware 3/7
2025/9/5 14:45 Getting Started: Route Handlers and Middleware | Next.js

app/page.ts TypeScript

export default function Page() {


return <h1>Hello, Next.js!</h1>
}

// Conflict
// `app/route.ts`
export async function POST(request: Request) {}

Read more about how Route Handlers complement your frontend application, or explore
the Route Handlers API Reference.

Route Context Helper


In TypeScript, you can type the context parameter for Route Handlers with the globally
available RouteContext helper:

app/users/[id]/route.ts TypeScript

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 })
}

Good to know
- Types are generated during next dev , next build or next typegen .

Middleware
Middleware allows you to run code before a request is completed. Then, based on the
incoming request, you can modify the response by rewriting, redirecting, modifying the
request or response headers, or responding directly.

https://nextjs.org/docs/app/getting-started/route-handlers-and-middleware 4/7
2025/9/5 14:45 Getting Started: Route Handlers and Middleware | Next.js

Use cases
Some common scenarios where Middleware is effective include:

- Quick redirects after reading parts of the incoming request


- Rewriting to different pages based on A/B tests or experiments
- Modifying headers for all pages or a subset of pages

Middleware is not a good fit for:

- Slow data fetching


- Session management

Using fetch with options.cache , options.next.revalidate , or options.next.tags ,


has no effect in Middleware.

Convention
Create a middleware.ts (or .js ) file in the project root, or inside src if applicable, so
that it is located at the same level as pages or app .

Note: While only one middleware.ts file is supported per project, you can still organize your
middleware logic into modules. Break out middleware functionalities into separate .ts or .js
files and import them into your main middleware.ts file. This allows for cleaner management of
route-specific middleware, aggregated in the middleware.ts for centralized control. By enforcing
a single middleware file, it simplifies configuration, prevents potential conflicts, and optimizes
performance by avoiding multiple middleware layers.

Example

middleware.ts TypeScript

import { NextResponse } from 'next/server'


import type { NextRequest } from 'next/server'

// This function can be marked `async` if using `await` inside


export function middleware(request: NextRequest) {
return NextResponse.redirect(new URL('/home', request.url))
}

// See "Matching Paths" below to learn more

https://nextjs.org/docs/app/getting-started/route-handlers-and-middleware 5/7
2025/9/5 14:45 Getting Started: Route Handlers and Middleware | Next.js
export const config = {
matcher: '/about/:path*',
}

Read more about using middleware , or refer to the middleware API reference.

API Reference
Learn more about Route Handlers and Middleware

route.js middleware.js
API reference for the route.js special file. API reference for the middleware.js file.

Backend for Frontend


Learn how to use Next.js as a backend
framework

Previous Next
Metadata and OG images Deploying

Was this helpful?

Resources More About Vercel Legal

Docs Next.js Commerce Next.js + Vercel Privacy Policy


Support Policy Contact Sales Open Source Software
Learn Community GitHub
Showcase GitHub Bluesky
https://nextjs.org/docs/app/getting-started/route-handlers-and-middleware 6/7
2025/9/5 14:45 Getting Started: Route Handlers and Middleware | Next.js

Blog Releases X
Team Telemetry
Analytics Governance
Next.js Conf
Previews

Subscribe to our newsletter

Stay updated on new releases and


features, guides, and case studies.

[email protected] Subscribe

© 2025 Vercel, Inc.

https://nextjs.org/docs/app/getting-started/route-handlers-and-middleware 7/7

You might also like