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.
