Next.js/Routing/Lesson 11
Middleware — Intercepting Every Request for Auth, Redirects, and Header Manipulation
30 min·theory
This chapter
3/3
TypeScript
Middleware — Intercepting Every Request for Auth, Redirects, and Header Manipulation
💡 Why Learn This? — So You Don't Have to Write if(!session) in Every Page Component
🎯
Placing 'redirect to login if no session' code on every protected page is tedious — putting it in middleware in one place is all you need.
💼
Runs on the Edge Runtime → blocks requests before they reach page components. Faster response.
⚡
Use the matcher config to precisely control which routes the middleware applies to.
🔗
A/B testing, country-based redirects, bot blocking, adding response headers — all the logic needed just before routing.
📈
codemaster40's Next.js app also uses [`src/middleware.ts`](src/middleware.ts) to handle protected routes like `/dashboard` and `/admin`.
🏢 실무에서는
This project's middleware.ts does exactly that — it validates the session when entering personalized routes like `/dashboard`, `/bookmark`, and `/memo-notes`, and redirects to `/login?next=...` if there is none. Page components can then be written assuming a session always exists.
middleware.ts · matcher · NextResponse
1. Location and Signature
- ▸Runs on the Edge Runtime (some Node APIs are restricted).
- ▸Only activates for paths listed in matcher.
2. matcher Patterns
3. Four Key Behaviors
4. In Practice — Auth Middleware
5. Manipulating Response Cookies and Headers
6. Edge Runtime Constraints
- ▸Node-only modules like
fs,net, anddnsare not available. - ▸Response time should stay under 25ms (Vercel guideline).
- ▸No heavy database calls — only fast, lightweight checks.
💡 💡 5 Practical Middleware Tips
1. Negative lookahead patterns in matcher — expressing 'exclusions'
Prevents middleware from touching frequent static asset requests.
2. Edge Runtime constraints — no heavy database calls
Only fast operations like cookie validation or simple JWT decoding. Save real database queries for page components.
3. Setting headers in a single NextResponse.next() call
4. Setting response cookies
httpOnly + secure by default. SameSite=Lax is also recommended.
5. Debugging — console.log goes to server logs
console.log inside middleware appears in server logs (Vultr/Vercel), not in the browser console.
⚡ Try It Yourself — Middleware Behavior Simulation
Simulate how each request path is handled by middleware.
✏️ JS 코드
📟 Console output
▶ Press the Run button
⚠️ Runs in a browser sandbox — only console.log() is supported; alert/fetch are not.
Check Your Understanding
Which of the following can be configured using matcher in middleware.ts?
Read this first: Layout vs Template — State Persistence vs Remounting