Igor P.
Igor P.

Reputation: 1477

Node.Js: Signed cookie can't be found

Using a MEAN environment (with express 4), I create a cookie like this.

//webserver.js
app.use(cookieParser(„somesecretkey“));

//somescript.js
res.cookie(‚testcookie‘, ‚testvalue', {signed: true, maxAge: 999999, httpOnly: true}); 

In another script, I try to check the existence of the cookie like this.

//someotherscript.js
if(req.cookies.testcookie){   
        console.log("COOKIE EXISTS“+req.cookies.testcookie); 
}else{
        console.log(„NO COOKIE“+req.cookies.testcookie); //always undefined
}   

I checked the browser for the cookie and it definitely exists but the console keeps logging that there is no cookie (cookie undefined) when I press refresh or simply visit the page. As soon as I change the cookie to unsigned and remove the secret key, I can access it!? Why can’t the cookie be found once its signed?

Upvotes: 0

Views: 873

Answers (1)

jcaron
jcaron

Reputation: 17710

The expressjs documentation for res.cookie tells us:

When using cookie-parser middleware, this method also supports signed cookies. Simply include the signed option set to true. Then res.cookie() will use the secret passed to cookieParser(secret) to sign the value.

res.cookie('name', 'tobi', { signed: true });

Later you may access this value through the req.signedCookie object.

So:

  • did you specific a secret using cookieParser?
  • you should check for the cookie in req.signedCookie, not req.cookies

Upvotes: 1

Related Questions