Rob Rob - 1 month ago 12
Node.js Question

Express.js session undefined. Redis

Trying to get sessions set up with Redis. I have my Redis DB in a dokku container, linked to my app (also in a dokku container). I keep getting a session undefined.I've stripped things back to the bare minimum, also checked the order in which things are run. I still get an undefined.

I've read here 'session' is undefined when using express / redis for session store and Express js session undefined to no avail.

I shouldn't need to use cookie-parser, as expression-session has cookie stuff in it, and the docs say cookie-parser can cause problems with expression-session.

var express = require('express');
var session = require('express-session');
var redisStore = require('connect-redis')(session);
var bodyParser = require('body-parser');

var app = express();

app.set('port', (process.env.PORT || 5000));

var redisURL = 'redis://xxxxx:1234567@bar-redis-foo:6379';
var store = new redisStore({ url: redisURL });

app.use(session({
secret: 'ssshhhhh',
store: store,
saveUninitialized: true,
resave: true
}));


app.use(express.static(__dirname + '/public'));
app.use(bodyParser.json()); // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: true
}));

app.get('/', function(req, res, next) {
console.log(req.session); // Logs Undefined
res.send('Hello');
});

Answer

Check your redis connection and run again. Sample code is following line.

"use strict";

const express = require("express");
const bodyParser = require("body-parser");
const session = require("express-session");
const RedisStore = require("connect-redis")(session);

const app = express();

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

app.use(session({
    secret: "$kx(Fj$uB!Ug!@jCkguFmc6f7t<c-e$9",
    resave: false,
    saveUninitialized: true,
    store: new RedisStore({
        url: "redis://:********@pub-redis-12766.eu-central-1-1.1.ec2.redislabs.com:12766",
        ttl: 5 * 60 // 5 minute (Session store time)
    })
}));

app.use(function (request, response, next) {
    let path = request.originalUrl;

    if (request.session.user) {
        request.session.reload(function (err) { //session expire time regenerate
            if (!err) {
                next();
            } else {
                response.redirect('/login');
            }
        });
    } else {
        if (path == '/login') {
            next();
        } else {
            response.redirect('/login');
        }
    }
});

app.get('/', function(request, response) {
    if (request.session.user) {
        response.send(request.session.user);
    } else {
        response.redirect("/login");
    }
});

app.get('/login', function(request, response) {
    if (request.session.user) {
        response.redirect("/");
    } else {
        request.session.user = {username: "halil"}; //custom key {user} and custom data {username: "halil"}
    }

    response.send('Login');
});

app.get('/logout', function(request, response) {
    if (request.session.user) {
        request.session.destroy();
        response.redirect("/login");
    } else {
        response.redirect("/login");
    }
});

app.listen(app.get('port'), function () {
    console.log('App is working on port: ' + app.get('port'));
});