-
Notifications
You must be signed in to change notification settings - Fork 27.2k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Next.js TypeError: Cannot read properties of undefined (reading 'bind') - caused by middleware.ts #56368
Comments
This comment has been minimized.
This comment has been minimized.
There's a warning from the console, please run the standalone server instead
|
@huozhi it's warning not error. If you think that it works as expected it should throw error and not start. Moreover app works correctly without middleware. |
@huozhi I tested it standalone mode as well before I created an issue, and got following error: ➜ next13-test git:(main) ✗ node .next/standalone/server.js
(node:94767) 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.js 13.5.4
- Local: http://localhost:3000
- Network: http://0.0.0.0:3000
✓ Ready in 124ms
[
{
label: 'Your personal data',
fields: [
[Object], [Object],
[Object], [Object],
[Object], [Object],
[Object], [Object],
[Object], [Object],
[Object]
]
}
]
{ list: [ { label: 'Your personal data', fields: [Array] } ] }
TypeError: Cannot read properties of undefined (reading 'bind')
at NextNodeServer.handleRequestImpl (/Users/michal.stys/OwnProjects/next13-test/.next/standalone/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/.next/standalone/node_modules/next/dist/server/base-server.js:389:50)
at processTicksAndRejections (node:internal/process/task_queues:96:5) |
@huozhi, this still exists - not sure why it's closed. This break features based on middleware and have other problem on Vercel, like |
@mstys I couldn't repro that error with with-docker example and that middleware
|
@Phoenix-Alpha |
@huozhi you add middleware to project? // middleware.ts
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)
);
}
} then try again |
I did, I cannot repro it |
The bug is reproducible on Node.js 19 and above, with bare next app (obtained from
I got it on Node.js 20 (It will become the LTS on 24 of October) and with the unset |
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).
However when I renamed the file from From the docs we can read:
Is it possible it should say "/_middleware.(ts/js)" perhaps? Here is a minimal reproduction of the behaviour: |
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 export const config = {
matcher: '/((?!ws$).*)', // match all paths except /ws
} |
Same issue here, it will fix in the future right? |
I think I might be know what is happening in most of the cases with this @spencerchang @mstys . This error seems to occur when trying to connect to a standalone server in websocket mode with middleware enabled. the but can be passed as a socket when calling the endpoint as a websocket: (Try calling standalone server with Think it might be worth excluding anything trying to connect over |
Enables route handlers to receive and act on `Connection: Upgrade` requests, such as WebSockets, when using the Node runtime. To enable this, the base http server has the `on('upgrade')` handler removed. In this author's opinion, that handler is an anti-pattern as it makes it much more difficult to handle middleware and other request lifecycle behavior. By passing the raw request to the route handler and implementing a `NextResponse.upgrade()` response value to opt out of additional processing that would write to the socket, the route handler can handle an upgrade request itself. Fixes vercel#58698 (feature request) Fixes vercel#56368 (caused by next-ws / websocket middleware)
Enables route handlers to receive and act on `Connection: Upgrade` requests, such as WebSockets, when using the Node runtime. To enable this, the base http server has the `on('upgrade')` handler removed. In this author's opinion, that handler is an anti-pattern as it makes it much more difficult to handle middleware and other request lifecycle behavior. By passing the raw request to the route handler and implementing a `NextResponse.upgrade()` response value to opt out of additional processing that would write to the socket, the route handler can handle an upgrade request itself. Fixes vercel#58698 (feature request) Fixes vercel#56368 (caused by next-ws / websocket middleware)
Enables route handlers to receive and act on `Connection: Upgrade` requests, such as WebSockets, when using the Node runtime. To enable this, the base http server has the `on('upgrade')` handler removed. In this author's opinion, that handler is an anti-pattern as it makes it much more difficult to handle middleware and other request lifecycle behavior. By passing the raw request to the route handler and implementing a `NextResponse.upgrade()` response value to opt out of additional processing that would write to the socket, the route handler can handle an upgrade request itself. Fixes vercel#58698 (feature request) Fixes vercel#56368 (caused by next-ws / websocket middleware)
next.js 14.0.4 this issue still happened. |
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. |
I encountered the same issue today using 13.5.6. No matter what I did, nothing fixed the error. So I started building from scratch, and I
So I don't know why and how the error is gone, but I do not see the I surely see this at 389 in const origSetHeader = _res.setHeader.bind(_res); |
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'm also facing same issue: Node version: 20.10.0, 18.18.0 |
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 had this problem after upgrading to 14.1. |
@huozhi @ztanner @agustints |
@yamatsum you succeed with finding some solution? |
No, it's not resolved yet |
In my case, it's happened when i include socket.io and enable websocket. |
after I've added |
In your reproduction @yamatsum, since you're using a multi-zone approach, when loading // apps/web/middleware.ts
export const config = {
matcher: [
// Don't handle HMR requests for the dev server we rewrite to
"/((?!test/_next/webpack-hmr).*)",
],
}; Note: It's currently important that you use 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. |
@ztanner Thank you for investigating! Also, is it necessary to exclude webpack-hmr? |
Hi @yamatsum -- currently yes, you need to exclude it. In a typical single-server setup, that single server handles 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 :) |
Thank you for your investigation |
In my case none of the above solutions worked I just set the matcher where i want to run the middleware and it's working export const config = {
matcher: ["/", "/register", "/dashboard/:path*"],
}; |
@ztanner have you had a chance to look into the issue yet? Thank you in advance. |
@ztanner i tried every solutions here and `import { NextRequest, NextResponse } from 'next/server' const PUBLIC_FILE = /.(.*)$/ export async function middleware(req: NextRequest) {
}` |
Up |
This is the correct answer @VanCoding |
I have encountered the same issue with export const config = {
matcher: [
'/((?!api|_next/static|_next/image|favicon.ico).*)',
],
} The TypeError issue has been resolved, but unfortunately, a new error arises with clerck due to a discrepancy in the provided documentation. They suggest using a different match : |
@mstys Could not reproduce with the given link, please provide a valid repro. Thank you! For the future readers, please take a look at the Middleware Matching Paths doc and ensure the config is set correctly. Also, thank you @issam-seghir, @Siumauricio, @webmak and @smartinio for sharing your working matcher config! |
The issue is likely due to a compatibility problem with the version of next-auth you are using. I resolved the issue by upgrading to the beta version of next-auth, which resolved the error related to the oidc-token-hash library. Here's what I did:
npm install next-auth@beta |
I also seem to be having this same issue when even using the clerk quickstart here: https://github.com/clerk/clerk-nextjs-app-quickstart. Talking to their support has been primarily pushed back here as the error happening in I have tested all of the Middleware matching patterns on here as well as a couple more. Anything else people can think of to check? |
Small update to the above. I still receive this error even when I create a new project with create-next-app and adding the following middleware.ts file
|
Thank you, this gave me a clue as to what the problem was. I had two Next JS apps, and one was shutdown but the browser tab was still open. When I started the other one it started on the same port and caused this. |
I had similar issue running What helped me was to set the request locale on these pages, here's an example:
|
Verify 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
My middleware.ts from next.js docs.
PS. all works perfect without this middleware
Expected Behavior
Type error doesn't exists if using middleware.ts
To Reproduce
// add middleware.ts added above
NEXT-1739
The text was updated successfully, but these errors were encountered: