-
Notifications
You must be signed in to change notification settings - Fork 27.1k
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
WebSocket connection failed errors after upgrade to Next.js 12 #30491
Comments
Hi, if you are using |
I have the same problem. Nginx is not used "next": "^12.0.1" Maybe it's a custom server? I use this package https://github.com/fridays/next-routes |
same here, just upgraded to v12.0.1 from v11 (without touching anything than increasing the nextjs version in the package.json). running dev server works, but hmr seems not working. Not blocking since i can just manually reload, but it would be nice to get it back working :). Thanks for your great work |
FWIW I was also having this issue and @ijjk's comment (#30491 (comment)) put me in the correct direction. Previously there had not been a need to include the web sockets proxying for HMR to work but it seems now there is. After I added to proxying to the Next.JS server and restarted Nginx I no longer have this issue. @matt-joecoffee We are also serving the site from a real domain in a similar way I suspect to you.
Obviously not helpful for non nginx situations like @pmoskvin's but perhaps the package there is not forwarding these same headers and upgrading the http version? |
@ijjk we'll want to add this to the upgrading guide 👍 |
Sorry for coming back to this, but can anybody help find a solution when using a custom Express server? As I understand, the problem here is slightly different, because the WS request cannot be forwarded/proxied to a HTTP port, because Next.js handles requests using a JavaScript function. Example (abbreviated): import createNextServer from 'next';
const nextServer = createNextServer(/*...*/);
const nextRequestHandler = nextServer.getRequestHandler();
nextServer
.prepare()
.then(() => {
const server = express();
/* Other routes… */
server.all('*', (req, res) => nextRequestHandler(req, res));
}); |
@Manc it should be working with the above case can you share the network error/log showing it not working? |
It's the same issue for me. I have a custom express server.
The error in the js console of the browser is that a ws connection to
_next/webpack-hmr can not be established (I am in my handy currently,
sorry).
I tried adding a proxy as Express Middleware for the giving url to Upgrade
ws connections. But it looks like the webpack hmr is not running/reachable
at all?
JJ Kasper ***@***.***> schrieb am Mo., 1. Nov. 2021, 17:22:
… @Manc <https://github.com/Manc> it should be working with the above case
can you share the network error/log showing it not working?
—
You are receiving this because you commented.
Reply to this email directly, view it on GitHub
<#30491 (comment)>,
or unsubscribe
<https://github.com/notifications/unsubscribe-auth/AARI4YBXRTXP7XOMBMMYODDUJ25E3ANCNFSM5G3L3VMA>
.
|
Hi, I am getting the following error in my console where Next.js is running: And in the browser console: In case it helps, here is the custom server code:
|
Same issue here, not using nginx, but a custom express server similar to the one above. I get a bit different error though:
Happy for any pointers. |
x-ref: #30491 (comment) ## Documentation / Examples - [x] Make sure the linting passes by running `yarn lint`
For me, this code worked:
where loadbalacer is local docker server. |
hey there and the provided solution for routing all hmr requests to the nextjs handler is not working for me. const wsServer = new ws.Server({
server: httpServer,
path: '/graphql'
}) Searching for a solution... |
Just to add, I was having this issue without any kind of middleware/proxy, I just restarted my computer to fix. Possible something WSL related. |
I finally solved the issue I was having (see comment above). I use both a WS connection in my web app, which needs to be proxied in development, and Webpack HMR for development. This is my modified custom server script (abbreviated): import http from 'http';
import createNextServer from 'next';
import { createProxyMiddleware } from 'http-proxy-middleware';
const port = parseInt(process.env.PORT || '3000', 10);
const nextServer = createNextServer(/*...*/);
const nextRequestHandler = nextServer.getRequestHandler();
nextServer
.prepare()
.then(() => {
const expressInstance = express();
// Set up the WebSocket API proxy.
expressInstance.use(
createProxyMiddleware('/path/to/my/websocket/endpoint', {
target: 'ws://192.168.0.123:1234',
ws: true,
})
);
// Set up REST API proxy.
expressInstance.use('/api', createProxyMiddleware({
target: 'http://192.168.0.123:1234',
});
/* Other routes… */
server.all('*', (req, res) => nextRequestHandler(req, res));
http.createServer(expressInstance).listen(port);
}); |
see here |
I'm still experiencing this exact issue, which I think is related to having a custom server + import { getAccessToken, getSession } from "@auth0/nextjs-auth0";
import { loadEnvConfig } from "@next/env";
import express from "express";
import { createProxyMiddleware } from "http-proxy-middleware";
import next from "next";
loadEnvConfig("./", process.env.NODE_ENV !== "production");
const port = parseInt(process.env.PORT, 10) || 3000;
const dev = process.env.NODE_ENV !== "production";
const app = next({ dev });
const handle = app.getRequestHandler();
app
.prepare()
.then(() => {
const server = express();
server.use("/graphql", async (req, res, next) => {
try {
const { accessToken } = await getAccessToken(req, res, { refresh: true });
if (accessToken) {
req.headers["Authorization"] = accessToken;
}
} catch (err) {
res.json({ errors: [{ code: err.code, message: err.message }] });
}
next();
});
server.use(
"/graphql",
createProxyMiddleware({
target: process.env.NEXT_PUBLIC_BACKEND_URL,
changeOrigin: true,
ws: true,
onProxyReqWs: async (proxyReq, req, socket, server, head) => {
if (req.url !== "/graphql") {
return;
}
socket.on("error", function (error) {
console.warn("Websockets error.", error, req.url);
});
try {
const session = getSession(req, {} as any);
if (session?.accessToken) {
proxyReq.setHeader("Authorization", session.accessToken);
}
} catch (err) {}
},
})
);
server.all("*", (req, res) => {
return handle(req, res);
});
server.listen(port, () => {
console.log(`> Ready on http://localhost:${port}`);
});
})
.catch((err) => console.log("error", err)); EDIT: Since this issue is closed and the OP had a different issue, I opened a new one here #32047 |
Having a similar issue, after adding the aforementioned nginx config the request has the headers Connection: Upgrade and Upgrade: websocket but getting an error "WebSocket connection to < URL > failed: WebSocket is closed before the connection is established." - has anyone had this issue? |
Does anyone have a solution? I still have the same problem. |
If you're using Nextjs with Nestjs, it might relate to this one https://stackoverflow.com/questions/67035266/socket-connection-from-nextjs-to-a-node-backend Jay McDoniel mentioned that nest 8 will solve the issue. |
We are using Charles Proxy for local development to map our URL (i.e. From: To: |
@KillerCodeMonkey The only solution I found was to run a separate server for GraphQL from the next server ie a http server listening on a different port. |
For those using apache, here are the proxy settings you'll need in your virtualhost, in this case I'm running node on port 10510, please adjust to suite your setup:
|
I have this problem on my nextjs12. Running locally..no custom server.. |
x-ref: vercel#30491 (comment) ## Documentation / Examples - [x] Make sure the linting passes by running `yarn lint`
Thanks for sharing. It worked in my case where i am using next js with fastify server and nginx for proxy |
I found a solution -- dumb as I may be ;)Version Info: My fix:
In
I was running my "test" script on a test sever that is a pre-prod copy of the prod environment not realizing that So even though everything else was identical between my test version and my production version, My test env Next Custom Express Server was evaluating to dev:trueMy fix: In
I ended up using the dev and test flags in my server file a lot to give myself one codebase between my environments, so I removed them as a dependency on the fast refresh indication and only do fast refresh when I explicitly pass 'development' as my NODE_ENV. Hope this helps someone. tl;drIf you have a Custom Express Server |
If anyone is running into this because they are using a custom next 12 server and apollo graphql subscriptions, we found the easiest workaround was to run the apollo sub server on a different port locally. Apollo + express are able to reconcile the new port, and HMR works as expected. Happy to share more if anyone runs into this. |
I ran into exactly the same issue with custom next server and apollo graphql subscriptions, do you mind sharing your solution with some code snippets? |
Sure!
const options = {
server,
path: '/graph-subscription-route',
};
if (process.env.NODE_ENV === 'development') {
// Override to prevent conflicts with next12+ hmr
options.port = process.env.DEV_GRAPHQL_SUBSCRIPTION_PORT;
}
And then passed that options object to the apollo config
new SubscriptionServer(
{
execute,
subscribe,
schema,
keepAlive: xxx,
onDisconnect: (ws, context) => {
...
},
onConnect: async (connectionParams, ws) => {
...
},
options,
Hope this helps! |
Thanks for sharing it. I tried but it seems SubscriptionServer code doesn't allow the passing server and port together, I got the below error at runtime.(the error seems to be coming from ws's WebSocket.Server constructor error - unhandledRejection: TypeError: One and only one of the "port", "server", or "noServer" options must be specified the package versions I used are Follow-ups: |
With jeremypress shared information and some experiments, I finally made it working Server: import express from 'express';
import http from 'http';
import path from 'path';
import fs from 'fs';
import createNextServer from 'next';
import * as WebSocket from 'ws';
import { makeExecutableSchema } from '@graphql-tools/schema';
import { execute, subscribe } from 'graphql';
import {
SubscriptionServer,
ConnectionContext,
} from 'subscriptions-transport-ws';
import { ApolloServer } from 'apollo-server-express';
import gql from 'graphql-tag';
import { resolvers } from '../api/graphql/resolvers';
const typeDefs = gql(
fs.readFileSync(
path.resolve(__dirname, '../api/graphql/schema.graphql'),
'utf8'
)
);
const schema = makeExecutableSchema({ typeDefs, resolvers });
console.log('node env : ', process.env.NODE_ENV);
const dev = process.env.NODE_ENV !== 'production';
const port = (process.env.PORT && parseInt(process.env.PORT, 10)) || 3080;
let subPort = port;
if(dev) {
subPort = (process.env.SUB_PORT && parseInt(process.env.SUB_PORT, 10)) || 3081;
}
const nextServer = createNextServer({ dev });
const nextRequestHandler = nextServer.getRequestHandler();
nextServer.prepare().then(async () => {
const app = express();
const httpServer = http.createServer(app);
const options: WebSocket.ServerOptions = {
path: '/graphql',
};
if (dev) {
// Override to prevent conflicts with next12+ hmr
options.port = subPort;
} else {
options.server = httpServer;
}
console.log(JSON.stringify(options));
const subscriptionServer = SubscriptionServer.create(
{
// This is the `schema` we just created.
schema,
// These are imported from `graphql`.
execute,
subscribe
},
options
);
const apolloServer = new ApolloServer({
schema,
plugins: [
{
async serverWillStart() {
return {
async drainServer() {
subscriptionServer.close();
},
};
},
},
],
});
await apolloServer.start();
apolloServer.applyMiddleware({ app });
app.use((req, res) => nextRequestHandler(req, res));
httpServer.listen(port, () => {
console.log('dev ', dev);
console.log(`🚀 Http Server ready at http://localhost:${port}`);
console.log(
`🚀 GraphQL Server ready at http://localhost:${port}${apolloServer.graphqlPath}`
);
console.log(
`🚀 GraphQL Subscriptions ready at ws://localhost:${subPort}${apolloServer.graphqlPath}`
);
});
}); client using with-apollo import React from 'react';
import withApollo from 'next-with-apollo';
import { ApolloProvider } from '@apollo/react-hooks';
import { ApolloLink, split } from 'apollo-link';
import { HttpLink } from 'apollo-link-http';
import { WebSocketLink } from 'apollo-link-ws';
import { getMainDefinition } from 'apollo-utilities';
import { ApolloClient } from 'apollo-client';
import { InMemoryCache } from 'apollo-cache-inmemory';
import fetch from 'isomorphic-unfetch';
let ssrMode = typeof window == 'undefined';
const dev = process.env.NODE_ENV !== 'production';
console.log('ssrMode : ' + ssrMode + ' dev: '+dev);
const port = (process.env.PORT && parseInt(process.env.PORT, 10)) || 3000;
let wsPort = port;
if(dev) {
wsPort = (process.env.DEV_SUB_PORT && parseInt(process.env.DEV_SUB_PORT, 10)) || 3081;
}
let httpURI: string = '/graphql';
let wsURI = '';
if (ssrMode) {
httpURI = `http://localhost:${port}/graphql`;
wsURI = `ws://localhost:${wsPort}/graphql`;
} else {
let isHttps = window.location.protocol == 'https:';
wsURI =
(isHttps ? 'wss' : 'ws') +
'://' +
window.location.hostname +
':' +
wsPort +
'/graphql';
}
let httpLink: ApolloLink = new HttpLink({
uri: httpURI,
credentials: 'same-origin',
fetch: fetch,
});
let link = httpLink;
if (!ssrMode) {
let wsLink = new WebSocketLink({
uri: wsURI,
options: {
reconnect: true,
},
});
link = split(
({ query }) => {
const def = getMainDefinition(query);
return (
def.kind === 'OperationDefinition' &&
def.operation === 'subscription'
);
},
wsLink,
httpLink
);
}
export default withApollo(
({ initialState }) =>
new ApolloClient({
link: link,
ssrMode: ssrMode,
connectToDevTools: !ssrMode,
cache: new InMemoryCache().restore(initialState || {}),
}),
{
render: ({ Page, props }) => {
return (
<ApolloProvider client={props.apollo}>
<Page {...props} />
</ApolloProvider>
);
},
}
); |
I have the same problem (Next.js 12.1.4, Express server run on localhost:3001 with no intent of going to elsewhere ever) happening at random. For a while the error was happening but not preventing the app from working, now it kills some pages but not others, I added a component in one branch and now nothing in that branch loads. As far as I can tell it's not at all related to the code itself and everything I can find about it either says it's been fixed, has fixes for things I'm not using (e.g. nginx), or both. |
Same problem here, regular local server, no custom server (no express). Make the first load and the fast refresh buggy and slow. I'm using windows 11 and Node v16. |
|
where should i add the above server code in Nextjs |
@Raghu-M-S It just needs to be in its own file eg |
I have this same issue but I'm not using any customer server. Running Next.js 12 on Windows 11 with wsl2 |
This closed issue has been automatically locked because it had no new activity for a month. If you are running into a similar issue, please create a new issue with the steps to reproduce. Thank you. |
What version of Next.js are you using?
12.0.1
What version of Node.js are you using?
12.22.3
What browser are you using?
Brave
What operating system are you using?
macOS
How are you deploying your application?
next start
Describe the Bug
After upgrading to Next.js 12, I'm getting the following error while running the app in
dev
mode:We're using nginx to proxy the domain, so that we actually have a domain name, rather than just using localhost. I can't think of any other gotchas that might be contributing factors.
The error repeats every few seconds, on a regular interval, and eventually floods the browser console. I am not seeing any errors printed to the terminal.
Expected Behavior
No errors!
To Reproduce
n/a
The text was updated successfully, but these errors were encountered: