user3449782 user3449782 - 4 months ago 68
Node.js Question

Socket.io set cookie with nginx

My app architecture is here.


  • front-server 3000 - domain.com, serve files to browser

  • api-server 3001 - api.domain.com

  • socket-server 3003 - io.domain.com



In dev mode, socket request have all http request cookies,

But in production mode with nginx (down to conf),

socket cookie just have a cookie io


  • In dev
    enter image description here

  • In prod
    In prod



This is nginx conf(part of socket server).

server {
server_name io.domain.com;

location / {
include proxy_params;
proxy_redirect off;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-NginX-Proxy true;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header X-Forwared-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_http_version 1.1;
proxy_pass http://127.0.0.1:3003;
}
location /socket.io/ {
include proxy_params;
proxy_redirect off;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-NginX-Proxy true;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header X-Forwared-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_http_version 1.1;
proxy_pass http://127.0.0.1:3003;
}
}


Here is socket client

const io = require('socket.io-client');
let socket;

if (process.env.NODE_ENV === 'production') {
socket = io.connect('http://io.domain.com/noti');
} else {
socket = io.connect('http://localhost:3003/noti');
}

module.exports = socket;


In development env, it works well but in production mode because of the problem, I can't retrieve user values.

I need to use cookie value sessionId, token to auth, but two cookie values are disappeared.

What's wrong with it?

Answer

Most of all, Set cookie with domain.

For example in node js,

res.setCookie({...
    domain: 'domain.com'
});

And in nginx conf,

proxy_cookie_domain io.domain.com domain.com
Comments