Next.js Middleware enables running code on the edge before a request is completed. Located at the root of the project as middleware.ts, it allows intercepting incoming HTTP traffic to perform route authentication protection, URL redirects/rewrites, header manipulation, and geolocation routing.
Middleware runs on the lightweight Vercel Edge Runtime before cached content or route handlers execute:
How data and code flow step-by-step
Create middleware.ts in your project root (or inside src/):
NextResponse.redirect(url)): Returns an HTTP 307/308 status code, updating the user's browser address bar to the new URL.NextResponse.rewrite(url)): Serves content from a different destination URL while preserving the original URL in the user's browser address bar (useful for multi-tenant subdomains or A/B testing).middleware.ts file be located in a Next.js application?NextResponse.redirect() and NextResponse.rewrite()?matcher array in export const config recommended for Middleware?middleware.ts?Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Test your understanding of this lesson with 5 questions. Each question has one correct answer.
Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.