Vercel Middleware Integration

Vercel is a cloud platform that allows to deploy JavaScript-based applications to the cloud. It is a great platform for deploying serverless functions or full-stack applications. This page explains how to integrate redirection.io with a Vercel application.

In order to install redirection.io in your application hosted on Vercel, there are mainly two options:

  • using the redirection.io managed instances, which are hosted by redirection.io and do not require any specific setup on your side. This is the easiest way to use redirection.io, but please note that Vercel does not specificaly recommend using a reverse proxy in front of their platform, except if you run the Enterprise plan, which allows for custom networking configurations.
  • using the redirection.io Vercel middleware. In the setup, redirection.io will be executed as a middleware in your Vercel application, and will be able to intercept and analyze the requests and responses. Due to Vercel restrictions on 3rd party reverse proxies, this is the recommended way to use redirection.io with Vercel.

Prerequisites

Before starting the integration of redirection.io with your Vercel application, you need to have:

  • the ability to install a package in your Vercel application;
  • the ability to deploy a Vercel application and to configure environment variables.

Using the redirection.io Vercel middleware

Deploying redirection.io on Vercel requires several steps:

  1. create a redirection.io account;
  2. create a redirection.io organization and a project. At this step, you may want to invite your co-workers ;
  3. Install the redirection.io Vercel middleware in your Vercel application;
  4. Configure the redirection.io Vercel middleware with your project key using a Vercel environment variable;
  5. Deploy your Vercel application.

Install the redirection.io Vercel middleware

In your Vercel application, install the @redirection.io/vercel-middleware package:

npm install @redirection.io/vercel-middleware

// or with yarn
yarn add @redirection.io/vercel-middleware

This package is available as an open-source package on npm and on our GitHub page.

Use the redirection.io middleware in your application

Once installed, the middleware has to be used by your Vercel application. The approach depends on whether your application already uses a middleware or not.

My application does not have any middleware

If no middleware is currently used by your application, we'll have to create one! To do so, create a new file named middleware.ts in the root of your Vercel application (at the same level as the app or pages folders, possibly in a src folder if your project uses one), and add the following code:

import redirectionioMiddleware from '@redirection.io/vercel-middleware/next';

export default redirectionioMiddleware;

export const config = {
  unstable_allowDynamic: [
    '/node_modules/@redirection.io/**',
  ],
}

