cheatsheets devlog projects

Express Sessions with a SQLite Backend

2022-11-13 4

The default in memory store that is used in express-sessions results in memory leaks and isn’t recommended for production. However we can use postgres or sqlite as a session backend very easily.

These notes follow:

This will be the notes for the sqlite one and my pg notes can be found at:

The first step as always:

npm install better-sqlite3
npm install better-sqlite3-session-store

I need to install better-sqlite3 first because I use the sqlite3 package with sequelize for my orm. This does mean that I have 2 libraries that both handle sqlite. The better one is indeed better but not yet supported in sequelize.

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

var sqlite = require("better-sqlite3");
var SqliteStore = require("better-sqlite3-session-store")(session)
var sessionsDB = new sqlite("sessions.db");

var app = express();

    proxy: process.env.ENV === 'production',
    store: new SqliteStore({
        client: sessionsDB,
    secret: process.env.SECRET,
    resave: true,
    saveUninitialized: false,
    cookie: {},

Voila! We are done! Now sessions will be set and persisted through sessions.db. This file will be created at the app.js level.