3

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 ?

3
  • Are you trying to access the cookie in code executed Clientside or Serverside? If it's clientside, the first time it sees the cookie is in the response. If it's serverside, look at the headers you're about to/have submitted to the client as you set it, or look at the received headers in requests from the client which arrive after it has been set. Commented Feb 4, 2015 at 17:20
  • Thanks for the comment. Edited the question, specified the server side is in question. The thing is when I check headers to be sent to the client in the node route handler with res.getHeader('set-cookie') it returns undefined. That's why I wonder if there is some special trick to do it. Commented Feb 4, 2015 at 17:23
  • Could you post the code where you set the cookie, and where you're checking the cookie. Commented Feb 4, 2015 at 17:45

1 Answer 1

8

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.