Table of contents
1.
Introduction
2.
Next.js middlewares
3.
How to implement middleware in next.js?
4.
What About API Routes?
5.
Authenticating in middleware
5.1.
Redirect vs. Rewrite
6.
Rewriting with authentication
6.1.
Won’t this be slow like SSR?
7.
JWT (JSON Web Tokens) User Authentication in Next.js Web Application
8.
The Limitations Of Middlewares
9.
Frequently Asked Questions
9.1.
Why NextJS is used?
9.2.
What are the three types of middleware?
9.3.
What are API routes next JS?
10.
Conclusion
Last Updated: Mar 27, 2024
Easy

Middlewares in next.js

Author Shivani Singh
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Before venturing into Middlewares in next.js, let's first understand the term. The term "Middleware" is just not a new one in the field of computer science. It is frequently used to describe a piece of software that join different devices. You might call it "software glue," and that's primarily how Next.js' middleware works. Middleware offers the chance for developers. You use middleware to modify request responses and redirect users from one route to another. Middleware is a function that can be attached to routes and run before the route. To put it another way, it runs "in the middle." This can be used to see if a user is authorized or has the necessary roles to visit a route.

These are characteristics you'd want on various routes, and middleware makes it simple to write a function once and use it on multiple routes (Don't Repeat Yourself). But how can you construct middleware in Next.js? Let us see this in detail. 

Next.js middlewares

Middleware in Next.js is a simple piece of code that allows us to alter the reaction to a request before it completes. or, to put it another way, Next.js' middleware enables us to write functions that run after a user's request is made but before the request is completed — in the middle of the two processes. We can rewrite, redirect, add headers, or even stream HTML based on a user's request. Middleware in Next.js works in a limited runtime known as the "Edge Runtime." The runtime-executed code has access to a set of regular Web APIs. 

Image source: middleware

How to implement middleware in next.js?

The process of implementing middleware is simple. 

Requirement for middleware

You are using the most current edition of next.js. It's an important step.

Steps:

  1. Make a middleware file.
  2. Install typescript 
  3. Under-construction next.js page

 

Keep this in mind whenever you make a change to the middleware file. Your nextjs server is restarted once more.

  1. Create middleware file

The first step is to create a file called _middleware.ts in the nextjs pages folder.

Image source: middleware file

After successfully creating the _middleware.ts file. Now copy the typescript code below and paste it into the _middleware.ts file.

import type { NextFetchEvent, NextRequest } from "next/server";
import { NextResponse } from "next/server";

// In rewrite method you pass a page folder name(as a string). which // you create to handle underConstraction  functionalty.
export function middleware(req: NextRequest, ev: NextFetchEvent) {
 return NextResponse.rewrite("/underConstraction");
}
You can also try this code with Online Javascript Compiler
Run Code

 

In middleware, NextResponse has four ways.

  • The redirect() method transfers requests from one route to another.
  • rewrite() is a function that allows you to rewrite an existing response.
  • The next method is used to pass the middleware network from one middleware to the next.
  • JSON response or data is returned by the json() function.

 

Choose from the above method according to your needs and requirements. We will go with the rewrite method.

2. Install typescript 

Next typescript and @types/react are both npm packages that must be installed in the project folder.

yarn add --dev typescript @types/react
You can also try this code with Online Javascript Compiler
Run Code

 

The Nextjs middleware fails to run with typescript, resulting in a terminal error. You can skip this section if you're all already using typescript.

3. Under-construction next.js page

Create a page in the nextjs pages folder as the final step. You create an under-construction page in the nextjs page folder with whatever name you like. Assume the file name for your underconstruction pages is different. Then specify the rewrite("your-custom-path") method on the inside.

Image source: nextjs

Now you need some piece of code into your under-construction file under the nextjs pages folder, which you recently created.

You run the dev server with NPM and yarn after pasting the code.

npm run start
or
yarn start
ytd34
You can also try this code with Online Javascript Compiler
Run Code

 

Now you're in the midst of a construction project. Users always view the under-contraction page on your website, regardless of how much traffic it receives.

What About API Routes?

As we progress through this blog, you may notice that middleware sounds oddly similar to Next.js' API routes, which have been around for a long. Individual requests are made to API routes in the more constrained runtime of middleware functions, whereas middleware functions work in the time between a user's request for a page and that page's rendering.

Middleware can also be scoped to many pages, permitting you to avoid duplicating code.

The main technical difference between the two is that Next.js' API routes are designed to be deployed on a single node server in a single location, whereas Middleware functions are designed to be deployed on the "edge," which is primarily a marketing term for deploying code in different locations around the world. Along with the physical distance difference, the "edge" is often related to proactive caching and fast cache invalidation, both of which reduce wasteful work.

The goal is to get as fast as possible. Because a server's response time is faster when the user is closer to it, those speeds are only available to a subset of your users when you just have one server. However, if your code is deployed in numerous locations, more people will be able to use it.

Finally, Middleware is built with no cold boot time in mind. The boot time of an API route is a major source of sluggish responses.

