k.k k.k - 1 year ago 233
Node.js Question

how to use express Session

I am a express freshman, I have a problem with session now. this code I can't store seesion. req.session.user is undefined, maybe the quession was the session not store. what's wrong of my code, please tell me my wrong please thanks

var express = require('express');
var bodyParser = require('body-parser');
var expressSession = require('express-session');
var cookieParser = require('cookie-parser');
var app = express();
secret: 'keyboard cat',
resave: false,
saveUninitialized: true,
cookie: { secure: true }
var auth = function(req, res, next) {
console.log(req.session.user); **this is undefined**
if (req.session && req.session.user === "amy" && req.session.admin)
return next();
return res.sendStatus(401);
app.get('/login', function (req, res) {
if (!req.query.username || !req.query.password) {
res.send('login failed');
} else if(req.query.username === "amy" || req.query.password === "amyspassword") {
req.session.user = "amy";
req.session.admin = true;
app.get('/logout', function (req, res) {
res.send("logout success!");
app.get('/content', auth, function (req, res) {
res.send("You can only see this after you've logged in.");

Answer Source

Instead of the current code you have for using express session try the following code.

    secret: 'keyboard cat',
    resave: false,
    saveUninitialized: true

secure: true although a recommended option requires an https-enabled website. HTTPS is necessary for storing secure cookies. If you set that option to true while using an HTTP only site without HTTPS the cookie will not be set which is why you were running into problems. The GitHub repo for express-session has some more detail regarding this.

So changing your code to that should work. Let me know if that doesn't make sense or if it still gives you problems.


Try also the following line of code inside your get /login route from:


To this:



To not have it automatically redirect but still save the session try the code below.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download