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

References

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 How to uninstall Cocoapods from the Mac OS? #6 PHP Login System using PDO Part 1: Create User Registration Page

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
The 7 Security Objectives of Any Organization for IT and Network SecurityMiscellaneousHow to reference an aliased column in the WHERE clause?SQL/MySQLHow to float an image around texts?CSSHow to create a Progress Bar using JavaScript?JavaScriptHow to invalidate all existing cookies using Security Keys in WordPress?WordPressHow to add menu to your WordPress theme?WordPress