9

By default, a NextJs middleware is run using the Edge runtime and from what I understand this is because the middleware is meant to be run on the edge network instead of the main server (being run on the edge network reduces the latency so this offers improved performance in some scenarios).

The downside of this is that the Edge runtime comes with some restrictions in terms of what it can run (list here).

My question is: is there any way to make a middleware run using the default runtime instead of the Edge runtime?

In my situation, we're not hosting anything on the edge so the Edge runtime imposes some restrictions on us without providing any benefits. A possible workaround would be to use a custom middleware instead of a NextJs one, but unless this is the only choice, I would rather use the NextJs middleware architecture & plumbing instead of building our own.

P.s.: We're using NextJs 12.1.6 (latest version at the moment of writing this question)

mccuna
  • 471
  • 7
  • 11

2 Answers2

9

There's no way to do it at the moment, but it's being worked on. See RFC: Switchable Next.js Runtime

At the moment if you need node apis in your middleware you can work around the issue by making api routes that do stuff with node apis and then calling them from your middleware. You should definitely try that one out instead of making custom middleware with custom server I assume, since custom servers have limitations.

Next.js 13 added option to change the runtime, but I don't think the setting applies to middleware. The setting can be used to make everything run on the edge though. https://beta.nextjs.org/docs/rendering/edge-and-nodejs-runtimes#global-runtime-option

FINDarkside
  • 2,102
  • 1
  • 18
  • 26
-1

Now it's possible to determine at global and segment levels which runtime should be used with Next.js 13.

This configuration is for defining the runtime for global:

module.exports = {
  experimental: {
    runtime: 'experimental-edge', // 'node.js' (default) | experimental-edge
  },
};

https://beta.nextjs.org/docs/rendering/edge-and-nodejs-runtimes#global-runtime-option

If you want to determine at the segment (aka server component) level, the only thing to do is export a runtime constant variable.

[app/layout.js]

export const runtime = 'experimental-edge'; // 'node.js' (default) | 'experimental-edge'

https://beta.nextjs.org/docs/rendering/edge-and-nodejs-runtimes#segment-runtime-option

sametcodes
  • 583
  • 5
  • 8