skip to Main Content

I’m trying to emit upon any socket.io event, but haven’t been able to. I have a react app with frontend and backend, socket.io installed on the backend and socket.io-client on the frontend.

I have a socketServer.js:

const registerSocketServer = (server) => {
  const io = require("socket.io")(server, {
    cors: {
      origin: "*",
      methods: ["GET", "POST"],
    },
  });

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

module.exports = {
  registerSocketServer,
};

Which is imported into my server.js:

const express = require("express");
const http = require("http");
const cors = require("cors");
const mongoose = require("mongoose");
require("dotenv").config();

const socketServer = require("./socketServer");
const authRoutes = require("./routes/authRoutes");

const PORT = process.env.PORT || process.env.API_PORT;

const app = express();
app.use(express.json());
app.use(cors());

app.use("/api/auth", authRoutes);

const server = http.createServer(app);
socketServer.registerSocketServer(server);

mongoose
  .connect(process.env.MONGO_URL)
  .then(() => {
    server.listen(PORT, () => {
      console.log(`Server is listening on ${PORT}`);
    });
  })
  .catch((err) => {
    console.log("Database connection failed. Server not started");
    console.error(err);
  });

On my frontend, I have a function just to connect to the socket Server:

import io from "socket.io-client";

let socket = null;

export const connectWithSocketServer = (userDetails) => {
  socket = io("http://localhost:5002");

  socket.on("connection", () => {
    console.log("succesfully connected with socket.io server");
    console.log(socket.id);
  });
};

Then I’m just calling that function in another component.

I have gone through multiple tutorials, all with more or less the same setup as above. Is there something I am missing or is this code outdated?

I was expecting a console.log to appear.

2

Answers


  1. In your frontend, instead of this:

    socket = io("http://localhost:5002");
    

    try this:

    const socket = io("http://localhost:5002", {
      transports: ["websocket"],
      cors: {
        origin: "http://localhost:5002"
      }
    })
    

    I was able to get sockets working in my app, but I use python as the backend. I’d be happy to share the backend code if you want to try and draw comparisons between the two.

    Login or Signup to reply.
  2. The "connection" event is emitted on the server side when a new socket is connected, but on the client side, you should listen for the "connect" event. Try updating your frontend code as follows:

    import io from "socket.io-client";
    
    let socket = null;
    
    export const connectWithSocketServer = (userDetails) => {
      socket = io("http://localhost:5002");
    
      socket.on("connect", () => {
        console.log("succesfully connected with socket.io server");
        console.log(socket.id);
      });
    };
    

    Now, when you call the connectWithSocketServer function in your component, you should see the expected console logs when the connection is established.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search