arpo arpo - 1 month ago 7x
Javascript Question

Cookies undefined on node js/express (localhost)

A Newbie question I guess. I want to set and get cookies on my express site.

cookieParser is set up and seems to run. But my cookies are always undefined. So what can be wrong? Doesn't cookies work on localhost?
I can access all cookies in the console on chrome.

I have tried both httpOnly: false/true.

Here's my code:

var express = require('express'),
exphbs = require('express-handlebars'),
bodyParser = require('body-parser'),
cookieParser = require('cookie-parser'),
request = require('request'),
livereload = require('express-livereload'),
port = Number(process.env.PORT || 3000);

var log = require('./lib/log.js'));

var app = express();

livereload(app, config = {watchDir: process.cwd()});

app.engine('handlebars', exphbs({defaultLayout: 'main'}));
app.set('view engine', 'handlebars');

app.use(bodyParser.urlencoded({ extended: true}));

app.get('/', function(req, res) {

.cookie('cart', 'test', {maxAge: 900000, httpOnly: false})



app.listen(port, function() {

log.out('Express on http://localhost:' + port);;


Any clues?

rsp rsp

Maybe you should change:




I just wrote a simple example that demonstrates what's going on:

var express = require('express');
var cookieParser = require('cookie-parser');
var app = express();
app.get('/', function(req, res) {
  var oldCookie = req.cookies.test;
  var newCookie = (oldCookie|0) + 1;
  res.cookie('test', newCookie, {maxAge: 900000});
    newCookie: newCookie,
    oldCookie: oldCookie,
    reqCookie: req.cookies.test,
app.listen(3000, function () {
  console.log('Listening on http://localhost:3000/');

When you run it and go with your browser to http://localhost:3000/ you will see:


When you reload the page you will see:


Here's what's going on: In the first request even though you set the cookie in you handler before printing it it is not really set yet - it is just queued to be passed to the client in the response with an HTTP header like this one:

Set-Cookie: test=1; Max-Age=900; Path=/; Expires=Wed, 21 Sep 2016 13:03:06 GMT

In the second request you see the old value in reqCookie and the new value in newCookie - those values are different. Seeting the cookie doesn't change the one that you got in the request. I even included the reqCookie which is not stored in a variable but accessed directly from req.cookies during the res.end() invocation to demonstrate that it is not changed.