Search code examples
node.jstypescriptexpresssessionnodemon

How do I get a persistent session working with Express.js/Nodemon?


My TypeScript server is based on this example project. Whenever nodemon restarts my server, whether automatic or manually, I lose my session and have to log in again. I hate this because it's a massive waste of time when done for the 1000th time. I've tried to configure my Express.js session settings, but nothing seems to be working. Here's my configuration:

/**
* Configure application
*
* @class Server
* @method config
*/
public config() {
    //add static paths
    this.app.use(express.static(path.join(__dirname, 'public')));

    //configure pug
    this.app.set('views', path.join(__dirname, 'views'));
    this.app.set('view engine', 'ejs');

    //use logger middlware
    this.app.use(logger('dev'));

    //use json form parser middlware
    this.app.use(bodyParser.json());

    //use query string parser middlware
    this.app.use(bodyParser.urlencoded({
        extended: true
    }));

    this.app.use(cookieParser("my secret"));
    this.app.use(session({
        name: 'MyStudio',
        secret: "my secret",
        resave: false,
        saveUninitialized: false,
        cookie: {
            maxAge: 86400000,
            httpOnly: true,
            secure: false
        }
    }));
    this.app.use(passport.initialize());
    this.app.use(passport.session());
    //this.app.set('trust proxy', 1) // trust first proxy

    this.app.set('json spaces', 4);

    passport.serializeUser((user, done) => {
        return done(null, user);
    });

    passport.deserializeUser((user, done) => {
        return done(null, user);
    });

    passport.use('local-login', new Local.Strategy(
        (username, password, done) => {
            // My custom login logic
        }
    ));

    this.app.use(methodOverride());
}

How do I stop Express.js from losing my session on every restart?


Solution

  • express-session has support for different stores (databases) to store the session data in.

    The default that is used is MemoryStore which keeps session data in memory for as long as the Express process runs. When the Express process stops (for instance, when it restarts), all session data is gone.

    If you want session data to survive restarts, you need to use a persistent session store. Instead of storing the session data in memory, these store the session data in (for instance) a database. There are plenty of persistent session stores available, a list of which can be found here: https://github.com/expressjs/session#compatible-session-stores