NextJS Middleware Server Error: Attempt to export a nullable value for "TextDecoderStream"

1.1k views Asked by At

I have set up a simple nextjs application with bun (version 1.0.4, bun create next-app) with app routing (nextjs 13.5.4) and a source directory. I wanted to include a middleware that only allows traffic from certain IPs however if I have the middleware.ts file in the /src directory (where it should be according to the docs) no matter what's in the file I get the following error:

Error: Attempt to export a nullable value for "TextDecoderStream"
This error happened while generating the page. Any console logs will be displayed in the terminal window.
Call Stack
defineProperties
file:<PROJECT>/node_modules/next/dist/compiled/edge-runtime/index.js
addPrimitives
file:<PROJECT>/node_modules/next/dist/compiled/edge-runtime/index.js
extend
file:<PROJECT>/node_modules/next/dist/compiled/edge-runtime/index.js
new VM
file:<PROJECT>/node_modules/next/dist/compiled/edge-runtime/index.js
new EdgeVM
file:<PROJECT>/node_modules/next/dist/compiled/edge-runtime/index.js
<anonymous>
file:<PROJECT>/node_modules/next/dist/server/web/sandbox/context.js (196:64)

The directory structure looks like this:

/node_modules
/public
/src
/src/app
/src/lib
/src/middleware.ts
/<config_and_env_files...>
/bun.lockb
/next-env.d.ts
/next.config.js
/package.json
/tsconfig.json

Is there any way to fix this error so that I can whitelist IPs or is there a better way to whitelist IPs so that I can go around the problem? I tried googling the issue but there is not much on the topic of this error.

2

There are 2 answers

1
Joshua Muuo On

This is what worked for me on PopOs

  1. Install nodejs - make sure you get the latest stable version
  2. Install npm
  3. cd into project
  4. Run npm run dev and stop it
  5. Run bun run dev

Bun have not implemented TextDecoderStream. They say "It’s faster to just make all the APIs accept strings instead of having a separate encoder/decoder stream pass through input." in this tweet thread

I'd love to know why this works.

0
heez On

Bun does not yet implement TextDecoderStream. You can follow its implementation on Bun's roadmap.

In Bun's Next.js guide they make this clear

The Next.js App Router currently relies on Node.js APIs that Bun does not yet implement. The guide below uses Bun to initialize a project and install dependencies, but it uses Node.js to run the dev server.

So that's why the other answer "works". It's still using the Node.js runtime. You have to pass the --bun flag to have it use the Bun runtime