Middleware in Next.js
In Next.js, Middleware allows you to run logic before a request is completed, enabling powerful features like authentication, redirects, and request modifications.
🧠How Middleware Works:
- Middleware runs before the request reaches a page or an API route.
- It can inspect and modify the request, perform checks (like authentication), or rewrite/redirect responses.
Example of Middleware for authentication:
- In this example, the middleware checks for a token in cookies. If it's missing, the request is blocked with a 401 response.
In short:
- Middleware runs code before routing completes.
- Great for auth checks, logging, redirects, and other pre-processing logic.