4

Im trying to set cookies for my website using node.js and express.js. Heres a simplified version of my code:

var express = require('express');
var cookieParser = require('cookie-parser');

var app = express();
app.use(cookieParser());

app.post('/testCookies', function(req, res) {
   console.log(req.cookies); //empty object
   res.cookie('username', 'test');
   console.log(req.cookies); //still an empty object

   res.end();
});

I tried POSTing twice in case the cookies somehow get set after the request (im not very familiar with cookies yet) but it doesn't change anything. The console does not show any errors.

  • I'm not familiar with your stack but can't you simply set a cookie value like that : req.cookies.test = "somestring"; ? – noa-dev Apr 07 '16 at 07:50
  • According to [this stackoverflow question](http://stackoverflow.com/questions/12240274/how-to-set-cookie-value-in-node-js) and [this blogpost](https://www.codementor.io/nodejs/tutorial/cookie-management-in-express-js) you have to use `res.cookie(...)` – Benjamin Minixhofer Apr 07 '16 at 07:59
  • 1
    See Alex's Answer, thats what I am using as well. – noa-dev Apr 07 '16 at 08:02

1 Answers1

1

You could use req.session() instead. That would let you do

req.session.username = "test";

See the docs here.

Alex Logan
  • 1,221
  • 3
  • 18
  • 27