[Fixed] Cors headers not handled properly ( http requests are fine, but socke.io connections not)


anybody could help me out with this. The code below is not handling cors properly. When i send http request the headers coming back are fine, however trying to get a connection through socket.io-client i get no cors headers in response. Anybody knows why is that happening and how to fix it?

const express = require("express");
const http = require('http')
const app = express();
const socket = require("socket.io");
const cors = require("cors");

app.options('*', cors())

app.get('/', (req,res)=>{
    res.send({e: 'elo'})
const server = http.createServer(app);

const io = socket(server);

io.on("connection", (socket) => {
  console.log("user connected to: ")
io.on("message", (data) => {


Socket IO handles CORS separately than express. See the following:

socket.io v2 docs

const io = socket(server, {
  origins: ["https://example.com"]

socket.io v3 docs

const io = socket(server, {
  cors: {
    origin: "https://example.com",
    methods: ["GET", "POST"]

In your case, you would pass * to the origin or origins property (depending on the version you are using) to allow all origins. Although locking it down to certain origins is recommended.

Leave a Reply

(*) Required, Your email will not be published