DEV Community

Nivethan
Nivethan

Posted on • Originally published at nivethan.dev

5

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.

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

Cloudinary image

Optimize, customize, deliver, manage and analyze your images.

Remove background in all your web images at the same time, use outpainting to expand images with matching content, remove objects via open-set object detection and fill, recolor, crop, resize... Discover these and hundreds more ways to manage your web images and videos on a scale.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay