Next.js Middleware
15 June 2025 (Updated 15 June 2025)
On this page
What is a middleware?
Middleware lets you run code before an HTTP request completes. For example, you might want to:
- Redirect the user based on their authentication status
- Add additional HTTP request headers based on the user’s user agent or IP address.
- Redirect to different pages based on A/B tests.
Add a middleware
Add a middleware.ts
file in the root of your project (src/app
or app
). For example:
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
export const config = {
matcher: '/about/:path*',
}
Tagged:
Next.js