Authentication
Middleware
Learn route-level authentication gates in Next.js middleware and proxy files, including matcher patterns and defense-in-depth rules.
## 1. Learning Objectives
By the end of this lesson, you will be able to use middleware/proxy for coarse route protection, configure matchers, redirect unauthenticated users, and explain why middleware is not a substitute for server-side authorization.
Difficulty: Intermediate.
## 2. Prerequisites
- Auth.js session checks.
- JWT/session basics.
- Next.js routing.
## 3. Overview
Middleware is request interception that runs before a matched route. In Next.js 15 and earlier, the file is `middleware.ts`; in newer Next.js versions this convention has moved toward `proxy.ts`, but the teaching goal is the same: perform lightweight request gating before route rendering.
## 4. Why This Topic Matters
Middleware can keep unauthenticated users away from protected route sections early. It improves user flow, but sensitive APIs and mutations still need authorization checks in the final server code path.
## 5. Real-World Analogy
Middleware is the building lobby guard. The guard can redirect visitors before they reach a floor, but each secure room should still verify access before opening.
## 6. Core Concepts
| Concept | Meaning |
|---|---|
| Middleware/proxy | Request interception before route handling. |
| Matcher | Pattern list deciding which paths run the gate. |
| Redirect | Send unauthenticated users to sign in. |
| Rewrite | Internally route a request elsewhere. |
| Defense in depth | Multiple checks at route gate and data access layers. |
## 7. Syntax & API Reference
In newer Auth.js examples for Next.js 16+, the same idea may be implemented with `proxy.ts` and `export { auth as proxy }`.
## 8. Visual Diagram
## 9. Live Example - Full Working Code
What just happened? Requests to `/account` and `/billing` are gated before route rendering.
## 10. Interactive Playground
Try this:
- Add a matcher for `/dashboard/:path*`.
- Redirect anonymous users to `/login`.
- Add a server-side role check inside the dashboard page too.
## 11. Common Mistakes
| Mistake | Why It Happens | Correct Approach |
|---|---|---|
| Protecting every asset path | Matcher is too broad. | Exclude static assets and public paths. |
| Doing heavy database work in middleware | Middleware runs very frequently. | Keep it lightweight. |
| Relying on middleware alone | It feels like a central gate. | Re-check auth near protected data and mutations. |
## 12. Best Practices
- Use middleware/proxy for coarse route gating.
- Keep logic fast and side-effect free.
- Configure matchers carefully.
- Preserve the intended destination in redirects.
- Revalidate authorization in Server Components, Server Actions, and Route Handlers.
## 13. Browser Compatibility
| Feature | Browser Impact | Notes |
|---|---|---|
| Redirect | Standard HTTP | Browser follows login redirect. |
| Cookie read | Request-side | Depends on cookie settings. |
| Matcher | Server/framework feature | No browser dependency. |
## 14. Interview Questions
**Easy:** What does middleware do?
Answer: It intercepts matched requests before route handling.
**Medium:** What is a matcher?
Answer: A path pattern that controls which requests run middleware/proxy code.
**Hard:** Why should middleware not be the only auth layer?
Answer: Sensitive operations can be reached through APIs, actions, or internal paths, so authorization must be verified close to data access.
## 15. Debugging Exercise
Bug report: "All images and static files redirect to login."
Solution
The matcher is too broad. Exclude `_next/static`, `_next/image`, favicon, and other public asset paths.
## 16. Practice Exercises
- Easy: Gate `/dashboard`.
- Medium: Preserve `next` redirect path.
- Hard: Combine route gating with server-side role checks.
## 17. Scenario-Based Challenge
An admin API is protected by middleware, but a user can still mutate data through a Server Action. What is missing?
Walkthrough
The Server Action needs its own session and role checks. Middleware is a route gate, not the final authorization authority.
## 18. Quick Quiz
1. What file name does Next.js 15 commonly use? Answer: `middleware.ts`.
2. What newer convention appears in Next.js 16 docs? Answer: `proxy.ts`.
3. What controls matched paths? Answer: `config.matcher`.
4. Should middleware do heavy DB work? Answer: No.
5. Should data access re-check auth? Answer: Yes.
## 19. Summary & Key Takeaways
- Middleware/proxy gates matched requests early.
- Matchers must be precise.
- Keep logic lightweight.
- Redirect unauthenticated users before rendering protected pages.
- Always re-check authorization near sensitive server logic.
## 20. Cheat Sheet
| Need | Middleware Fit |
|---|---|
| Redirect anonymous dashboard visits | Strong |
| Validate admin write permission | Not enough alone |
| Exclude static assets | Matcher config |
| Read full database profile | Avoid in middleware |
| Preserve destination | Add `next` query param |
## 21. Further Reading
- Auth.js Docs: Protecting Resources.
- Next.js Docs: Middleware/Proxy file convention.
- Next.js Docs: Redirecting.
## 22. Next Lesson Preview
Chapter 5 is complete. Next, you will move into SEO with the Metadata API.