Reza Safari Blog
Published on

Nextjs-Dynamic Code Evaluation

In versions 13 and later of Next.js, when you want to use middleware, there are several limitations. For example, some features are either not yet implemented or are not intended to be implemented at all.

For instance:

You cannot read/write files with Node.js APIs Using 'require' is not allowed There are also restrictions on the use of node_modules Complete details: Link The most significant limitation relates to Dynamic Code Evaluation, which prohibits the use of the following codes:

eval() new Function WebAssembly.compile

Now, here's something to consider: Not all the code we use is under our control. For instance, if you're using libraries like Socket-io-client or lodash, these libraries internally use the prohibited codes in middleware.

Naturally, you can't just go and change those codes (at least not in a simple and logical way), and making requests on their GitHub also leads nowhere.

The code causing the error in socket-io is:

return Function("return this")();

And the lodash code is:

var root = freeGlobal || freeSelf || Function("return this")();

Neither of which are allowed to be executed.

The solution is to use unstable_allowDynamic by adding the following code inside our middleware:

export const config = {
  runtime: "experimental-edge",
  unstable_allowDynamic: [
    "/node_modules/lodash/",
    "/node_modules/socket.io-client/",
  ],
};