Authenticating in middleware

We know that the issue with SSR is that it is too slow and that the issue with ISR is that it is impossible to validate. We can address this issue using NextJS Middleware by selecting a different rendering approach based on the customer's authentication headers.

Many hosts, such as Netlify and Cloudflare Workers, can be deployed with middleware. A Javascript function that runs before your website is sent to a user is known as middleware. It's located in the /pages folder and can be found inside any of your folders. It has exposure to a user's cookies as well as other data such as geolocation information.

This function returns precisely what the user sees – we could return a direct Response object, or we might redirect to another webpage, or we could do something different like rewriting the URL.

Redirect vs. Rewrite

The end-user will be able to see a redirect. That is, a consumer who is redirected from /oldpage to /newpage will see mywebsite.com/newpage in their browser

Behind the scenes, a rewrite is going to take place.

Rewriting with authentication

We can read user cookies using Middleware. We can provide a fast, public-only page using ISR, and a dynamic, authenticated private page with SSR that accesses the database.

we can ask via Middleware "Does this user appear to be authenticated?" If they say no, serve them the cached page. If they say yes, show them the sluggish SSR page, which will authenticate them fully.

Won’t this be slow like SSR?

Middleware, at least when deployed with Vercel, runs on edge workers and uses a trimmed-down set of Javascript libraries. Rather than starting a new Node instance, it executes V8 directly, resulting in startup speeds of less than 1 millisecond.

The middleware adds overhead in the tens of milliseconds (approx) when all you're doing is checking a cookie like this and proceeding directly to the cached web page if we have no grounds to suppose they're authenticated.

JWT (JSON Web Tokens) User Authentication in Next.js Web Application

JWT (JSON Web Tokens) is a protocol for exchanging information between a client and a server using an encoded token. For many developers, JWT may be used in any programming language environment in their applications. 

Image source: simple flow JWT

The Next.js feature provides a fantastic API that lets you leverage request and response in client-server communication. From a default Next.js project template, here's an example of a request and response in./pages/api/hello.js.

export default (req, res) => {
  res.statusCode = 200
  res.json({ name: 'John Doe' })
}
You can also try this code with Online Javascript Compiler
Run Code

The Limitations Of Middlewares

  • EXECUTION TIME (VERCEL SPECIFIC)
    A middleware function can run for up to thirty seconds, but it must produce a response in one and a half seconds.  This implies that your function should respond as soon as feasible, allowing you to continue working on other tasks in the background if necessary. If you wanted to do server-side analytics, for example, you could extract the data you need, return a response, and then contact your database to log the data after providing the response.
     
  • FUNCTION SIZE (VERCEL SPECIFIC)
    A Middleware function can only be 1MB in size, including all other code that comes with it. Although most use cases won't necessitate such a hefty code bundle, that's something to keep an eye on.
     
  • NATIVE NODE.JS APIS AREN’T SUPPORTED 
    Middleware functions, unlike the rest of Node.js' server-side code, do not run through Node.js (such as API Routes). Reading and writing to the filesystem is one of the main problems that prevent Middleware functionalities from working. This means that JavaScript plugins that depend on native Node.js APIs are also incompatible.
     
  • ES MODULES ONLY
    Within middleware, Node Modules can be used, but they must be ES Modules. While there is an increasing trend in the ecosystem to use ES Modules instead of CommonJS, many packages still use CommonJS or rely on other packages via CommonJS.
     
  • NO STRING EVALUATION
    The runtime does not support the use of JavaScript's eval or new Function(evalString).

Frequently Asked Questions

Why NextJS is used?

This enables developers to create full-stack apps with a single language and toolset while also providing a better user experience, which often results in a faster initial page render. Next. js became in popularity because it made it easier to create full-stack applications with React.

What are the three types of middleware?

Application-specific, information-exchange, and management and support middleware are the three primary categories of middleware functions.

What are API routes next JS?

API routes are a way to use Next. js to create an API. Any file in the pages/api subdirectory is linked to /api/* and is considered as an API endpoint rather than a page. They're exclusively server-side bundles, therefore they won't add to the size of your client-side bundle.

Conclusion

To sum up, we discussed the concept of middleware in this blog and then observed middleware in next.js. We also talked about how to construct middleware and the importance of API routes. After that, we looked at middleware authentication, the distinction between redirect and rewrite, and rewriting with authentication. We also looked at a JWT user authentication example in next.js and lastly discussed the limits of middleware.

Refer to our guided paths on Coding Ninjas Studio to upskill yourself in Data Structures and AlgorithmsCompetitive ProgrammingJavaScriptSystem Design, and many more! If you want to test your competency in coding, you may check out the mock test series and participate in the contests hosted on Coding Ninjas Studio! But if you have just started your learning process and looking for questions asked by tech giants like Amazon, Microsoft, Uber, etc; you must have a look at the problemsinterview experiences, and interview bundle for placement preparations.

Nevertheless, you may consider our paid courses to give your career an edge over others!

Do upvote our blogs if you find them helpful and engaging!

Happy Learning!

Live masterclass