What’s a Middleware?
“Middleware enables you to use code over configuration.”
NextJS Docs
What that quote form NextJS docs means is that you can run a bunch of code before a request is completed in NextJS. This freedom gives you a bit of flexibility since there are a few ways to use it to your advantage.
How to use Middleware to your advantage?
Based on the request you receive from the user, you can a run some code and change the server response. You could rewrite or redirect or add headers or even just display a bunch of simple HTML code.
You could also use that as a mean to save the request you receive from the user — basically user tracking that you see in many social media sites. If you pay attention to the URL while making a request in a social media site, you’ll notice that change in a matter of seconds and a redirect to the clicked link.
How to use Middleware in code?
Follow these simple steps to create a middleware in your NextJS project.
1. Install the latest version of NextJS using the following code:
npm install [email protected]
2. Create a _middleware.ts
file
Go to your “pages” directory in your NextJS project and create a _middleware.ts
file in that “pages” directory.
3. middleware function
In the third and the final step, add the middleware function to the file created in the previous step.
For e.g. this standard Web API Response:
// pages/_middleware.ts
import type { NextFetchEvent, NextRequest } from 'next/server'
export function middleware(req: NextRequest, ev: NextFetchEvent) {
return new Response('Hello, world!')
}
References
API functions how to Middleware web