create Websocket with custom NextJS server

Viewed 20

I'm runnung NextJS application with a custom server to establish a websocket between the frontend and the custom backend.

Here is the custom server:

const express = require("express");
const next = require("next");
const emitter = require("./lib/eventEmitter");

const port = parseInt(process.env.PORT, 10) || 3000;
const dev = process.env.NODE_ENV !== "production";
const app = next({ dev });
const handle = app.getRequestHandler();
const server = express();
const http = require('http')
const socketIo = require("socket.io");
const wbServer = http.createServer(server)

const io = socketIo(wbServer);

io.on("connection", (socket) => {
  console.log("client connected: ", socket.id);
});

app.prepare().then(() => {

  server.all("*", (req, res) => {
    return handle(req, res);
  });

  server.listen(port, () => {
    console.log(`> Ready on http://localhost:${port}`);
  });
});

Here is the frontend connection:

  useEffect(() => {
    (async () => {
      let socket = io("http://localhost:3000");

      socket.on("connected", () => {
        console.log("Connected");
      });
    })();
  });

but it's not connecting React is showing 404 error like this:

XHR GET http://localhost:3000/socket.io?EIO=4&transport=polling&t=ODFLYBM
[HTTP/1.1 404 Not Found 8ms]
1 Answers

The answer is listening to wbServer instead of server like this:

const server = require("http").Server(app);

server.listen(port, () => {
  console.log(`> Ready on http://localhost:${port}`);
});
Related