Introduction to Next.js 12 Middleware and Edge Functions

Introduction to Next.js 12 Middleware and Edge Functions

Next.js 12.0, Vercel's biggest ever release was announced at Next.js Conf in October last year. A Rust compiler was added to speed up build times, support for React 18, Image optimization, more SEO support, etc. along with a very interesting feature I'd like to discuss, Next.js Middleware.

What is a Middleware?

image.png Middleware by itself is nothing new to web development. In general, Middleware is software that is meant to comprise services that make an application or a stream of applications more efficient.

In the context of Middleware in APIs, Middleware in Express.js for instance is a function or a set of functions with access to the request and response that runs before a request is made. Middleware can be used in different layers of an application.

Next.js Middleware

image.png Middleware in Next.js enables you to run code over configuration, i.e. provide a lot more server-side control before a request is complete. Requests can be used for validation, logging, etc. and the subsequent responses can be rewritten or a user can be redirected, etc. React Server components are in Alpha as of now and so is HTML streaming which is possible with middleware.

Writing Next.js Middleware

To write middleware in Next.js, you simply have to create a file named _middleware.js (or ts for TypeScript) anywhere inside the pages folder of the project, the syntax of which looks something like this:

/* pages/_middleware.js */
/* Will be executed on all routes inside pages */

import { NextResponse } from "next/server";
export function middleware(req,ev) {
  return NextResponse.next(); // Continues the cycle
}

Keep in mind that the middleware is triggered on all pages which are inside the same folder as the middleware file.

Consider this file structure for instance -

- package.json
- /pages
    index.js
    auth.js
    /account
      _middleware.js
      dashboard.js
      edit_profile.js
      /videos
        saved_videos.js

Here, the middleware was created in the account folder. This means that all routes under account upon request will trigger the middleware function (i.e. dashboard, edit_profile and videos/saved_videos) however, routes index and auth will be unaffected.

In the case of subdirectories with nested routes, middleware runs from the top down. Here's an example from the documentation image.png

Edge Functions

image.png

The functions that are deployed globally on Vercel's Edge Network are called Edge Functions. Any middleware code in your Next.js Application upon deployment to Vercel is deployed to this Network, close to your visitors' origin.

This moves a lot of server-side logic away from the actual server that runs the application, thus making it significantly faster.

The NextRequest Object, which is an extension of the native Request interface comes with added properties like cookies, geo (for the geographical location with country code, region and city) and IP address which can create a multitude of use cases.

Use Cases

image.png The concept of Middleware itself brings a lot of interesting uses to the application. Next.js Middleware can be used in Authentication, handling cookies, API rate limiting, rewriting responses, Security, Testing, Crypto, Geolocation-based functions and much much more.

This was just a brief idea of what comes with Next.js Middleware. Let me know in the comments if you'd like more threads on this and its implementations. Thank you for reading :)

Did you find this article valuable?

Support Sreekesh Iyer by becoming a sponsor. Any amount is appreciated!