Concept Flow - Why middleware intercepts requests
Incoming Request
Middleware Intercepts
Modify Request
Pass to Next
Final Handler (Page/API)
Middleware catches requests first to check or change them before they reach the final page or API.
import { NextResponse } from 'next/server'; export function middleware(request) { if (!request.nextUrl.pathname.startsWith('/admin')) { return NextResponse.next(); } return NextResponse.redirect(new URL('/login', request.url)); }
| Step | Request Path | Condition | Action | Result |
|---|---|---|---|---|
| 1 | /home | Does path start with '/admin'? No | Allow request to continue | Request passes to final handler |
| 2 | /admin/dashboard | Does path start with '/admin'? Yes | Redirect to '/login' | Response sent with redirect |
| 3 | /admin/settings | Does path start with '/admin'? Yes | Redirect to '/login' | Response sent with redirect |
| 4 | /about | Does path start with '/admin'? No | Allow request to continue | Request passes to final handler |
| Variable | Start | After Step 1 | After Step 2 | After Step 3 | After Step 4 |
|---|---|---|---|---|---|
| request.nextUrl.pathname | /home | /home | /admin/dashboard | /admin/settings | /about |
| condition (startsWith '/admin') | N/A | false | true | true | false |
| action taken | N/A | next() | redirect('/login') | redirect('/login') | next() |
Middleware in Next.js runs before pages or APIs. It checks or changes requests. It can allow, redirect, or block requests. Use conditions on request paths. Return NextResponse.next() to continue. Return NextResponse.redirect() to redirect.