How to fix CORS error in Socket IO NodeJS

In this short tutorial, I will show you how you can fix CORS error in socket IO in NodeJS.

First, you need to use the socket IO import statement in following way:

const socketIO = require("socket.io")(http, {
	cors: {
		origin: "*"
	}
})

Then, with your Express app instance, you can set the following headers.

// Add headers before the routes are defined
app.use(function (req, res, next) {

    // Website you wish to allow to connect
    res.setHeader("Access-Control-Allow-Origin", "*")

    // Request methods you wish to allow
    res.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS, PUT, PATCH, DELETE")

    // Request headers you wish to allow
    res.setHeader("Access-Control-Allow-Headers", "X-Requested-With,content-type,Authorization")

    // Set to true if you need the website to include cookies in the requests sent
    // to the API (e.g. in case you use sessions)
    res.setHeader("Access-Control-Allow-Credentials", true)

    // Pass to next layer of middleware
    next()
})