Script Valley
Authentication From Scratch
Session-Based AuthenticationLesson 2.3

Storing sessions in a database instead of memory

MemoryStore limitations, production session stores, connect-pg-simple, connect-redis, session table schema, session store connection

Why MemoryStore Fails in Production

By default, express-session stores sessions in memory. This has two fatal flaws for production: all sessions are lost when the server restarts, and sessions cannot be shared across multiple server instances. Use a persistent store.

PostgreSQL Session Store

npm install connect-pg-simple pg
const pgSession = require('connect-pg-simple')(session);
const { Pool } = require('pg');

const pool = new Pool({ connectionString: process.env.DB_URL });

app.use(session({
  store: new pgSession({
    pool,
    tableName: 'user_sessions',
    createTableIfMissing: true
  }),
  secret: process.env.SESSION_SECRET,
  resave: false,
  saveUninitialized: false,
  cookie: { httpOnly: true, secure: true, sameSite: 'lax' }
}));

The createTableIfMissing: true option auto-creates the sessions table on first run. In production, prefer running the schema migration manually so you have full control over the table structure.

Redis Alternative

For high-traffic applications, Redis is a better session store than PostgreSQL due to its in-memory speed and built-in TTL support. Use connect-redis with the same API. The configuration is identical โ€” swap the store constructor and connection options.

Up next

Building login and logout routes with sessions

Sign in to track progress

Storing sessions in a database instead of memory โ€” Session-Based Authentication โ€” Authentication From Scratch โ€” Script Valley โ€” Script Valley