Security and hardening · Intermediate · 28 min
Secure sessions and cookies in an Express app
By Padding · Updated 18 Nov 2026
node:26 image (Debian) · Node.js 26.13.1 · Express 5.3.0 · express-session 1.19.0
You will prove five session flaws in Noticeboard's sign-in with failing tests, then fix them with express-session 1.19 and a SQLite store, leaving a __Host- cookie, new IDs at sign-in, idle and absolute timeouts, server-side sign-out, revocable sessions and a rotatable secret file.
On this page
A session is the server's memory of who you are between requests. The browser holds only a random ID in a cookie, and every request that carries that cookie is treated as you. So anyone who gets the ID, or gets you to use an ID they chose, is you until the session ends. OWASP lists these mistakes under A07:2025 Authentication Failures.
Part 1 gave Noticeboard a home-made session map with three FLAW comments in POST /signin and POST /signout. This part replaces it with express-session 1.19, the session middleware maintained by the Express project, and shows that a library does not make sessions safe on its own: the settings most examples copy keep the same flaws. You will build the sign-in slice of Noticeboard with those copied settings, prove five flaws with tests, and fix them one at a time:
- Session fixation. The ID a browser had before sign-in is still the ID after it.
- Weak cookie. The default cookie name, and no
SecureorSameSiteattribute. - No timeouts. A session lasts as long as the process, however long it sits unused.
- Client-only sign-out. "Sign out" asks the browser to forget the cookie, and a copy of it still works.
- No way to end other sessions. Changing the password leaves a phone or a café computer signed in.
The last step moves the signing secret out of the environment into a file that can hold two secrets at once, so you can rotate it without signing everyone out.
The ground rules from part 1 still apply. Work only on your own copy of Noticeboard, bound to 127.0.0.1, and never try these checks against a site you do not own or have written permission to test.
Step 1 · Create the sessions project
The sign-in slice lives in its own folder inside the demo, ~/noticeboard-demo/sessions, with its own package.json. That keeps the work from earlier parts untouched, and part 8's clean-up removes it with the rest of ~/noticeboard-demo. If you are starting the series here, the command below creates the demo folder too.
mkdir -p ~/noticeboard-demo/sessions/routes ~/noticeboard-demo/sessions/test/security
cd ~/noticeboard-demo/sessions
cat > package.json <<'JSON'
{
"name": "noticeboard-sessions",
"version": "1.0.0",
"private": true,
"type": "module",
"scripts": {
"start": "node --env-file=.env server.js",
"test": "node --test \"test/**/*.test.js\""
}
}
JSON
cat > .gitignore <<'TXT'
node_modules/
.env
secrets/
noticeboard-sessions.db
TXT
npm install --save-exact express@5.3.0 express-session@1.19.0--save-exact pins both packages, so your results match this page. The .gitignore already lists secrets/, the folder that will hold the signing secret in the last step.
Check it worked
npm ls express express-sessionThe tree lists express@5.3.0 and express-session@1.19.0. If node --version prints anything below v26, install Node.js 26 first (see the prerequisites): this project uses node:sqlite and import.meta.dirname, which older releases lack or handle differently.
Step 2 · Add sign-in with the copied defaults
The users table works as in earlier parts: two demo users share one password read from NOTICEBOARD_DEMO_PASSWORD, stored in plain text, which Argon2id hashing fixes. Create db.js and a one-function views.js for the HTML shell:
cat > db.js <<'JS'
import { DatabaseSync } from 'node:sqlite'
export function openDb(file = ':memory:') {
const password = process.env.NOTICEBOARD_DEMO_PASSWORD
if (!password) throw new Error('Set NOTICEBOARD_DEMO_PASSWORD (it lives in .env)')
const db = new DatabaseSync(file)
db.exec(`
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL UNIQUE,
password TEXT NOT NULL
);
`)
// Passwords in plain text are a known Noticeboard flaw, fixed in its own tutorial.
const addUser = db.prepare('INSERT OR IGNORE INTO users (name, password) VALUES (?, ?)')
addUser.run('amara', password)
addUser.run('bola', password)
return db
}
JS
cat > views.js <<'JS'
export const page = (title, body) => `<!doctype html>
<html lang="en"><head><meta charset="utf-8"><title>${title} - Noticeboard</title></head>
<body><main>${body}</main></body></html>`
JSAll session settings go in one file, session.js, so each fix touches one place. This first version is the snippet that most examples show, with resave and saveUninitialized both true and no cookie options. It also loads the signed-in user, and exports requireSignIn, which sends a signed-out visitor to the sign-in page and remembers where they were going:
cat > session.js <<'JS'
import session from 'express-session'
export function useSessions(app, { db, secrets }) {
// FLAW: copied defaults. Sessions live in process memory, every visitor gets one,
// the cookie keeps its default name with no Secure or SameSite, and nothing expires.
const store = new session.MemoryStore()
app.use(session({ secret: secrets, store, resave: true, saveUninitialized: true }))
const userById = db.prepare('SELECT id, name FROM users WHERE id = ?')
app.use((req, res, next) => {
req.user = req.session.userId ? userById.get(req.session.userId) : undefined
next()
})
return { store }
}
// Sends signed-out visitors to the sign-in page, which brings them back afterwards.
export function requireSignIn(req, res, next) {
if (req.user) return next()
req.session.returnTo = req.originalUrl
res.redirect(303, '/signin')
}
JSNow the routes. routes/auth.js signs people in and out; routes/account.js shows the account page and changes the password. Read the FLAW comments, which mark what the later steps fix:
cat > routes/auth.js <<'JS'
import { Router } from 'express'
import { page } from '../views.js'
export function authRouter(db) {
const router = Router()
const findUser = db.prepare('SELECT id, password FROM users WHERE name = ?')
router.get('/signin', (req, res) => {
res.send(page('Sign in', `<form method="post" action="/signin">
<label>Name <input name="name" autocomplete="username"></label>
<label>Password <input name="password" type="password" autocomplete="current-password"></label>
<button>Sign in</button></form>`))
})
router.post('/signin', (req, res) => {
const user = findUser.get(String(req.body?.name ?? ''))
if (!user || user.password !== req.body?.password) {
return res.status(401).send(page('Sign in', '<p>Wrong name or password.</p>'))
}
const returnTo = req.session.returnTo ?? '/account'
delete req.session.returnTo
// FLAW: keeps the session ID the browser arrived with (session fixation).
req.session.userId = user.id
res.redirect(303, returnTo)
})
router.post('/signout', (req, res) => {
// FLAW: tells the browser to forget the cookie; the session stays valid on the server.
res.clearCookie('connect.sid')
res.redirect(303, '/signin')
})
return router
}
JS
cat > routes/account.js <<'JS'
import { Router } from 'express'
import { page } from '../views.js'
import { requireSignIn } from '../session.js'
export function accountRouter(db, store) {
const router = Router()
const passwordOf = db.prepare('SELECT password FROM users WHERE id = ?')
const setPassword = db.prepare('UPDATE users SET password = ? WHERE id = ?')
router.use(requireSignIn)
router.get('/', (req, res) => {
res.send(page('Account', `<p>Signed in as ${req.user.name}</p>
<form method="post" action="/signout"><button>Sign out</button></form>`))
})
router.post('/password', (req, res) => {
const current = String(req.body?.current_password ?? '')
const next = String(req.body?.new_password ?? '')
if (passwordOf.get(req.user.id).password !== current || next.length < 12) {
return res.status(400).send(page('Account', '<p>Check your current password. The new one needs 12 characters or more.</p>'))
}
setPassword.run(next, req.user.id)
// FLAW: every other session for this user stays signed in.
res.redirect(303, '/account')
})
return router
}
JSWire it together in app.js, and start it from server.js on the loopback address only. The secret arrives as an array of one; express-session accepts a list, which matters in the last step:
cat > app.js <<'JS'
import express from 'express'
import { useSessions } from './session.js'
import { authRouter } from './routes/auth.js'
import { accountRouter } from './routes/account.js'
export function createApp({ db, ...options }) {
const app = express()
app.disable('x-powered-by')
app.use(express.urlencoded({ extended: false }))
const { store } = useSessions(app, { db, ...options })
app.use(authRouter(db))
app.use('/account', accountRouter(db, store))
app.use((err, req, res, next) => {
console.error(err)
res.status(500).type('text/plain').send('Something went wrong.')
})
return app
}
JS
cat > server.js <<'JS'
import path from 'node:path'
import { openDb } from './db.js'
import { createApp } from './app.js'
const PORT = Number(process.env.PORT ?? 3000)
if (!process.env.SESSION_SECRET) throw new Error('Set SESSION_SECRET (it lives in .env)')
const db = openDb(path.join(import.meta.dirname, 'noticeboard-sessions.db'))
const app = createApp({ db, secrets: [process.env.SESSION_SECRET] })
// Loopback only: other machines cannot connect.
app.listen(PORT, '127.0.0.1', (err) => {
if (err) throw err
console.log(`Noticeboard sessions on http://127.0.0.1:${PORT}`)
})
JS
if [ ! -f .env ]; then
(umask 077; node -p "'NOTICEBOARD_DEMO_PASSWORD=' + require('node:crypto').randomUUID() + '\nSESSION_SECRET=' + require('node:crypto').randomBytes(32).toString('base64url')" > .env)
fiThe last command writes a random demo password and a random 32-byte secret to .env, private to you from the moment it exists. No secret is written in the code.
Stop any earlier Noticeboard that is still running on port 3000, then start this one in your second terminal:
cd ~/noticeboard-demo/sessions
npm startBack in the first terminal, visit the account page signed out and look at the cookie that comes back:
curl -si http://127.0.0.1:3000/account | grep -i '^set-cookie'Check it worked
The second terminal shows Noticeboard sessions on http://127.0.0.1:3000. The curl line prints something like Set-Cookie: connect.sid=s%3A...; Path=/; HttpOnly. Three things in that line are worth noticing already: a visitor who has not signed in has been given a session, the name connect.sid tells anyone which library you use, and there is no Secure or SameSite attribute. HttpOnly is there because express-session sets it by default; part 3 showed why it matters.
Step 3 · Prove the flaws with a cookie jar
The tests need to behave like browsers: keep the cookies each response sets and send them back. Create test/helpers.js with a small Client class that does that, plus startApp, which starts a fresh copy of the app on a free port with an in-memory database.
The jar deliberately ignores Expires and Max-Age. A browser drops an expired cookie, but someone who copied the cookie does not, so the tests make the server prove that it refuses old sessions. Each request also sends X-Forwarded-Proto: https, the header an HTTPS reverse proxy such as nginx or Caddy adds in front of the app; you will need it once the cookie is Secure.
cat > test/helpers.js <<'JS'
import { randomBytes, randomUUID } from 'node:crypto'
import { openDb } from '../db.js'
import { createApp } from '../app.js'
process.env.NOTICEBOARD_DEMO_PASSWORD ??= randomUUID()
export const demoPassword = () => process.env.NOTICEBOARD_DEMO_PASSWORD
// Starts a copy of the app on a free port with an in-memory database.
export async function startApp(options = {}) {
const db = options.db ?? openDb()
const secrets = options.secrets ?? [randomBytes(32).toString('base64url')]
const app = createApp({ ...options, db, secrets })
const server = await new Promise((resolve, reject) => {
const s = app.listen(0, '127.0.0.1', (err) => (err ? reject(err) : resolve(s)))
})
return {
base: `http://127.0.0.1:${server.address().port}`,
db,
async close() {
server.closeAllConnections()
await new Promise((resolve) => server.close(resolve))
},
}
}
// One browser: a cookie jar plus fetch. The jar ignores Expires and Max-Age on purpose.
// A copied cookie does not expire because a browser would drop it; the server must refuse it.
export class Client {
constructor(base) {
this.base = base
this.jar = new Map()
this.setCookies = []
}
copyCookiesFrom(other) {
this.jar = new Map(other.jar)
return this
}
sessionCookie() {
return [...this.jar].find(([name]) => name.endsWith('sid'))?.[1]
}
async request(path, { method = 'GET', form } = {}) {
const cookie = [...this.jar].map(([name, value]) => `${name}=${value}`).join('; ')
// The app sits behind an HTTPS reverse proxy; the tests play the proxy's part.
const headers = { 'x-forwarded-proto': 'https', 'user-agent': 'noticeboard-test' }
if (cookie) headers.cookie = cookie
const res = await fetch(`${this.base}${path}`, {
method,
headers,
body: form ? new URLSearchParams(form) : undefined,
redirect: 'manual',
})
this.setCookies = res.headers.getSetCookie()
for (const line of this.setCookies) {
const pair = line.split(';')[0]
const i = pair.indexOf('=')
const name = pair.slice(0, i).trim()
const value = pair.slice(i + 1).trim()
if (value) this.jar.set(name, value)
else this.jar.delete(name)
}
return res
}
signIn(name = 'amara', password = demoPassword()) {
return this.request('/signin', { method: 'POST', form: { name, password } })
}
async isSignedIn() {
const res = await this.request('/account')
await res.text()
return res.status === 200
}
}
JSNow the security tests, one per rule. "Attacker", "laptop" and "phone" are just separate cookie jars. The first test is a control that passes today and must keep passing, so a fix that locks everyone out is caught too. The two timeout tests use limits of about a second, passed to createApp as options the app does not read yet:
cat > test/security/sessions.test.js <<'JS'
import { test } from 'node:test'
import assert from 'node:assert/strict'
import { randomUUID } from 'node:crypto'
import { startApp, Client, demoPassword } from '../helpers.js'
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms))
async function appFor(t, options) {
const app = await startApp(options)
t.after(() => app.close())
return app
}
test('control: the right password signs in and a wrong one does not', async (t) => {
const app = await appFor(t)
const wrong = new Client(app.base)
assert.equal((await wrong.signIn('amara', 'not-the-password')).status, 401)
const right = new Client(app.base)
assert.equal((await right.signIn()).status, 303)
assert.equal(await right.isSignedIn(), true)
})
test('A07: sign-in issues a new session ID', async (t) => {
const app = await appFor(t)
const browser = new Client(app.base)
await browser.request('/account') // signed out: the app remembers where to return
const before = browser.sessionCookie()
assert.ok(before, 'visiting /account signed out should start a session')
await browser.signIn()
assert.notEqual(browser.sessionCookie(), before)
})
test('A07: a session ID planted before sign-in is useless after it', async (t) => {
const app = await appFor(t)
const attacker = new Client(app.base)
await attacker.request('/account')
const victim = new Client(app.base).copyCookiesFrom(attacker)
assert.equal((await victim.signIn()).status, 303)
assert.equal(await victim.isSignedIn(), true)
assert.equal(await attacker.isSignedIn(), false, 'the planted ID is signed in as amara')
})
test('A07: the session cookie is __Host-sid with HttpOnly, Secure, SameSite=Lax and no Domain', async (t) => {
const app = await appFor(t)
const browser = new Client(app.base)
await browser.signIn()
const line = browser.setCookies.find((c) => /^[^=]*sid=/.test(c))
assert.ok(line, 'sign-in should set a session cookie')
assert.match(line, /^__Host-sid=/)
assert.match(line, /; Path=\/(;|$)/)
assert.match(line, /; HttpOnly/)
assert.match(line, /; Secure/)
assert.match(line, /; SameSite=Lax/)
assert.doesNotMatch(line, /; Domain=/i)
})
test('A07: sign-out ends the session on the server', async (t) => {
const app = await appFor(t)
const browser = new Client(app.base)
await browser.signIn()
const copied = new Client(app.base).copyCookiesFrom(browser)
await browser.request('/signout', { method: 'POST' })
assert.equal(await browser.isSignedIn(), false)
assert.equal(await copied.isSignedIn(), false, 'a copy of the cookie still works')
})
test('A07: changing the password signs out every other session', async (t) => {
const app = await appFor(t)
const laptop = new Client(app.base)
const phone = new Client(app.base)
await laptop.signIn()
await phone.signIn()
const res = await laptop.request('/account/password', {
method: 'POST',
form: { current_password: demoPassword(), new_password: randomUUID() },
})
assert.equal(res.status, 303)
assert.equal(await laptop.isSignedIn(), true)
assert.equal(await phone.isSignedIn(), false, 'the other session survived the password change')
})
test('A07: a user can list and revoke their other sessions', async (t) => {
const app = await appFor(t)
const laptop = new Client(app.base)
const phone = new Client(app.base)
await laptop.signIn()
await phone.signIn()
const list = await laptop.request('/account/sessions')
assert.equal(list.status, 200)
const sessions = await list.json()
assert.equal(sessions.length, 2)
const rawId = decodeURIComponent(laptop.sessionCookie()).slice(2).split('.')[0]
assert.ok(!JSON.stringify(sessions).includes(rawId), 'the list shows a raw session ID')
const other = sessions.find((s) => !s.current)
const revoke = await laptop.request('/account/sessions/revoke', { method: 'POST', form: { handle: other.handle } })
assert.equal(revoke.status, 303)
assert.equal(await phone.isSignedIn(), false)
assert.equal(await laptop.isSignedIn(), true)
})
test('A07: an idle session expires on the server', async (t) => {
const app = await appFor(t, { idleMs: 1000 })
const browser = new Client(app.base)
await browser.signIn()
await sleep(600)
assert.equal(await browser.isSignedIn(), true, 'activity inside the limit keeps the session')
await sleep(600)
assert.equal(await browser.isSignedIn(), true, 'each request should restart the idle clock')
await sleep(1500)
assert.equal(await browser.isSignedIn(), false, 'the session outlived its idle limit')
})
test('A07: a busy session still ends at the absolute limit', async (t) => {
const app = await appFor(t, { idleMs: 60_000, absoluteMs: 1500 })
const browser = new Client(app.base)
await browser.signIn()
for (let i = 0; i < 3; i++) {
await sleep(350)
assert.equal(await browser.isSignedIn(), true)
}
await sleep(1000)
assert.equal(await browser.isSignedIn(), false, 'the session outlived its absolute limit')
})
JSThe planted-ID test is session fixation in miniature. The attacker visits the site, gets a session ID, and finds a way to make the victim's browser use it, for example through a page on a sibling subdomain that sets cookies for the parent domain. When the victim signs in, the attacker's copy of the ID is signed in too.
Run the suite:
npm testCheck it worked
The summary at the end shows ℹ pass 1 and ℹ fail 8. The control passes. Each failure names its flaw: the session ID before and after sign-in are identical; the planted ID is signed in as amara; the cookie line starts connect.sid= and ends Path=/; HttpOnly; a copy of the cookie still works after sign-out; the other session survived the password change; /account/sessions answers 404; and both timeout tests report that the session outlived its limit. The two timeout tests take a few seconds each because they wait in real time.
Step 4 · Give the session a new ID at sign-in
The fix for fixation is one call: req.session.regenerate() deletes the old session and starts a new one with a new ID, and you then mark the new one as signed in. Anything you kept before sign-in is gone after regenerate, so copy across what you need. Here that is the page to return to, which is also checked to be a path on this site, so it cannot become an open redirect.
The same function records when the session started and which browser it was, which the timeout and session-list steps use. It is exported because the password change in a later step needs it too. Replace routes/auth.js:
cat > routes/auth.js <<'JS'
import { Router } from 'express'
import { page } from '../views.js'
// Swaps the session for a new one with a new ID, then marks it as signed in.
// Anything kept before sign-in (here, the page to return to) is copied across on purpose.
export async function beginSession(req, user) {
const saved = String(req.session.returnTo ?? '')
const returnTo = saved.startsWith('/') && !saved.startsWith('//') ? saved : '/account'
await new Promise((resolve, reject) => req.session.regenerate((err) => (err ? reject(err) : resolve())))
req.session.userId = user.id
req.session.signedInAt = Date.now()
req.session.userAgent = String(req.get('user-agent') ?? 'unknown').slice(0, 120)
return returnTo
}
export function authRouter(db) {
const router = Router()
const findUser = db.prepare('SELECT id, password FROM users WHERE name = ?')
router.get('/signin', (req, res) => {
res.send(page('Sign in', `<form method="post" action="/signin">
<label>Name <input name="name" autocomplete="username"></label>
<label>Password <input name="password" type="password" autocomplete="current-password"></label>
<button>Sign in</button></form>`))
})
router.post('/signin', async (req, res) => {
const user = findUser.get(String(req.body?.name ?? ''))
if (!user || user.password !== req.body?.password) {
return res.status(401).send(page('Sign in', '<p>Wrong name or password.</p>'))
}
res.redirect(303, await beginSession(req, user))
})
router.post('/signout', (req, res) => {
// FLAW: tells the browser to forget the cookie; the session stays valid on the server.
res.clearCookie('connect.sid')
res.redirect(303, '/signin')
})
return router
}
JSExpress 5 passes a rejected promise from an async handler to the error handler, so a store failure during regenerate becomes a 500 rather than a hung request.
Check it worked
npm testSix tests fail now instead of eight. The new-ID test and the planted-ID test pass: the attacker's copy gets a redirect to /signin, because the session it named no longer exists. The rule to remember is wider than sign-in: give the session a new ID whenever its privileges change, including a password change or a switch to an admin role.
Step 5 · Set the cookie attributes
Each attribute closes a different door:
HttpOnlykeeps the cookie out ofdocument.cookie, so an injected script cannot read the ID.Securemeans the browser sends the cookie over HTTPS only, so nobody on the same Wi-Fi can read it from a plain-HTTP request.SameSite=Laxstops the browser sending the cookie with cross-site form posts and background requests, the CSRF defence from part 4.Strictis tighter, but someone who taps a Noticeboard link in WhatsApp or an email would land signed out on the first page. Set it explicitly: browsers do not all apply the same default.- The
__Host-prefix makes the browser refuse the cookie unless it isSecure, hasPath=/and has noDomain. Without aDomain, the cookie belongs to this exact host, and a page on another subdomain cannot set or overwrite it, which is the route the fixation test imitated.
The name __Host-sid also stops advertising connect.sid. With Secure set, express-session will not send the cookie at all over plain HTTP. In production, HTTPS ends at a reverse proxy on the same machine, such as nginx or Caddy, which forwards to 127.0.0.1:3000 with an X-Forwarded-Proto: https header. trust proxy set to loopback tells Express to believe that header only when the request comes from this machine. Replace session.js:
cat > session.js <<'JS'
import session from 'express-session'
// __Host- tells the browser to accept this cookie only with Secure, Path=/ and no Domain.
export const COOKIE_NAME = '__Host-sid'
export const COOKIE_OPTIONS = { path: '/', httpOnly: true, secure: true, sameSite: 'lax' }
export function useSessions(app, { db, secrets }) {
// HTTPS ends at a reverse proxy on this machine; believe its X-Forwarded-Proto header.
app.set('trust proxy', 'loopback')
// FLAW (still): sessions live in process memory, every visitor gets one, nothing expires.
const store = new session.MemoryStore()
app.use(session({
name: COOKIE_NAME,
cookie: COOKIE_OPTIONS,
secret: secrets,
store,
resave: true,
saveUninitialized: true,
}))
const userById = db.prepare('SELECT id, name FROM users WHERE id = ?')
app.use((req, res, next) => {
req.user = req.session.userId ? userById.get(req.session.userId) : undefined
next()
})
return { store }
}
// Sends signed-out visitors to the sign-in page, which brings them back afterwards.
export function requireSignIn(req, res, next) {
if (req.user) return next()
req.session.returnTo = req.originalUrl
res.redirect(303, '/signin')
}
JSRestart the app: press Ctrl+C in the second terminal and run npm start again.
Ask for the account page twice, once as a plain-HTTP request and once as the proxy would forward an HTTPS one:
curl -si http://127.0.0.1:3000/account | grep -i '^set-cookie' || echo "no Set-Cookie header"
curl -si -H 'X-Forwarded-Proto: https' http://127.0.0.1:3000/account | grep -i '^set-cookie'Check it worked
The first request prints no Set-Cookie header. The second prints Set-Cookie: __Host-sid=s%3A...; Path=/; HttpOnly; Secure; SameSite=Lax. Run the tests too:
npm testFive tests fail; the cookie test now passes. From here on, signing in from a browser at http://127.0.0.1:3000 no longer keeps you signed in, because the app will not send its cookie over plain HTTP. That is the production behaviour you want. To click through it in a browser, put the app behind HTTPS with Caddy as a reverse proxy, which sets X-Forwarded-Proto for you; with nginx, add proxy_set_header X-Forwarded-Proto $scheme; as in the nginx reverse proxy tutorial.
Step 6 · Keep sessions in SQLite with idle and absolute timeouts
MemoryStore keeps sessions in the Node.js process. The express-session README says it is not meant for production: it grows without limit, every restart signs everyone out, and two processes cannot share it. It also cannot answer "which sessions belong to amara?", which the next step needs. Community stores exist for Redis, PostgreSQL and others; this one is under 100 lines on the node:sqlite module built into Node.js, so there is nothing to compile.
A store implements get, set, destroy and, optionally, touch. This one also records the user ID in its own column, refuses a session whose expiry has passed even if the row is still there, and can list a user's live sessions. Create store.js:
cat > store.js <<'JS'
import session from 'express-session'
// An express-session store in the app's SQLite database. Each row records the user it
// belongs to, so the app can list and end one user's sessions. Expired rows are refused.
export class SqliteStore extends session.Store {
constructor(db) {
super()
db.exec(`
CREATE TABLE IF NOT EXISTS sessions (
sid TEXT PRIMARY KEY,
user_id INTEGER,
data TEXT NOT NULL,
expires INTEGER NOT NULL
);
CREATE INDEX IF NOT EXISTS sessions_user ON sessions (user_id);
`)
this.sql = {
get: db.prepare('SELECT data, expires FROM sessions WHERE sid = ?'),
set: db.prepare(`INSERT INTO sessions (sid, user_id, data, expires) VALUES (?, ?, ?, ?)
ON CONFLICT (sid) DO UPDATE SET user_id = excluded.user_id, data = excluded.data, expires = excluded.expires`),
touch: db.prepare('UPDATE sessions SET expires = ? WHERE sid = ?'),
destroy: db.prepare('DELETE FROM sessions WHERE sid = ?'),
forUser: db.prepare('SELECT sid, data FROM sessions WHERE user_id = ? AND expires > ?'),
prune: db.prepare('DELETE FROM sessions WHERE expires <= ?'),
}
}
get(sid, cb) {
reply(cb, () => {
const row = this.sql.get.get(sid)
if (!row) return null
if (row.expires <= Date.now()) {
this.sql.destroy.run(sid)
return null
}
return JSON.parse(row.data)
})
}
set(sid, sess, cb) {
reply(cb, () => {
this.sql.set.run(sid, sess.userId ?? null, JSON.stringify(sess), expiry(sess))
})
}
touch(sid, sess, cb) {
reply(cb, () => {
this.sql.touch.run(expiry(sess), sid)
})
}
destroy(sid, cb) {
reply(cb, () => {
this.sql.destroy.run(sid)
})
}
// Live sessions for one user, as [{ sid, data }].
listForUser(userId) {
return this.sql.forUser.all(userId, Date.now()).map((row) => ({ sid: row.sid, data: JSON.parse(row.data) }))
}
prune() {
this.sql.prune.run(Date.now())
}
}
function expiry(sess) {
return new Date(sess.cookie.expires).getTime()
}
// express-session expects Node-style callbacks; node:sqlite is synchronous.
function reply(cb, work) {
let result
try {
result = work()
} catch (err) {
return process.nextTick(() => cb?.(err))
}
process.nextTick(() => cb?.(null, result))
}
JSBecause node:sqlite is synchronous, each change is in the database before the method returns; the callback only reports the result.
Then the timeouts. They answer different questions:
- Idle timeout: how long can a session sit unused? This is the cookie's
maxAge, and withrolling: trueevery response restarts the clock. The store enforces it on the server, so a copied cookie does not outlive it. - Absolute timeout: how long can a session last at all, however busy? A stolen session that the thief keeps alive with requests still ends. The app checks
signedInAton every request and, past the limit, swaps the session for an empty one.
The defaults below are 30 minutes idle and 8 hours absolute, the upper end of what the OWASP Session Management Cheat Sheet suggests for lower-risk apps; a banking or admin app should use much shorter limits. Shorter is also kinder on a shared or second-hand phone, or a café computer, where the next person picks up whatever the last one left signed in.
saveUninitialized: false and resave: false now replace the copied defaults: no row is written for a visitor until there is something to keep, and an unchanged session is touched rather than rewritten. Replace session.js:
cat > session.js <<'JS'
import session from 'express-session'
import { SqliteStore } from './store.js'
// __Host- tells the browser to accept this cookie only with Secure, Path=/ and no Domain.
export const COOKIE_NAME = '__Host-sid'
export const COOKIE_OPTIONS = { path: '/', httpOnly: true, secure: true, sameSite: 'lax' }
const MINUTE = 60_000
export function useSessions(app, { db, secrets, idleMs = 30 * MINUTE, absoluteMs = 8 * 60 * MINUTE }) {
// HTTPS ends at a reverse proxy on this machine; believe its X-Forwarded-Proto header.
app.set('trust proxy', 'loopback')
const store = new SqliteStore(db)
setInterval(() => store.prune(), 10 * MINUTE).unref()
app.use(session({
name: COOKIE_NAME,
cookie: { ...COOKIE_OPTIONS, maxAge: idleMs }, // idle timeout, enforced by the store
rolling: true, // every response restarts the idle clock
secret: secrets,
store,
resave: false,
saveUninitialized: false, // no session row until there is something to keep
}))
const userById = db.prepare('SELECT id, name FROM users WHERE id = ?')
app.use((req, res, next) => {
const { userId, signedInAt } = req.session
if (userId && Date.now() - signedInAt > absoluteMs) {
// Absolute timeout: however busy, a session ends this long after sign-in.
return req.session.regenerate((err) => next(err))
}
req.user = userId ? userById.get(userId) : undefined
next()
})
return { store }
}
// Sends signed-out visitors to the sign-in page, which brings them back afterwards.
export function requireSignIn(req, res, next) {
if (req.user) return next()
req.session.returnTo = req.originalUrl
res.redirect(303, '/signin')
}
JSRestart the app with Ctrl+C and npm start, then make one request and read the sessions table:
curl -s -o /dev/null -H 'X-Forwarded-Proto: https' http://127.0.0.1:3000/account
node --input-type=module -e "
import { DatabaseSync } from 'node:sqlite'
const db = new DatabaseSync('noticeboard-sessions.db', { readOnly: true })
for (const row of db.prepare('SELECT user_id, expires, data FROM sessions').all()) {
console.log({ user: row.user_id, minutesLeft: Math.round((row.expires - Date.now()) / 60000), returnTo: JSON.parse(row.data).returnTo })
}
"Check it worked
The query prints one row like { user: null, minutesLeft: 30, returnTo: '/account' }: a signed-out visitor who has something worth keeping, with 30 minutes to live. Now the tests:
npm testThree tests fail. Both timeout tests pass: requests 600 ms apart keep a one-second idle session alive, a 1.5-second gap ends it, and the busy session ends at its absolute limit. Sign-out, the password change and the session list are what remain.
Step 7 · Sign out on the server and revoke other sessions
Sign-out has to delete the session on the server; clearing the cookie is only a courtesy to the browser. req.session.destroy() removes the row, and res.clearCookie then needs the same name and attributes the cookie was set with, or the browser treats it as a different cookie and keeps the old one.
The account area gets two features:
GET /account/sessionslists the user's live sessions as JSON for a settings page: when each started, which browser, and which one is this one. It never shows a raw session ID. Each row gets a handle, the first 16 characters of a SHA-256 hash of the ID, which identifies the row without being usable as a cookie.POST /account/sessions/revokeends one of those sessions by handle. It only looks among the current user's sessions, so a handle belonging to someone else is simply not found.
A password change now ends every other session for that user, then calls beginSession so the current browser gets a fresh ID too. Someone who changes their password because they think it leaked expects whoever has it to be thrown out, not kept in.
Replace routes/auth.js with the version that signs out on the server:
cat > routes/auth.js <<'JS'
import { Router } from 'express'
import { page } from '../views.js'
import { COOKIE_NAME, COOKIE_OPTIONS } from '../session.js'
// Swaps the session for a new one with a new ID, then marks it as signed in.
// Anything kept before sign-in (here, the page to return to) is copied across on purpose.
export async function beginSession(req, user) {
const saved = String(req.session.returnTo ?? '')
const returnTo = saved.startsWith('/') && !saved.startsWith('//') ? saved : '/account'
await new Promise((resolve, reject) => req.session.regenerate((err) => (err ? reject(err) : resolve())))
req.session.userId = user.id
req.session.signedInAt = Date.now()
req.session.userAgent = String(req.get('user-agent') ?? 'unknown').slice(0, 120)
return returnTo
}
export function authRouter(db) {
const router = Router()
const findUser = db.prepare('SELECT id, password FROM users WHERE name = ?')
router.get('/signin', (req, res) => {
res.send(page('Sign in', `<form method="post" action="/signin">
<label>Name <input name="name" autocomplete="username"></label>
<label>Password <input name="password" type="password" autocomplete="current-password"></label>
<button>Sign in</button></form>`))
})
router.post('/signin', async (req, res) => {
const user = findUser.get(String(req.body?.name ?? ''))
if (!user || user.password !== req.body?.password) {
return res.status(401).send(page('Sign in', '<p>Wrong name or password.</p>'))
}
res.redirect(303, await beginSession(req, user))
})
router.post('/signout', (req, res, next) => {
// Delete the session on the server first, then ask the browser to drop the cookie.
req.session.destroy((err) => {
if (err) return next(err)
res.clearCookie(COOKIE_NAME, COOKIE_OPTIONS)
res.redirect(303, '/signin')
})
})
return router
}
JSThen replace routes/account.js:
cat > routes/account.js <<'JS'
import { Router } from 'express'
import { createHash } from 'node:crypto'
import { page } from '../views.js'
import { requireSignIn } from '../session.js'
import { beginSession } from './auth.js'
// A short, stable label for a session. It identifies a row without revealing the ID.
const handleFor = (sid) => createHash('sha256').update(sid).digest('base64url').slice(0, 16)
export function accountRouter(db, store) {
const router = Router()
const passwordOf = db.prepare('SELECT password FROM users WHERE id = ?')
const setPassword = db.prepare('UPDATE users SET password = ? WHERE id = ?')
router.use(requireSignIn)
router.get('/', (req, res) => {
res.send(page('Account', `<p>Signed in as ${req.user.name}</p>
<form method="post" action="/signout"><button>Sign out</button></form>`))
})
router.get('/sessions', (req, res) => {
res.json(store.listForUser(req.user.id).map(({ sid, data }) => ({
handle: handleFor(sid),
current: sid === req.sessionID,
signedInAt: new Date(data.signedInAt).toISOString(),
userAgent: data.userAgent,
})))
})
router.post('/sessions/revoke', (req, res) => {
const handle = String(req.body?.handle ?? '')
const target = store.listForUser(req.user.id).find(({ sid }) => handleFor(sid) === handle)
if (!target || target.sid === req.sessionID) return res.status(404).send(page('Account', '<p>No such session.</p>'))
store.destroy(target.sid)
res.redirect(303, '/account')
})
router.post('/password', async (req, res) => {
const current = String(req.body?.current_password ?? '')
const next = String(req.body?.new_password ?? '')
if (passwordOf.get(req.user.id).password !== current || next.length < 12) {
return res.status(400).send(page('Account', '<p>Check your current password. The new one needs 12 characters or more.</p>'))
}
setPassword.run(next, req.user.id)
// End every session this user has, then give this browser a fresh one.
for (const { sid } of store.listForUser(req.user.id)) {
if (sid !== req.sessionID) store.destroy(sid)
}
await beginSession(req, req.user)
res.redirect(303, '/account')
})
return router
}
JSBoth forms are POST, and the SameSite=Lax cookie means another site cannot submit them with the user's session. Part 4 adds tokens on top for older browsers and same-site attackers.
Check it worked
npm testAll nine tests pass, and the summary shows ℹ pass 9 and ℹ fail 0. The copied cookie gets a redirect to /signin after sign-out, the phone is signed out after the laptop changes the password, and the session list holds two entries with handles, neither of which contains the laptop's session ID.
Step 8 · Keep the secret in a file and rotate it
The secret signs the session cookie. It does not encrypt anything, but anyone who has it can make the app accept any session ID they choose, so it deserves the same care as a database password. Two changes make it easier to look after:
- A file, not an environment variable. Environment variables are inherited by every child process the app starts and often turn up in crash reports and debug dumps. A file can be readable by the app's user alone, and the app can refuse to start if it is not.
- More than one secret. express-session signs new cookies with the first secret in the array and accepts cookies signed with any of them. To rotate, put a new secret first and keep the old one second; each signed-in user's cookie is re-signed with the new secret on their next request, because
rollingsets the cookie on every response. Once the absolute timeout has passed, every session signed with the old secret has ended, and you can remove it.
Create the secrets folder and file. Both are private from the moment they exist:
cd ~/noticeboard-demo/sessions
mkdir -p -m 700 secrets
(umask 077 && node -p "require('node:crypto').randomBytes(32).toString('base64url')" > secrets/session-secrets)
ls -l secretsCreate secrets.js, which reads one secret per line, newest first, and refuses a file that group or others can read:
cat > secrets.js <<'JS'
import { readFileSync, statSync } from 'node:fs'
// Reads session secrets from a file: one per line, newest first. Blank lines and lines
// starting with # are ignored. The first secret signs new cookies; all of them verify.
export function loadSecrets(file) {
if (process.platform !== 'win32' && (statSync(file).mode & 0o077) !== 0) {
throw new Error(`${file} must not be readable by group or others`)
}
const secrets = readFileSync(file, 'utf8')
.split(/\r?\n/)
.map((line) => line.trim())
.filter((line) => line && !line.startsWith('#'))
if (secrets.length === 0) throw new Error(`${file} holds no secrets`)
if (secrets.some((s) => s.length < 32)) throw new Error(`every secret in ${file} needs 32 characters or more`)
return secrets
}
JSPoint server.js at the file. SESSION_SECRETS_FILE lets a server keep it elsewhere, for example /etc/noticeboard/session-secrets, owned by the user the app runs as:
cat > server.js <<'JS'
import path from 'node:path'
import { openDb } from './db.js'
import { createApp } from './app.js'
import { loadSecrets } from './secrets.js'
const PORT = Number(process.env.PORT ?? 3000)
const secretsFile = process.env.SESSION_SECRETS_FILE ?? path.join(import.meta.dirname, 'secrets', 'session-secrets')
const db = openDb(path.join(import.meta.dirname, 'noticeboard-sessions.db'))
const app = createApp({ db, secrets: loadSecrets(secretsFile) })
// Loopback only: other machines cannot connect.
app.listen(PORT, '127.0.0.1', (err) => {
if (err) throw err
console.log(`Noticeboard sessions on http://127.0.0.1:${PORT}`)
})
JSThe app no longer reads SESSION_SECRET, so take it out of .env. This writes a private copy without that line and puts it in place:
(umask 077 && grep -v '^SESSION_SECRET=' .env > .env.next)
mv .env.next .envAdd tests for the loader and for a full rotation. The rotation test restarts the app three times on one shared database: with the old secret, with both, and with the new secret alone:
cat > test/security/session-secrets.test.js <<'JS'
import { test } from 'node:test'
import assert from 'node:assert/strict'
import { chmod, mkdtemp, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import path from 'node:path'
import { randomBytes } from 'node:crypto'
import { openDb } from '../../db.js'
import { loadSecrets } from '../../secrets.js'
import { startApp, Client } from '../helpers.js'
const newSecret = () => randomBytes(32).toString('base64url')
test('loadSecrets reads one secret per line, newest first', async (t) => {
const dir = await mkdtemp(path.join(tmpdir(), 'nb-secrets-'))
t.after(() => rm(dir, { recursive: true, force: true }))
const [a, b] = [newSecret(), newSecret()]
const file = path.join(dir, 'session-secrets')
await writeFile(file, `# newest first\n${a}\n\n${b}\n`, { mode: 0o600 })
assert.deepEqual(loadSecrets(file), [a, b])
})
test('loadSecrets refuses a file that others can read', { skip: process.platform === 'win32' }, async (t) => {
const dir = await mkdtemp(path.join(tmpdir(), 'nb-secrets-'))
t.after(() => rm(dir, { recursive: true, force: true }))
const file = path.join(dir, 'session-secrets')
await writeFile(file, `${newSecret()}\n`)
await chmod(file, 0o644)
assert.throws(() => loadSecrets(file), /readable by group or others/)
})
test('rotation: an old cookie works during the overlap and stops once its secret is gone', async () => {
const db = openDb()
const [oldSecret, nextSecret] = [newSecret(), newSecret()]
const before = await startApp({ db, secrets: [oldSecret] })
const browser = new Client(before.base)
await browser.signIn()
const signedWithOld = new Client(before.base).copyCookiesFrom(browser)
await before.close()
// Restart with the new secret first and the old one still listed.
const overlap = await startApp({ db, secrets: [nextSecret, oldSecret] })
browser.base = signedWithOld.base = overlap.base
assert.equal(await browser.isSignedIn(), true, 'the old cookie should still work')
assert.notEqual(browser.sessionCookie(), signedWithOld.sessionCookie(), 'the reply should re-sign the cookie')
await overlap.close()
// Restart with the old secret removed.
const after = await startApp({ db, secrets: [nextSecret] })
browser.base = signedWithOld.base = after.base
assert.equal(await browser.isSignedIn(), true, 'the re-signed cookie should work')
assert.equal(await signedWithOld.isSignedIn(), false, 'a cookie signed with the removed secret still works')
await after.close()
db.close()
})
JS
npm testRestart the app with Ctrl+C and npm start so it reads the file.
When it is time to rotate, put a new secret at the top of the file, keep the old one below it, and restart the app:
(umask 077 && { node -p "require('node:crypto').randomBytes(32).toString('base64url')"; cat secrets/session-secrets; } > secrets/session-secrets.next)
mv secrets/session-secrets.next secrets/session-secrets
wc -l secrets/session-secretsAfter the absolute timeout (8 hours with the defaults) has passed, keep only the newest secret and restart once more:
(umask 077 && head -n 1 secrets/session-secrets > secrets/session-secrets.next)
mv secrets/session-secrets.next secrets/session-secrets
wc -l secrets/session-secretsCheck it worked
ls -l secrets shows session-secrets as -rw-------. npm test passes all 12 tests: the nine session tests and the three secret tests. The first wc -l prints 2 with the file name and the second prints 1, and after each restart the second terminal shows Noticeboard sessions on http://127.0.0.1:3000. If you made the file readable by others, the app would refuse to start with must not be readable by group or others rather than run with an exposed secret.
If a secret leaks, do not wait for the overlap: replace the file with a single new secret and restart. Every session ends at once and everyone signs in again, which is the right trade.
When you are done, stop the app with Ctrl+C. Keep ~/noticeboard-demo: part 8 adds regression tests across the series and then removes the whole folder.
Next steps
- Part 8 keeps these fixes from coming back, with security regression tests and custom Semgrep rules: /tutorials/add-security-regression-tests-and-semgrep-rules-to-the-app
- Replace Noticeboard's plain-text passwords, the flaw this part left alone: /tutorials/hash-passwords-with-argon2id
- If your API uses tokens rather than server-side sessions, avoid the mistakes that make them impossible to revoke: /tutorials/avoid-the-jwt-mistakes-that-break-api-security
- Go back over SameSite and CSRF tokens for Noticeboard's forms in part 4: /tutorials/protect-forms-from-csrf-with-samesite-cookies-and-tokens
Related tutorials
- Write custom Fail2ban jails and filters for your own appsYou will have Fail2ban 1.1 banning repeated failed sign-ins to your own app and to an nginx basic-auth area, with filters you tested against sample logs, your own addresses allow-listed, and longer bans for repeat offenders.
- Validate file uploads before you store or serve themYou will take a FastAPI image upload route that trusts everything the browser sends, prove its flaws with pytest, and rebuild it with size limits, type checks from the file's own bytes, Pillow re-encoding, random storage names and safe download headers.
- Use SSH certificates instead of copying keys to every serverYou will run a small SSH certificate authority with ssh-keygen, log in to an Ubuntu 26.04 server with an eight-hour user certificate, give the server a host certificate so clients stop asking about fingerprints, and revoke a certificate the server then refuses.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials