Middleware in Next.js
⏱ Estimated reading time: 2 min
Middleware in Next.js allows you to run code before a request is completed. It is mainly used for authentication, authorization, redirects, rewrites, and request handling at the edge.
1. What is Middleware?
Middleware runs before routing happens.
It executes on the Edge Runtime, which makes it fast and lightweight.
Common uses:
-
Authentication checks
-
Route protection
-
Redirects and rewrites
-
Localization (i18n)
-
Logging and headers
2. Creating Middleware
Middleware is defined in a file named middleware.js or middleware.ts at the root of the project.
Basic Example
3. Protecting Routes (Authentication Example)
4. Matching Specific Routes
You can control where middleware runs using matchers.
This middleware will apply only to:
5. Reading Cookies and Headers
Cookies
Headers
6. Rewriting URLs
7. Redirect vs Rewrite
| Feature | Redirect | Rewrite |
|---|---|---|
| URL change | Yes | No |
| Browser aware | Yes | No |
| Use case | Auth, SEO | Internal routing |
8. Middleware Limitations
-
Runs on Edge Runtime
-
No access to Node.js APIs
-
Cannot access databases directly
-
Must be fast and lightweight
Use Cases
-
Authentication & authorization
-
Role-based access
-
Geo-based routing
-
Maintenance mode
-
A/B testing
Conclusion
Middleware in Next.js is a powerful feature for controlling requests before they reach your routes. It helps improve security, performance, and user experience when used correctly.
Register Now
Share this Post
← Back to Tutorials