Middleware serve a purpose of augmenting or modifying the request and response objects before the request reaches the actual page or API route handler.
There can be instances where you want to validate if user has valid token or check if the request has valid header from security perspective or update cookies, log some information about request or response, add CORS header to response. Middleware file is best place to perform such actions.
Middleware handles requests before they reach the route handlers. It allows you to add additional functionality or perform tasks such as modify response by redirecting, rewriting, modifying the headers.
How to create Middleware
1) Middleware needs to be created in root folder. Right click on src folder, create file named as middleware.ts
2) Add middleware function which accepts Next Request
3) Perform logic and return response as required
Now the question arises that is it possible to execute middleware based on some condition or for specific URLs only.
The answer is YES, you can add condition to check the request and its parameter and it also supports matcher config where you can specify paths, path with modifiers and regular expression:
Example:
export const config = { matcher: ‘/<desired path>/:path*’}