Session management — track user state across requests.
1const crypto = require("crypto");23class SessionStore {4 constructor(options = {}) {5 this.sessions = new Map();6 this.ttl = options.ttl || 3600000; // 1 hour7 this.cleanupInterval = setInterval(() => this.cleanup(), 60000);8 }910 create(data = {}) {11 const id = crypto.randomBytes(32).toString("hex");12 this.sessions.set(id, {13 data,14 createdAt: Date.now(),15 lastAccessed: Date.now(),16 });17 return id;18 }1920 get(id) {21 const session = this.sessions.get(id);22 if (!session) return null;2324 if (Date.now() - session.lastAccessed > this.ttl) {25 this.sessions.delete(id);26 return null;27 }2829 session.lastAccessed = Date.now();30 return session.data;31 }3233 set(id, data) {34 const session = this.sessions.get(id);35 if (session) {36 session.data = { ...session.data, ...data };37 session.lastAccessed = Date.now();38 }39 }4041 destroy(id) {42 this.sessions.delete(id);43 }4445 cleanup() {46 const now = Date.now();47 this.sessions.forEach((session, id) => {48 if (now - session.lastAccessed > this.ttl) {49 this.sessions.delete(id);50 }51 });52 }53}5455// Express middleware56const sessions = new SessionStore();5758app.use((req, res, next) => {59 const sessionId = req.headers.cookie?.match(/sid=([^;]+)/)?.[1];60 req.session = sessions.get(sessionId);6162 if (!req.session) {63 const id = sessions.create();64 res.setHeader("Set-Cookie", `sid=${id}; HttpOnly; SameSite=Strict`);65 req.session = sessions.get(id);66 }6768 next();69});