Question

Is there a way that I can maintain the user session over a server restart to help keep my development nice and fast?

I'm working on an ExpressJS node project locally on my machine. I'm using Grunt-nodemon to watch my JS files and restart the server once i've made changes. What this means though is that any sessions on my project (there's a user log in) are wiped clean.

Currently if I'm in a deep page somewhere and restart, I'm kicked out to the log-in page and have to re-navigate which is really frustrating.

I'm using passport as the session middleware. I'm using mongoose as my main application datastore, if I can use that somehow that would be super.

Was it helpful?

Solution

It's very possible with the simple usage of any storage method.

One option is to use Redis.

Here is example that uses the connect-redis module:

    app.use(express.cookieParser());
    var session = require('express-session');
    var RedisStore = require('connect-redis')(session);
    app.use(express.session(
        {
            store: new RedisStore(
                {
                    host: '127.0.0.1',       //where redis store is
                    port: 6379,              //default redis port
                    prefix: 'sess',          //prefix for sessions name is store
                    pass: 'passwordtoredis'  //password to redis db
                }
            ),
            secret: 'cookiesecret',        //cookie secret
            key: 'express.sid'
        }

));

It could be more concisely, but it should work well.

Setting up redis is quite easy; the redis webpage has a great tutorial for that: http://redis.io/topics/quickstart

Please remember that redis by default stores the session in memory, which means that if you restart your hardware, the session will be lost (but there is an option to make it persist http://redis.io/topics/persistence)

Hope this helped :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top