Three Things You Wanted to Know About Next.js Middleware

Szymon Korytnicki
Jobtome Engineering
2 min readNov 8, 2022

Middlewares became stable in Next 12.2. This is great news, since it’s mindblowing how much stuff can be done using this feature:

  • rewriting and redirecting files
  • applying translations
  • sending analytics data
  • setting cookies

Nonetheless, Next middleware comes with a set of small caveats that are hard to internalise at first. To make your life easier, let us highlight top three things that make Next middleware special:

  • Edge runtime
  • Ability to compose middlewares
  • Identifying a page, API call and assets

This article assumes basic understanding of Next.js and its Middleware docs.

1. Next Middleware uses Edge runtime

Edge Runtime was designed as lightweight and optimised for performance. As such, it is limited in terms of developer’s flexibility. When entering middleware.ts file, you shouldn’t treat it as a Node file, it’s indeed a completely separate runtime executing your code under the hood.

You can’t use Node APIs or some Web APIs you might be used to. Most likely you’d like to call some external module. It’s very risky!

It might use Node-specific API. We recommend to use native fetch and API routes to use Node-specific modules.

Inside API routes, you are allowed to use Node:

On top of that, you can’t use runtime environment variables. It means that environment variables are only replaced in build time.

Try it yourself:

2. Yes, you can compose multiple middlewares

In previous, unstable versions, you could simply create multiple files to support multiple middlewares.

Now, the convention forces you to have a single middleware.ts or js file placed at /pages directory level. Do not allow this convention to put all your middlewares in the one, lengthy file!

Actually, it is simply enough to iterate over middlewares. First, define their shape:

and then make a simple iteration over these:

3. How do I know it is a page?

There is no longer an official way to tell if the request is made for page and what page is it. You can however work your way to build a simple page detector.

50% of the work here is to use middleware matchers, to exclude some paths you aren’t interested in “middlewaring”. This will have an extra performance bonus of skipping unnecessary work:

On top of that, you can exclude all calls for API, for your assets directory and paths with a dot (presumably some files).

Small tip: remember that your assets directory might be overridden from _next in next.config.js. Look for distDir option.

You can access a lot of URL properties to identify the path inside a middleware:

Summary

We hope that this article helped you design great middlewares!

--

--