Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use cookieSession in express

I'm trying to use the built in cookieSession object of connect, but I cannot get it to work properly with express.

I have this app:

var express = require('express');
var connect = require('connect');

var app = express.createServer();

app.configure(function() {
  app.use(express.logger());
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(express.cookieParser('whatever'));
  app.use(connect.cookieSession({ cookie: { maxAge: 60 * 60 * 1000 }}));
});

app.get('/', function(req, res) {
    res.render('root');
});

app.listen(3000);

I'm getting this error:

TypeError: Cannot read property 'connect.sess' of undefined
    at Object.cookieSession [as handle] 

Any ideas?

thanks

like image 327
mihai Avatar asked Mar 29 '12 12:03

mihai


People also ask

How do I use cookies in Express session?

var cookieSession = require('cookie-session') var express = require('express') var app = express() app. use(cookieSession({ name: 'session', keys: ['key1', 'key2'] })) // Update a value in the cookie so that the set-cookie will be sent. // Only changes every minute so that it's not sent with every request. app.

What is saveUninitialized in Express session?

saveUninitialized : When an empty session object is created and no properties are set, it is the uninitialized state. So, setting saveUninitialized to false will not save the session if it is not modified. The default value of both resave and saveUninitialized is true, but using the default is deprecated.

How do I clear an express session?

destroy(callback) Destroys the session and will unset the req. session property.


2 Answers

Sessions won't work unless you have these 3 in this order:

app.use(express.cookieParser());
app.use(express.cookieSession());
app.use(app.router);

Working like a charm after that.

see : https://stackoverflow.com/a/10239147/2454820

like image 51
Patrice Avatar answered Oct 13 '22 21:10

Patrice


What is the version of your connect module? The cookieSession middleware was first added in version 2.0.0. Run npm list|grep connect to make sure your connect version is at least 2.0.0 or higher.

like image 38
belltoy Avatar answered Oct 13 '22 22:10

belltoy