next.js: Next.js TypeError: Cannot read properties of undefined (reading 'bind') - caused by middleware.ts
Verify canary release
- I verified that the issue exists in the latest Next.js canary release
Provide environment information
Operating System:
Platform: darwin
Arch: x64
Version: Darwin Kernel Version 22.6.0: Wed Jul 5 22:21:56 PDT 2023; root:xnu-8796.141.3~6/RELEASE_X86_64
Binaries:
Node: 16.13.1
npm: 8.19.2
Yarn: 1.22.11
pnpm: N/A
Relevant Packages:
next: 13.5.4
eslint-config-next: N/A
react: 18.2.0
react-dom: 18.2.0
typescript: N/A
Next.js Config:
output: standalone
Which example does this report relate to?
https://github.com/vercel/next.js/blob/canary/examples/with-docker/README.md
What browser are you using? (if relevant)
No response
How are you deploying your application? (if relevant)
No response
Describe the Bug
I getting following error on run next app after npm run build
(node:50480) ExperimentalWarning: stream/web is an experimental feature. This feature could change at any time
(Use `node --trace-warnings ...` to show where the warning was created)
⚠ "next start" does not work with "output: standalone" configuration. Use "node .next/standalone/server.js" instead.
▲ Next.js 13.5.4
- Local: http://localhost:3000
✓ Ready in 257ms
TypeError: Cannot read properties of undefined (reading 'bind')
at NextNodeServer.handleRequestImpl (/Users/michal.stys/OwnProjects/next13-test/node_modules/next/dist/server/base-server.js:389:50)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
TypeError: Cannot read properties of undefined (reading 'bind')
at NextNodeServer.handleRequestImpl (/Users/michal.stys/OwnProjects/next13-test/node_modules/next/dist/server/base-server.js:389:50)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
My middleware.ts from next.js docs.
import { NextRequest, NextResponse } from "next/server";
const PUBLIC_FILE = /\.(.*)$/;
export async function middleware(req: NextRequest) {
if (
req.nextUrl.pathname.startsWith("/_next") ||
req.nextUrl.pathname.includes("/api/") ||
PUBLIC_FILE.test(req.nextUrl.pathname)
) {
return;
}
if (req.nextUrl.locale === "default") {
const locale = "en";
return NextResponse.redirect(
new URL(`/${locale}${req.nextUrl.pathname}${req.nextUrl.search}`, req.url)
);
}
}
PS. all works perfect without this middleware
Expected Behavior
Type error doesn’t exists if using middleware.ts
To Reproduce
npx create-next-app --example with-docker nextjs-docker
// add middleware.ts added above
npm run build
npm start
About this issue
- Original URL
- State: open
- Created 9 months ago
- Reactions: 27
- Comments: 36 (7 by maintainers)
Commits related to this issue
- feat: Support WebSocket API routes, Upgrade requests Enables route handlers to receive and act on `Connection: Upgrade` requests, such as WebSockets, when using the Node runtime. To enable this, the ... — committed to AaronFriel/next.js by AaronFriel 7 months ago
- feat: Support WebSocket API routes, Upgrade requests Enables route handlers to receive and act on `Connection: Upgrade` requests, such as WebSockets, when using the Node runtime. To enable this, the ... — committed to AaronFriel/next.js by AaronFriel 7 months ago
- feat: Support WebSocket API routes, Upgrade requests Enables route handlers to receive and act on `Connection: Upgrade` requests, such as WebSockets, when using the Node runtime. To enable this, the ... — committed to AaronFriel/next.js by AaronFriel 7 months ago
The bug is reproducible on Node.js 19 and above, with bare next app (obtained from
pnpm create next-app
) with the simplest middleware:I got it on Node.js 20 (It will become the LTS on 24 of October) and with the unset
output
field innext.config.js
@ztanner have you had a chance to look into the issue yet? Thank you in advance.
after I’ve added
export const config = { matcher: [ '/((?!api|_next/static|_next/image|favicon.ico).*)', ], }
this bug disapiered on 14.1I had this problem after upgrading to 14.1. It didn’t happen in 13.4.2 before the upgrade. After deleting middleware.ts the error disappeared Is there any workaround?
I experienced this error message earlier after upgrading to Next v14 — i needed to upgrade my Clerk package, it turned out. The error went away after.
Check any middleware that your middleware may be using.
Hi @yamatsum – currently yes, you need to exclude it. In a typical single-server setup, that single server handles
webpack-hmr
requests, so they never make it to your middleware.But because your first server is seeing an HMR request for a different server, it doesn’t know what to do with it, so it’s passing it on to middleware for your first server rather than letting it rewrite to your second server.
I don’t have an ETA yet on a fix, I will try to look into it next week 😃
@huozhi @ztanner @agustints I was able to reproduce the problem with minimal configuration Reproduce by starting locally and accessing localhost:3000/test https://github.com/yamatsum/nextjs-14.1-sample
I’m also facing same issue: ⨯ TypeError: Cannot read properties of undefined (reading ‘bind’) at NextNodeServer.handleRequestImpl
Node version: 20.10.0, 18.18.0 Next verson: 14.0.4 app-router
I think I might be know what is happening in most of the cases with this @spencerchang @mstys . Did you have a browser tab open with the app left running in dev mode? (Given HMR tries to connect over websockets)
This error seems to occur when trying to connect to a standalone server in websocket mode with middleware enabled.
the
handleRequestImpl
method assumes that the passed res._res is always going to be aServerResponse
but can be passed as a socket when calling the endpoint as a websocket:
(Try calling standalone server with
new WebSocket ( "ws://127.0.0.1:3000" )
from a browser tab)Think it might be worth excluding anything trying to connect over
ws://
as a whole from being run as middleware @huozhi given the assumptions made in the current code? 🤔I am running to the same issue on Node.js v18.15.0
For me, the issue was that the middleware was being applied to my
/ws
(custom websocket) endpoint. I don’t need any middleware on that endpoint, so adding this tomiddleware.ts
fixes it:@huozhi I tested it standalone mode as well before I created an issue, and got following error:
In your reproduction @yamatsum, since you’re using a multi-zone approach, when loading
/test
the dev HMR websocket forweb2
is being handled by your middleware inapps/web
rather than making it to the server it was intended for (apps/web2
). Updating your middleware matcher to exclude paths that correspond the basepath of the other server you’re rewriting to (ie anything that starts with/test
) will fix the problem. Something like this:Note: It’s currently important that you use
matcher
to exclude these paths, rather than skipping over them in the middleware handler itself.When doing this, it will see that your middleware didn’t handle the request, and move onto your rewrites which point the request to your other server.
If you’re running into this issue but aren’t running a multi-zone setup, then there’s likely some other websocket upgrade request that is being handled by your middleware. As mentioned by some folks in earlier replies, make sure your middleware matchers are skipping over those routes so they can make it to the server they were intended for.
We should be able to detect this and handle it more gracefully on our side, so I can work on a fix for that. The above is a workaround in the meantime.
Hi @yamatsum, thanks for sharing, next weekend I will try to reproduce it with your repo and see if I can help fix this issue (I don’t promise anything, I will try to do my best to help you with this)!
Agustín Tornielli, Software Developer
If you’re using fallbacks on dynamic pages (i.e., pages like [componentId.jsx] or [componentIdNameDirectory]/index.jsx), set fallback to ‘blocking’.
E.g.:
This should fix the issue.
I today had this happening locally and it drove me crazy. Then I realized I had a dev-instance of the app open in a tab, that tried to make websocket requests to the prod app, that doesn’t support websockets. So… false alert 😅
I ran into this error as well. I could reproduce it only if I put the middleware.js file in root (I used the with-docker repo).
docker build -t nextjs-docker .
However when I renamed the file from
middleware.js
to_middlewere.js
the error dissapered. I tired this in my own project and the renaming indeed removes the error. I haven’t ran all tests yet but I’ll continue investigate this further tomorrow.From the docs we can read:
Is it possible it should say “<root>/_middleware.(ts/js)” perhaps?
Here is a minimal reproduction of the behaviour: nextjs-docker.zip
@huozhi you add middleware to project?
then try again