10

I thought I understood how Cookies worked, but I guess not since I'm stuck on the following:

I cannot display a cookie with document.cookie, testing with alert(document.cookie); in my code.

I am playing around with node and have the following code snippet up on my server (everything else works and serving pages with Express):

var express = require('express')
, util = require('util')
, MemoryStore = express.session.MemoryStore
, app = express.createServer()
, sessionStore = new MemoryStore();

app.configure(function() {
    app.set('views', __dirname + '/views');
    app.set('view engine', 'ejs');
    app.use(express.logger());
    app.use(express.cookieParser());
    app.use(express.bodyParser());
    app.use(express.methodOverride());
    app.use(express.session({ 
            store: sessionStore, 
            secret: 'BBQ12345AHHH',
            key: 'cookie.sid' }));
    app.use(app.router);
    app.use(express.static(__dirname + '/public'));
    });

On my server, I see a cookie being sent when I hit index.ejs. Chrome also shows a cookie being sent in the header on index.ejs. However, when I add alert(document.cookie) in the of the index.ejs page, the alert is blank. What am I doing wrong?

Thanks

gotta have my pops
  • 878
  • 4
  • 11
  • 22

2 Answers2

10

The Connect session cookies default to httpOnly which Chrome respects, I.E. the cookies are inaccessible by client side javascript.

A session cookie doesn't need to be read by client side javascript, unless it's by malicious XSS scripts so it's all good.

If you wanna override it though, try:

app.use(express.session({ 
  store: sessionStore, 
  secret: 'BBQ12345AHHH',
  cookie: {httpOnly: false},
  key: 'cookie.sid' }          
))

Source http://www.senchalabs.org/connect/session.html#session

Munawir
  • 3,346
  • 9
  • 33
  • 51
Esailija
  • 138,174
  • 23
  • 272
  • 326
  • so how can Node access a signed cookie later in the app? – vsync Aug 04 '13 at 23:16
  • 1
    @vsync first result on google for "signed cookie" `req.signedCookies['name']` – Esailija Aug 04 '13 at 23:25
  • 10x. it's best all the information will be here, in one place, instead of evil Google :) but when I read a signed encrypted cookie, does the server knows how to decrypt it using the same key? – vsync Aug 05 '13 at 19:21
0

Are you calling up the cookie right? I found this page helpful when i was learning:

http://www.quirksmode.org/js/cookies.html

PitaJ
  • 12,969
  • 6
  • 36
  • 55