Deliver dynamic content at the speed of static with Next.js Middleware and Vercel Edge!

Intro

In this post I’d like to share a topic that we’ve presented together with my friend Ehsan Aslani during the Sitecore User Group France, an event that I’ve also organized with my friends Ugo Quaisse and Ramkumar Dhinakaran in Paris at the Valtech offices, find more details and pictures about the event here.

About Edge Middleware

At the time we presented this topic in the UG, the Edge Functions in Vercel were in beta version, now we got the good news from Vercel that they released Next.js version 12.2 that includes Middleware stable among other amazing new experimental features like:

On top of this new release, Vercel also introduced a new concept that makes a little bit of confusion around it, Edge Functions != Edge Middleware. In the previous version, the middleware was deployed to Vercel as an Edge Function, while now it’s a “Middleware Edge”.

Edge Functions (still in beta)

Vercel Edge Functions allow you to deliver content to your site’s visitors with speed and personalization. They are deployed globally by default on Vercel’s Edge Network and enable you to move server-side logic to the Edge, close to your visitor’s origin.

Edge Functions use the Vercel Edge Runtime, which is built on the same high-performance V8 JavaScript and WebAssembly engine that is used by the Chrome browser. By taking advantage of this small runtime, Edge Functions can have faster cold boots and higher scalability than Serverless Functions.

Edge Functions run after the cache, and can both cache and return responses.

Edge Functions

Middleware Functions

Edge Middleware is code that executes before a request is processed on a site. Based on the request, you can modify the response. Because it runs before the cache, using Middleware is an effective way of providing personalization to statically generated content. Depending on the incoming request, you can execute custom logic, rewrite, redirect, add headers, and more, before returning a response.

Edge Middleware allows you to deliver content to your site’s visitors with speed and personalization. They are deployed globally on Vercel’s Edge Network and enable you to move server-side logic to the Edge, close to your visitor’s origin.

Middleware uses the Vercel Edge Runtime, which is built on the same high-performance V8 JavaScript and WebAssembly engine that is used by the Chrome browser. The Edge Runtime exposes and extends a subset of Web Standard APIs such FetchEventResponse, and Request, to give you more control over how you manipulate and configure a response, based on the incoming requests. To learn more about writing Middleware, see the Middleware API guide.

Edge Middleware

Benefits of Edge Functions

  • Reduced latency: Code runs geographically close to the client. A request made in London will be processed by the nearest edge node to London, instead of Washington, USA.
  • Speed and agility: Edge Functions use Edge Runtime, which, due to its smaller API surface, allows for a faster startup than Node.js
  • Personalized content: Serve personalized cached content based on attributes such as visitor location, system language, or cookies

About nested middleware in beta

With the stable release of middleware in Next.js v12.2, nested middleware is not supported anymore, details here.

In the beta version, it was possible to create different “_middleware.ts” files under specific folders so we can control when those are executed. Now, only one file at the app’s root is allowed and we need to add some logic to handle that by checking the parsed URL, like:

// <root>/middleware.ts
import type { NextRequest } from 'next/server'

export function middleware(request: NextRequest) {
  if (request.nextUrl.pathname.startsWith('/about')) {
    // This logic is only applied to /about
  }

  if (request.nextUrl.pathname.startsWith('/dashboard')) {
    // This logic is only applied to /dashboard
  }
}

Common usages

Demo time!

In the demo I’ve prepared for the UG, I used edge functions for doing a bit of geolocation, playing with cookies, A/B testing, rewrites, and feature-flag enablement.

To start I’ve just created an empty project using the nextjs CLI:

npx create-next-app@latest --typescript

Then, inside the recently created app folder, and then check localhost:

npm run dev

We are all set to start testing out the middleware, for doing that, we get started by creating a new file in the root folder, name it “middleware.ts”. Let’s add some code there to test how it works:

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

export function middleware (req: NextRequest, event: NextFetchEvent) {  
    const response = NextResponse.next()
    response.headers.set('x-sug-country', 'FR')
    return response
}

This will just simply add a response header and return it, refresh your browser and check the headers, our recently added “x-sug-country” should be there:

For this demo, I’ve created some simple pages:

– Pages
|- about
|- aboutnew
|- index
|- featureflag
|- featureflags
|- abtest
|- index

A/B Testing

The idea was to do some A/B testing on the about page, so for doing that I’ve used ConfigCat an easy-to-use tool for managing feature-flags enablement, that also has some options to target audience, so I’ve created my “newAboutPage” flag with 50% option:

