0

I'm running a Node.js application with HTTPS and Socket.IO on an AWS EC2 instance, behind NGINX. The REST APIs work fine, but the WebSocket connection to Socket.IO fails with a 400 Bad Request.

const app = express();
const { createServer } = require("http");  // Use HTTP not HTTPS
const { Server } = require("socket.io");

const httpServer = createServer(app);
const io = new Server(httpServer, {
  cors: {
    origin: ['https://abcdDomain.com', 'http://localhost:3000'],
    methods: ["GET", "POST"],
    credentials: true
  }
});

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

httpServer.listen(3001, () => {
  console.log("HTTP server running on port 3001");
});

1 Answer 1

1

According to documentation, when you get a 400 error when trying to connect, it usually means that

Usually, this means that a proxy in front of your server is not properly forwarding the WebSocket headers

Documentation also gives an example of the configuration you need to connect: Content of /etc/nginx/nginx.conf:

http {
  server {
    listen 80;

    location / {
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header Host $host;

      proxy_pass http://localhost:3000;

      proxy_http_version 1.1;
      proxy_set_header Upgrade $http_upgrade;
      proxy_set_header Connection "upgrade";
    }
  }
}
Sign up to request clarification or add additional context in comments.

Comments

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.