DEV Community

Nivethan
Nivethan

Posted on • Originally published at nivethan.dev

Express Sessions with a SQLite Backend

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:

https://nivethan.dev/devlog/express-sessions.html

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

https://nivethan.dev/devlog/setting-up-authentication-in-node.html

The first step as always:

npm install better-sqlite3
npm install better-sqlite3-session-store
Enter fullscreen mode Exit fullscreen mode

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();

app.use(session({
    proxy: process.env.ENV === 'production',
    store: new SqliteStore({
        client: sessionsDB,
    }),
    secret: process.env.SECRET,
    resave: true,
    saveUninitialized: false,
    cookie: {},
}));
Enter fullscreen mode Exit fullscreen mode

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

Top comments (0)