The following code is what we need to place in our middleware, and it will basically get the value flag value from ConfigCat and store it in a cookie. Note the usage here of URL Redirects and Rewrites, cookies management, feature flags, and of course, A/B testing, all running as a middleware function, that when deployed to Vercel will be executed on the edge network, close to the visitor origin, with close to zero latency.

export function middleware (req: NextRequest) {  
    if (req.nextUrl.pathname.startsWith('/about')) {
        const url = req.nextUrl.clone()

        // Redirect paths that go directly to the variant
        if (url.pathname != '/about') {
            url.pathname = '/about'
            return NextResponse.redirect(url)
        }

        const cookie = req.cookies.get(ABOUT_COOKIE_NAME) || (getValue('newaboutpage') ? '1' : '0')

        url.pathname = cookie === '1' ? '/about/aboutnew' : '/about'

        const res = NextResponse.rewrite(url)

        // Add the cookie if it's not there
        if (!req.cookies.get(ABOUT_COOKIE_NAME)) {
            res.cookies.set(ABOUT_COOKIE_NAME, cookie)
        }

        return res
      }
...

Let’s test it and by clicking on “Remove Cookie and Reload” you’ll be getting both variants with 50% probability:

Feature flags

In the demo, I’ve also added the features flag page where I’m rendering or hiding some components depending on their flag enablement, again by using ConfigCat for this:

The “sugconfr” flag, that you can see it’s disabled, and the “userFromFrance” that also checks the country parameter and only returns true if it’s France, so we can see here how easy we can personalize based on geolocation.

Let’s have a look at the code we’ve added to the middleware:

export function middleware (req: NextRequest) {  
    if (req.nextUrl.pathname.startsWith('/about')) {
        ...
      }

      if (req.nextUrl.pathname.startsWith('/featureflag')) {
        const url = req.nextUrl.clone()
  
        // Fetch user Id from the cookie if available 
        const userId = req.cookies.get(COOKIE_NAME_UID) || crypto.randomUUID()
        const country = req.cookies.get(COOKIE_NAME_COUNTRY) || req.geo?.country
        const sugfr = req.cookies.get(COOKIE_NAME_SUGFR) || (getValue(COOKIE_NAME_SUGFR) ? '1' : '0')

        const res = NextResponse.rewrite(url)
        
        // Add the cookies if those are not there
        if (!req.cookies.get(COOKIE_NAME_COUNTRY)) {
            res.cookies.set(COOKIE_NAME_COUNTRY, country)
        }

        if (!req.cookies.get(COOKIE_NAME_UID)) {
            res.cookies.set(COOKIE_NAME_UID, userId)
        }

        if (!req.cookies.get(COOKIE_NAME_SUGFR)) {
            res.cookies.set(COOKIE_NAME_SUGFR, sugfr)
        }

        return res
      }

Again, we get the values and store it in cookies. Then we use the feature flags to show or hide some components, as we can see here:

If we load the page with the “sugconfr” disabled, we will get this:

So, let’s enable it back from ConfigCat, publish the changes and reload the page:

Now the page looks different, the SUGFR component is showing up. As you can see, the other component where we have chosen to enable only for users coming from France is still not showing, this is because we are testing from localhost so of course, there is no geolocation data coming from the request. So, let’s deploy this app to Vercel so we can also test this part and check how it looks running in the Edge.

Deploying the Edge Middleware to Vercel

As I have my Vercel app installed in my GitHub repo, the integration is so simple that we can just push those changes to the repo and wait for Vercel to deploy it. For details on how to set this up, please check my previous post about Deploying a Sitecore JSS-Next.js App with SSG & ISR to Vercel (from zero to live)

Note: make sure you add the ConfigCat API Key to the environment variables in Vercel before deploying:

If you have a look at the deployment logs, you will see that it created the edge function based on our middleware:

If we check the site now, as we are now getting geolocation data from the user’s request, the component is showing up there:

You can check logs by going to functions sections from the Vercel dashboard, which is really cool for troubleshooting purposes:

This was just a quick example of how to start using this middleware feature from Next.js and Vercel’s Edge Network, which enable us to move some backend code from the server to the edge, making those calls super fast with almost no latency. Now that is already stable we can start implementing those for our clients, there are multiple usages, another quick example where we can implement those are for resolving multisite by hostnames for our Sitecore JSS/Next.js implementation.

You can find the example app code here in this GitHub repo. The app is deployed to Vercel and accessible here.

There is a great “getting started” video from Thomas Desmond, check it!

You can find a lot of great examples from Vercel Edge Functions repo as well and of course the official documentation.

I hope you enjoyed this reading and don’t wait, go and have fun with middleware!