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.
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
Middleware is defined in a file named middleware.js or middleware.ts at the root of the project.
You can control where middleware runs using matchers.
This middleware will apply only to:
| Feature | Redirect | Rewrite |
|---|---|---|
| URL change | Yes | No |
| Browser aware | Yes | No |
| Use case | Auth, SEO | Internal routing |
Runs on Edge Runtime
No access to Node.js APIs
Cannot access databases directly
Must be fast and lightweight
Authentication & authorization
Role-based access
Geo-based routing
Maintenance mode
A/B testing
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.
Take quizzes related to this topic and see where you stand!
Start Quiz Now