3

I use Helmet with Express to set quite some security HTTP headers from the server side. This is nicely done, when rendering client pages on top of the node.js app, using:

var app = express();
app.use(helmet());
..
res.render("pages/index", data);

All the resources on the index page will have the Helmet headers. Unfortunately, socket.io does its own header management. So, anything that comes after /socket.io/ will have insecure/its own headers. For example here:

<https_path>/socket.io/socket.io.js
<https_path>/socket.io/?EIO=3&transport=polling&t=Lj4CFnj&sid=ILskOFWbHUaU6grTAAAA

Hence, I want to set custom headers for all socket.io items manually.

This is how I require socket.io (excerpt only):

/src/app.js

var express = require("express");
var sio = require("socket.io");
var app = express();
var io = require("./../lib/io.js").initialize(app.listen(REST_PORT, () => {
    logger.info("Application ready on port " + REST_PORT + " . Environment: " + NODE_ENV);
}));

/lib/io.js

exports = module.exports = {};
var sio = require("socket.io");
exports.initialize = function(server) {
    var options = {
        cookie: false,
        extraHeaders: {
        "X-Custom-Header-For-My-Project": "Custom stuff",
        }
    };
    io = sio(server, options);
    io.on("connection", function(socket) {
    // logic
)};

The "extraHeaders" option doesn´t work, I guess it could only with socket.io-client. I did large amount of googling around, but not luck on this.

Also looked around how to use socket.request (apparently it helps with headers, according to: here), but I couldn´t figure that out either.

Could you guys help?

1 Answer 1

6

extraHeaders options will work as below, as you need to remove "transports: ['polling']," in case you are using, and use below pattern. This worked for me, and was able to send custom headers.

package used :- "socket.io-client": "^2.2.0",

this.socket = io(environment.host, {
   path: `/api/backend/socket.io`,
   origins: '*:*',
   // transports: ['polling'],
   transportOptions: {
     polling: {
        extraHeaders: {
           'authorization': token,
           'user-id' : userId
        }
     }
    }
 })

Ref:- https://socket.io/docs/client-api/#With-extraHeaders

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.