0

hello i am have created a socket in nodejs and used it in nextjs with reactjs, when working with localhost, it is working, when i put it on live server: "It returns FINISHED status in network request and in response I get: WebSocket is closed before the connection is established".

Below is my code:

//nodejs code
const server = express();
const customServer = http.createServer(server);

export const io = new Server(customServer, {
  cors: {
    origin: "*", // frontend URL
    methods: ["GET", "POST"],
    credentials: true,
  },
});

// Listen for connections
io.on("connection", (socket) => {
  console.log("A user connected:", socket.id);

  // User can join a private room
  socket.on("joinRoom", (userId) => {
    socket.join(userId);
    console.log(`User ${userId} joined room`);
  });

  socket.on("disconnect", () => {
    console.log("User disconnected:", socket.id);
  });
});

Below is my frontend code:

const socket = io("https://escortlisten.com", {//http://localhost:3001
    path: "/socket.io",
    transports: ["websocket"],
    withCredentials: true
});

I have also configured the nginx server, please check below:

location /socket.io {
        proxy_pass http://127.0.0.1:3001;  # Correct port
        proxy_http_version 1.1;

        # WebSocket headers
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "Upgrade";

        # Forward headers
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;

        # Long-lived connections
        proxy_read_timeout 36000s;
        proxy_send_timeout 36000s;
   }

Any small help will be really appreciated...

2
  • A wild guess - CORS origin: "*" is incompatible with the withCredentials: true. Try origin: "https://escortlisten.com" Commented Sep 24 at 10:34
  • @IvanShatsky still not working, getting "WebSocket is closed before the connection is established" Commented Sep 25 at 10:25

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.