Middleware
What is middleware
Middleware refers to functions that intercept and process incoming requests before they reach their final route handlers.
- e.g. authentication to verify a user's identity before granting access.
Then, based on the incoming request
, you can modify the response
by rewriting, redirecting, modifying the request or response headers, or responding directly
- Middleware runs before
cached content
androutes
are matched.
For example - You can set CORS headers
in Middleware
to allow cross-origin requests.
- including preflight and simple requests.
Where to Place it
Use the file middleware.ts
in the root of your project to define Middleware
- For example, at the same level as
pages
orapp
, or insidesrc
if applicable
matcher
matcher
allows you to filter Middleware
to run on specific paths
- you can also use regex
export const config = { matcher: [ '/about/:path*', '/dashboard/:path*' ], }