Search code examples
javascriptnext.jswebsocketnext.js13webpack-hmr

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


WebSocket connection to '' failed: WebSocket is closed before the connection is established

WebSocket connection to <'URL'> failed: WebSocket is closed before the connection is established.

I'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


Solution

  • I think this is happening because nextjs can't maintain a connection between the server and client. You should use express.js library to maintain a connection.

    Refrence https://youtu.be/6xvLUWpCSFM