Yogesh Chauhan's Blog

Middleware in NextJS

in NextJS on April 7, 2022

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!')


Middleware NextJS Docs

Middleware API reference.

Most Read

#1 Solution to the error “Visual Studio Code can’t be opened because Apple cannot check it for malicious software” #2 How to add Read More Read Less Button using JavaScript? #3 How to check if radio button is checked or not using JavaScript? #4 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to uninstall Cocoapods from the Mac OS?

Recently Posted

#Apr 8 JSON.stringify() in JavaScript #Apr 7 Middleware in NextJS #Jan 17 4 advanced ways to search Colleague #Jan 16 Colleague UI Basics: The Search Area #Jan 16 Colleague UI Basics: The Context Area #Jan 16 Colleague UI Basics: Accessing the user interface
You might also like these
How to change perception and behavior of a person for acceptance of new systems?MiscellaneousHow to list all PHP variables to debug the script?PHPForcing the domain to serve securely using HTTPSMiscellaneousWhat is ECMAScript?JavaScriptWhat are Conditional Tags in WordPress?WordPressEverything you need to know about ANY, SOME and ALL Operators in PostgresPostgres