next.jsmiddleware

NextJs middleware: use default runtime instead of Edge runtime


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)


Solution

  • 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