1

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');
});
Community
  • 1
  • 1
Rob
  • 1,576
  • 3
  • 22
  • 52

1 Answers1

3

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'));
});
Halil SAFAK
  • 377
  • 1
  • 6
  • Thanks Halil Ibrahim SAFAK - This also fails (however, I've upvoted it because its the best sample code I've seen so far). I'm now thinking my Redis connection is failing... However, I'm still trying to figure out how to check this. How would I log out a successful connection? If I change the password to junk - it throws an error (but this doesn't neccessarily mean that the correct password is connecting). – Rob Nov 07 '16 at 08:57
  • 1
    You can use redislabs(https://redislabs.com) for testing. A session occurs when a request is made from a computer. So it is not enough to check that only the session is established. For this reason it is necessary to add custom data. You can check this data to make transactions. When the user logs in, you can distinguish the user from the custom data added to the session value. – Halil SAFAK Nov 07 '16 at 10:51
  • Set up with Redislabs, and copied your example - and it works. Must be due to how I've installed Redis. Thanks! – Rob Nov 07 '16 at 11:55