Why does my Next.js 13 app keep getting 'WebSocket connection failed' error on server deployment?

huangapple go评论70阅读模式
英文:

Why does my Next.js 13 app keep getting 'WebSocket connection failed' error on server deployment?

问题

WebSocket连接到''失败:WebSocket在连接建立之前就关闭了。

WebSocket连接到''失败:WebSocket在连接建立之前就关闭了。

我正在使用nextjs 13,在服务器上部署后,我不断遇到这个问题。

我尝试在next.config.js中禁用WebSocket,如下所示:

// 禁用WebSocket HMR
experimental: {
  disableWebpackHMR: true,
},

我还创建了一个server.js文件,如下所示:

const { createServer } = require('http');
const { parse } = require('url');
const next = require('next');

const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const handle = app.getRequestHandler();

app.prepare().then(() => {
    createServer((req, res) => {
        const parsedUrl = parse(req.url, true);
        handle(req, res, parsedUrl);
    }).listen(3000, (

<details>
<summary>英文:</summary>

WebSocket connection to &#39;&lt;URL&gt;&#39; failed: WebSocket is closed before the connection is established

WebSocket connection to &lt;&#39;URL&#39;&gt; failed: WebSocket is closed before the connection is established.

I&#39;m using nextjs 13, once i deploy on server i keep getting this issue continuously.

i tried to do this in next.config.js to disble websocket,


// Disable WebSocket HMR
experimental: {
disableWebpackHMR: true,
},

i also created one server.js file,


const { createServer } = require('http');
const { parse } = require('url');
const next = require('next');

const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const handle = app.getRequestHandler();

app.prepare().then(() => {
createServer((req, res) => {
const parsedUrl = parse(req.url, true);
handle(req, res, parsedUrl);
}).listen(3000, (err) => {
if (err) throw err;
console.log('> Ready on http://localhost:3000');
});
});



I tried these things to get rid of the issue. On local there is no error but once i deploy i keep getting these errors. Please guys help me out. Thanks in advance




</details>


# 答案1
**得分**: 0

我认为这是因为Next.js无法维持服务器和客户端之间的连接。您应该使用`express.js`库来维护连接。

***参考***
https://youtu.be/6xvLUWpCSFM

<details>
<summary>英文:</summary>

I think this is happening because nextjs can&#39;t maintain a connection between the server and client. You should use `express.js` library to maintain a connection.

***Refrence***
https://youtu.be/6xvLUWpCSFM


</details>



huangapple
  • 本文由 发表于 2023年5月24日 22:07:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/76324436.html
  • javascript
  • next.js
  • next.js13
  • webpack-hmr
  • websocket

如何使用` :?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定