Middleware allows you to run code before a request is completed, letting you modify the response, redirect users, or check auth.
Interactive Concept Walkthrough
Edge Middleware Simulation
Gatekeeping at the Edge
Public Request
THE EDGE
MIDDLEWARE.TSInternal Server
Click a button to simulate a user request passing through Middleware.
Editable Code Example
page.tsx
Editable Code Example1import { NextResponse } from 'next/server'
2import type { NextRequest } from 'next/server'
3
4export function middleware(request: NextRequest) {
5 return NextResponse.redirect(new URL('/home', request.url))
6}Mental Model
A gatekeeper. Every request passes through Middleware first. It decides if you can enter or if you need to be sent elsewhere.
Why This Exists
For global logic like authentication, internationalization (i18n), and path rewriting.
Critical Note
"Developers often confuse this pattern with traditional client React. Use the editable code example above to follow the walkthrough."