Ricardo Cruz Ricardo Cruz - 4 months ago 35
Node.js Question

Node.js session login

Node.js does not seem to be remembering my session.

I am using Express with

cookie-parser
and
express-session
as middleware.

In my application, I use Mongo to keep usernames and passwords.

The following is a MWE:

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

var app = express();
app.use(cookieParser({
secret: 'derma-aid'
}));
app.use(session({
secret: 'derma-aid',
resave: false,
saveUninitialized: false,
cookie: {secure: false}
}));

// CORS (Cross-Origin Resource Sharing) headers to support Cross-site HTTP requests
app.all('*', function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'X-Requested-With');
next();
});

app.get('/login', function(req, res)
{
console.log('login');
req.session.user_id = 500;
res.send('<h1>login</h1>');
});

app.get('/view', function(req, res)
{
console.log('view id: ' + req.session.user_id);
res.send('<h1>view: ' + req.session.user_id + '</h1>');
});

app.get('/logout', function(req, res)
{
console.log('logout: ' + req.session.user_id);
res.send('<h1>logout: ' + req.session.user_id + '</h1>');
delete req.session.user_id;
});

app.listen(5000);


If you go to the browser to
http://localhost:5000/login
, then
req.session.user_id
should be set and displayed correctly on
http://localhost:5000/view
.

But, instead, I am getting undefined messages...

EDIT:
cookie: {secure: false}
as suggested by @tiblu. I get this error:
TypeError: Secret string must be provided.
.

Answer

In your session middleware setup change from: cookie: {secure: true} to cookie: {secure: false}

Cookies marked as secure are not sent for NON-HTTPS requests. You are accessing your application over HTTP.

More reading on that https://en.wikipedia.org/wiki/HTTP_cookie#Secure_cookie

Comments