Book a consultation
Back to blog
September 13th, 2022

Next.js Middleware: Everything You Need to Know

by Luca Reale
cropped-luca.png

Next.js is a JavaScript framework that lets you accomplish server-side rendering and build static web applications using React. 

In 2021, with version 12, Next.js introduced one of its most exciting new features: Next.js Middleware.

What is Next.js Middleware?

The clue is right there in the name. Next.js Middleware creates functions that execute between two processes. For example, you could use it to run functions:

  • After a user’s request is made 
  • Before the user’s request is completed

How Does Next.js Middleware Work?

With Middleware, you can run code before a request is completed and then, based on the incoming request, modify the response returned to the user by rewriting, redirecting, or even adding headers to the response.

This gives you greater flexibility and control over your site or application. For example, you can use Middleware to block certain users from your site or serve visitors personalised, location-specific content (More on this later).

Some examples where developers can use Next.js Middleware include:

  • Authentication
  • Serving localised pages
  • Handling unsupported browsers
  • Protection from bots
  • Redirects and rewrites
  • A/B tests
  • Server-side analytics

Is There a Difference Between Middleware and API Routes?

Yes. Middleware has no cold boot and is designed to deploy on the Edge network and make use of Edge functions. Edge functions deliver code to multiple server locations around the world to speed up content delivery. 

Next.js’ API routes, on the other hand, are designed to be hosted on a single node server located in one place. 

When to Use Next.js Middleware

Middleware needs to return a response in less than 1.5 seconds. So, you should only use it in cases where a small amount of processing is required; otherwise, the request will time out. Some applications of Next.js Middleware include the following:

Geolocation

The Middleware NextRequest API has geographic information available in the geo key. You can use this information to serve users pages with localised content.

For example, if you’re creating a site for a shoe company with branches in multiple regions, you can show trending shoes or exclusive offers close to the user’s location.

Security

You can use the cookies key available via the NextRequest API to set cookies using NextRequest API. You can then authenticate users on your site using the specified cookies.

Other security functions include blocking bots, users, or regions from accessing your site. To do this, you can simply rewrite the request to send them to a “blocked page” or a 404 error.

A/B Testing

A/B testing is a user testing process where you serve two different versions of a site to different visitors to see which version gets the best response.

Before Middleware was introduced, developers doing A/B testing on static sites used to show different versions of site pages by processing user requests on the client side. This meant the process was slow, and sometimes resulted in layout shifts in the sites.

However, with Middleware, user requests are processed server-side, making it much faster, and avoiding layout shifts. A/B testing with Middleware is done by using cookies to place users in “buckets”. Then, the servers will redirect users to the A or B page, depending on the bucket they’re grouped in.

How to Use Next.js Middleware

To add Middleware to your web app, you need to create a “middleware.ts” or.js file at the root of your project. The file should be located at the same level as your page’s directory. In the following example, we created a middleware.ts file.

Installation

  • To use Middleware, you need to install the latest version of Next.js using the following code.
installing latest version of next.js with npm

With npm: npm install next@latest

With Yarn: add next@latest

  • Next, create a _middleware.ts file in your pages directory.
  • Finally, you can export a Middleware function from the middleware.js file you created. In the following example, we redirect a user to a new URL.
exporting middleware functions from middleware.js file
// middleware.ts
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
// This function can be marked `async` if using `await` inside
export function middleware(request: NextRequest) {
  return NextResponse.redirect(new URL('/about-2', request.url))
}
// See "Matching Paths" below to learn more
export const config = {
  matcher: '/about/:path*',
}

An example of Middleware in action

The following is an example of a simple Middleware function you can use to show a user their operating system.

middleware function code
const Middleware = (req, ev) => {
  return new Response(req.ua.os.name);
};

export default middleware;

Now, when a user opens the page, this function will display the user’s operating system.

Summary

Overall, Next.js Middleware is a nifty tool that gives developers more flexibility when implementing custom functionality. And while it does have its limitations, it’s still a great way to deliver dynamic and personalised content to end-users quickly. 

For more tips and tutorials on web design, development, and more, have a read through the rest of our blog!

Category:
cropped-luca.png
Luca Reale
Content writer

Our newsletter

Our links

Our Work

Our Content

Social

Copyright © 2022 Drewl. All rights reserved