Back to Mastery Path
Routing

Middleware

Middleware allows you to run code before a request is completed, letting you modify the response, redirect users, or check auth.

Interactive Simulation Engine

Edge Middleware Simulation

Gatekeeping at the Edge

Public Request
THE EDGE
MIDDLEWARE.TS
Internal Server

Click a button to simulate a user request passing through Middleware.

Executable Code Workbench
page.tsx
Live Code Editor
1import { 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 Live Code Workbench above to simulate execution."