cheatsheets devlog projects

express-sessions.md

Express Sessions

2022-11-13 3

This is my notes for the express-sessions library. This is middleware for express that adds support for sessions. The default uses an in memory store that leaks memory. However it is quite easy to set up a different backend.

The first step:

npm install express-sessions

The second step as always, is to update app.js:

var session = require('express-session')

var app = express();

app.use(session({
    proxy: process.env.ENV === 'production',
    secret: process.env.SECRET,
    resave: true,
    saveUninitialized: false,
    cookie: {},
}));

The proxy flag sets it so express trusts cookies sent to it by a reverse proxy like nginx. This is needed when the cookie is in secure mode which it should be in production. This would require https but if you use a reverse proxy, this https is already handled at that level and the request is simply passed to node.

Now we are ready to use sessions!

This is what a very bad user login system would look like.

var express = require('express');
var router = express.Router();

router.get('/login', function(req, res, next) {
    res.render("login", {});
});

router.post('/login', function(req, res, next) {
    if (req.body.username !== "nivethan") {
        return res.send("Invalid username.");
    }
    if (req.body.password !== "123") {
        return res.send("Invalid password.");
    }

    req.session.loggedIn = true;

    res.redirect("/");
});

router.get('/logout', function(req, res, next) {
    req.session.destroy();
    return res.redirect("/");
});

module.exports = router;

When a user logs in we set the loggedIn flag on the session.

We can then use add our own session middleware to check for a valid session.

This would be routes/validateAdmin.js:

module.exports = (req, res, next) => req.session && req.session.loggedIn
    ? next()
    : res.redirect("/login");

This will check for a session before handling the request. If the session doesn’t exist it will redirect back to the login page.

Now we can do the following:

var express = require('express');
var router = express.Router();

var validateAccess = require("./validateAccess");

router.get('/admin/', validateAdmin, async function(req, res, next) {
    res.render("admin", {});
});

Voila! We have used sessions to enable logging in.