By default, our middleware ignores certain routes even if there's an exported configuration. The ignored routes are:

  • /api/* routes
  • /next/* (Next.js internals)
  • /static/* (inside /public)
  • all root files inside /public (e.g. /favicon.ico)

If you want to customize which routes the middleware handles, use the createRedirectionIoMiddleware() function and provide your own regex using the matcherRegex option:

import { createRedirectionIoMiddleware } from "@redirection.io/vercel-middleware/next";

const middleware = createRedirectionIoMiddleware({ 
    matcherRegex: "^/((?!api).*)$" // Your regex here
});

export default middleware;

export const config = {
  unstable_allowDynamic: [
    '/node_modules/@redirection.io/**',
  ],
}

If you want the middleware to handle all routes without any exclusions, you can set the matcherRegex option to null:

createRedirectionIoMiddleware({ matcherRegex: null });

My application already uses a Vercel middleware

If your application already contains a Vercel middleware, the integration mode described above will not be suitable for you. Instead, you will need to modify the existing middleware in order to have the redirection.io middleware wrap it.

Say your current middleware looks like this:

export default async function middleware(req: NextRequest) {
  // here
  // your
  // middleware
  // code
}

export const config = {
  matcher: ['/((?!api|static|.*\\..*|_next|favicon.ico|robots.txt).*)'],
};

Move your code in a dedicated function:

const myMiddleware = async (req: NextRequest) => {
  // here
  // your
  // middleware
  // code
};

export const config = {
  matcher: ['/((?!api|static|.*\\..*|_next|favicon.ico|robots.txt).*)'],
};

And use the createRedirectionIoMiddleware from @redirection.io/vercel-middleware/next to wrap your middleware code in the redirection.io middleware, thanks to the previousMiddleware or nextMiddleware options.

If you use previousMiddleware, your middleware's code will be executed before redirection.io runs its logic. If you choose nextMiddleware, then it will ne executed after redirection.io has been executed (and, potentially, it may not be executed at all if a redirect is to be run):

import { createRedirectionIoMiddleware } from "@redirection.io/vercel-middleware/next";

const myMiddleware = async (req: NextRequest) => {
  // here
  // your
  // middleware
  // code
};

const middleware = createRedirectionIoMiddleware({ 
    previousMiddleware: myMiddleware,  // In this case your middleware is executed before redirection.io middleware
    nextMiddleware: myMiddleware, // In this case your middleware is executed after redirection.io middleware
});

export default middleware;

export const config = {
  unstable_allowDynamic: ["/node_modules/@redirection.io/**"],
};

If your middleware configuration contains the "matcher" option (to restrict which requests must go through the middleware), this will be used upstream of our middleware.

If the regex passes, then our middleware will use a second default regex (which ignores Next.js internals and static files):

^/((?!api|static|.*\\..*|_next|favicon.ico|robots.txt).*)$

You can modify this regex by default using the matcherRegex option of the createRedirectionIoMiddleware function:

const middleware = createRedirectionIoMiddleware({ 
    matcherRegex: "^/((?!api/auth).*)$", // Your regex here
});

Please note that the regular expression is bit different than the one that was in the matcher option: it now starts with a ^ and ends with a $

If your project is not based on Next.js, all the code above can be adapted to import from @redirection.io/vercel-middleware instead of @redirection.io/vercel-middleware/next.

Configure the redirection.io Vercel middleware

In the settings of your Vercel application, add a new environment variable named REDIRECTIONIO_TOKEN with the value of your redirection.io project key:

The Vercel setting page to add the REDIRECTIONIO_TOKEN environment variable

Deploy your Vercel application

Once the redirection.io Vercel middleware is installed and configured, you can deploy your Vercel application. The redirection.io Vercel middleware will be executed on each request, it will analyze the requests and responses and allow for easy response modifications.

Supported environment variables

The behavior of the redirection.io Vercel Middleware can be cusomized using several environment variables to create in the Vercel project settings:

REDIRECTIONIO_TOKEN

  • This directive is required
  • Description: this is the "project key" of the redirection.io project that the traffic for this site must be associated to

REDIRECTIONIO_ADD_HEADER_RULE_IDS

  • This directive is optional
  • Default: false
  • Description: set this to true to append a response Header X-RedirectionIo-RuleIds containing the executed redirection.io rules identifier, separated by a ;

REDIRECTIONIO_INSTANCE_NAME

  • This directive is optional
  • Default: redirection-io-vercel-middleware
  • Description: this is the name for this Vercel middleware instance, as it should be displayed in the redirection.io manager "instances" screen

REDIRECTIONIO_TIMEOUT

  • This directive is optional
  • Default: 500
  • Description: define the maximal timeout to the redirection.io API calls (in ms). If this timeout is reached, no rule is applied to the request.

Troubleshooting

Which version of Next.js is this middleware compatible with?

The redirection.io Vercel Middleware is compatible with Next.js 14.2 at least.

Do you have any examples of integrating redirection.io with Next.js?

We offer a repository that includes several examples of integrating Next.js with Redirection.io:

  • Storyblok Integration: a demo showcasing how to integrate redirection.io with a Next.js app using Storyblok CMS.
  • Auth0 Integration: an example of setting up Next.js with Auth0 authentication and redirection.io.
  • Next-intl Integration: a guide demonstrating how to use Next.js with next-intl for internationalization, combined with redirection.io.

Each example comes with detailed setup instructions in their respective sub-directories within the examples repository.

Why do you use unstable_allowDynamic in the middlware config?

The Next.js documentation explains that some features are disabled in the Next.js Edge runtime, in particular dynamic code execution.

The unstable_allowDynamic configuration directive is a way to relax the static code analysis, and can be used to allow loading specific files in a middleware even if some part of them contain unsupported features. This is particularly useful if you depend on a feature offered by library that bundles such unsupported statements.

The redirection.io middleware relies on the getrandom library to generate some random data when using a samping trigger. Unfortunately, parts of this library, that will never be executed by the redirection.io middleware, can lead to dynamic code execution in very specific conditions (on node.js, when a specific module is not available) that cannot be met when using the middleware.

This is the only reason why unstable_allowDynamic is required to run the redirection.io middleware.

Do I need to change things if I use pnpm instead of npm or yarn?

If you are using pnpm, the install location of the module is not in /node_modules but in a .pnpm folder. In this case, you may use ["/node_modules/.pnpm/**/@redirection.io/**"] as the configuration value for unstable_allowDynamic.

In other words, in this case you would configure your base middleware like this:

import redirectionioMiddleware from '@redirection.io/vercel-middleware/next';

export default redirectionioMiddleware;

export const config = {
  unstable_allowDynamic: [
    '/node_modules/.pnpm/**/@redirection.io/**',
  ],
}
This page has been updated on October 22nd, 2024.
Can't find your answer?