Ludo Ludo - 5 months ago 47
Node.js Question

transfer cookies on a server/server request

In a universal app, i loose every users cookies on a server/server http request.
I have build a small nodeJS app that reproduce the thing:

const fetch = require('isomorphic-fetch');
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');
const session = require('express-session');

const server = require('express')();

server.use(bodyParser());
server.use(cookieParser());

server.use(session({
secret: 'foo',
httpOnly: false
}));

server.get('/set-cookies', (req, res) => {
req.session.user = { name: 'john doe' };
res.send('OK');
});

server.get('/a', (req, res) => {
console.log('COOKIE IN A = ', req.cookies); // Cookies are here !

const options = { credentials: 'include' };

fetch('http://localhost:3131/b', options)
.then( () => {
res.send('OK');
});
});

server.get('/b', (req, res) => {
console.log('COOKIES IN B = ', req.cookies); // Cookies are lost ! How to get it back ?
res.sendStatus(200);
});

server.listen(3131);


1) Hit GET /set-cookies
2) Hit GET /a (the cookies are here as expected)

Issue: When the /a controller will make an AJAX request to GET /b, it won't transfer the cookies, so the the route /b is unable to authenticate the user

How to transfer the users cookies on every requests ?
I have heard about "cookie jar" but i couldn't explain clearly what it is, and i didn't find any clean explanation on the web, if someone could share some knowledges about that, it would be great !

Answer

whatwg-fetch has option to send cookies by the following, but it doesn't seem to work.

fetch('http://localhost:3131/b', {
   credentials: 'same-origin'
});

You can send manually cookie to the fetch by the following way.

server.get('/a', (req, res) => {
    console.log('COOKIE IN A = ', req.cookies); // Cookies are here !
    const options = { 
       'headers' : {
          'Cookie': req.headers.cookie
        } 
    };

    fetch('http://localhost:3131/b', options)
       .then( () => {
          res.send('OK');
       });
});