Igor Malyk
Igor Malyk

Reputation: 2656

Get express encoded cookie as header value

Please see the communication description

  1. Client --- POST /login (no cookie yet) ---> Node Server
  2. Node Server ---> ‘set-cookie’ : ‘…’ -> Client (sets cookie and uses it for next requests)

How could I get encoded value of the cookie which is set as a set-cookie header before it is sent to the client on the first request ?

Express 3.x, cookieParser, expression-session and a mongo as a storage are used.

I tried:

  1. to access req.cookies but is not populated on the first request because client doesn't have a cookie yet.
  2. res.getHeader('set-cookie') returns undefined perhaps because it is set after express route handler is called by express-session.

At the server side how could I access either a set-cookie header in my handler or the cookie value in the response object even if request.cookie is empty ?

Upvotes: 3

Views: 1607

Answers (1)

Ivan Castellanos
Ivan Castellanos

Reputation: 8243

Almost a year later, but the reason you can't access is because express-session and other middlewares use a package called onHeaders which "Execute a listener when a response is about to write headers."

So you have to use it as well to modify the headers

var onHeaders = require('on-headers')
onHeaders(res, function(){
    // knock yourself out
    console.log(res.getHeader('set-cookie'));
});

Listeners are triggered in reverse order so for you to get the value this code (the listener) must be as soon as possible in your code.

Upvotes: 8

Related Questions