Express Session Not Working— Fixed [Complete Guide 2026]
⚡ Complete Working Setup
Install and configure express-session before all routes:
npm install express-sessionconst session = require('express-session')
app.use(session({
secret: process.env.SESSION_SECRET,
resave: false,
saveUninitialized: false,
cookie: {
secure: false, // true only in production with HTTPS
httpOnly: true,
maxAge: 24 * 60 * 60 * 1000 // 24 hours
}
}))Why Is Your Express Session Not Working?
Express does not have session management built in. The express-session package must be installed separately, configured correctly, and added to your app before routes. Sessions fail for several distinct reasons — identify yours in the table below:
| Symptom | Cause | Fix |
|---|---|---|
| req.session is undefined | express-session not installed or configured | Jump → |
| Session set but lost after page reload | Cookie not sent back / wrong cookie config | Jump → |
| Sessions work locally, fail cross-origin | CORS credentials not configured | Jump → |
| Session lost in production (HTTPS) | secure: true but wrong proxy setup | Jump → |
| Sessions lost on server restart | Default memory store — use persistent store | Jump → |
| Cookie visible in DevTools but ignored | SameSite or domain mismatch | Jump → |
Install and Configure express-session
req.session is undefinednpm install express-sessionMinimum working configuration
require('dotenv').config()
const express = require('express')
const session = require('express-session')
const app = express()
app.use(express.json())
// Session middleware — before routes
app.use(session({
secret: process.env.SESSION_SECRET || 'dev-secret-change-in-production',
resave: false,
saveUninitialized: false,
cookie: {
secure: false, // set true only with HTTPS
httpOnly: true, // prevents XSS access to cookie
maxAge: 1000 * 60 * 60 * 24 // 24 hours in milliseconds
}
}))
// Now req.session is available in all routes
app.post('/login', (req, res) => {
req.session.userId = 'user123'
req.session.isLoggedIn = true
res.json({ message: 'Logged in' })
})
app.get('/profile', (req, res) => {
if (!req.session.userId) {
return res.status(401).json({ error: 'Not authenticated' })
}
res.json({ userId: req.session.userId })
})
app.post('/logout', (req, res) => {
req.session.destroy((err) => {
if (err) return res.status(500).json({ error: 'Logout failed' })
res.clearCookie('connect.sid')
res.json({ message: 'Logged out' })
})
})Generate a secure session secret
node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"
# Copy the output to your .env file:
# SESSION_SECRET=a1b2c3d4e5f6...Never hardcode the session secret in source code. Store it in .env and load it with dotenv. A leaked session secret allows anyone to forge session cookies.
Middleware Order Matters
Session undefined for some routesExpress applies middleware in the order it is defined. If session middleware is added after a route, that route cannot access req.session.
// ❌ WRONG — session added after route
app.get('/profile', (req, res) => {
console.log(req.session) // undefined!
})
app.use(session({ secret: '...' })) // too late
// ✅ CORRECT — session before all routes
app.use(session({ secret: process.env.SESSION_SECRET, resave: false, saveUninitialized: false }))
app.use(cors())
app.use(express.json())
app.get('/profile', (req, res) => {
console.log(req.session) // populated!
})Correct order: cors → session → body parsers → routes → error handler. Session must come before any route that uses req.session.
Fix CORS with Credentials (Cross-Origin)
Session works locally but not cross-originWhen your frontend (e.g. React on port 3000) and backend (Express on port 5000) run on different origins, cookies are not sent by default. You must enable credentials on both sides.
const cors = require('cors')
app.use(cors({
origin: 'http://localhost:3000', // exact frontend origin
credentials: true, // allow cookies
}))Frontend — fetch API
// Must include credentials: 'include' in every request
fetch('http://localhost:5000/api/login', {
method: 'POST',
credentials: 'include', // ← send and receive cookies
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email: 'user@example.com', password: 'pass' })
})Frontend — Axios
import axios from 'axios'
// Set globally (recommended)
axios.defaults.withCredentials = true
// Or per-request
axios.post('http://localhost:5000/api/login', data, {
withCredentials: true
})When credentials: true, you CANNOT use origin: '*'. You must specify the exact frontend URL. Using wildcard with credentials will cause the browser to reject the response.
Fix Cookie Settings for Production (HTTPS)
Sessions work locally but fail in productionWhen deploying to production with HTTPS, cookie settings must be updated. The secure: true flag tells the browser to only send the cookie over HTTPS — but if Node.js is behind a proxy (nginx, Heroku, AWS), you need to tell Express to trust it.
// Tell Express to trust the proxy (nginx, load balancer, etc.)
app.set('trust proxy', 1)
app.use(session({
secret: process.env.SESSION_SECRET,
resave: false,
saveUninitialized: false,
cookie: {
secure: process.env.NODE_ENV === 'production', // HTTPS only in prod
httpOnly: true,
maxAge: 1000 * 60 * 60 * 24 * 7, // 1 week
sameSite: process.env.NODE_ENV === 'production' ? 'none' : 'lax',
}
}))app.set('trust proxy', 1) is required on Heroku, Railway, Render, and any deployment behind a reverse proxy. Without it, Express sees all requests as HTTP even when they arrive over HTTPS.
Use Persistent Session Store (Production)
Sessions lost on server restartThe default express-session store is in-memory. It loses all sessions every time the server restarts and cannot be shared across multiple Node.js processes. For production, use a database-backed store.
Option A — MongoDB store (connect-mongo)
npm install connect-mongoconst MongoStore = require('connect-mongo')
app.use(session({
secret: process.env.SESSION_SECRET,
resave: false,
saveUninitialized: false,
store: MongoStore.create({
mongoUrl: process.env.MONGODB_URI,
ttl: 14 * 24 * 60 * 60, // 14 days in seconds
autoRemove: 'native',
}),
cookie: {
secure: process.env.NODE_ENV === 'production',
httpOnly: true,
maxAge: 14 * 24 * 60 * 60 * 1000, // 14 days in ms
}
}))Option B — Redis store (connect-redis)
npm install connect-redis redisconst { createClient } = require('redis')
const connectRedis = require('connect-redis')
const redisClient = createClient({ url: process.env.REDIS_URL })
redisClient.connect()
const RedisStore = connectRedis(session)
app.use(session({
store: new RedisStore({ client: redisClient }),
secret: process.env.SESSION_SECRET,
resave: false,
saveUninitialized: false,
cookie: { secure: true, httpOnly: true, maxAge: 86400000 }
}))Redis is faster than MongoDB for session storage and is the industry standard for high-traffic production apps. MongoDB is simpler if you are already using it for your database.
Session Not Persisting Between Requests
Session set but not available on next requestIf you set session data in one route but it is gone in the next request, the session cookie is not being sent back to the server. Check these:
Debug — log session on every request
app.use((req, res, next) => {
console.log('Session ID:', req.sessionID)
console.log('Session data:', req.session)
next()
})Common causes
- Frontend not sending credentials: 'include' — add to every fetch call
- CORS not configured with credentials: true
- Cookie domain mismatch — localhost vs 127.0.0.1 are different origins
- SameSite: 'strict' blocking cross-origin requests
- Cookie expired — check maxAge value
Verify cookie in browser DevTools
Open browser DevTools → Application tab → Cookies → check that connect.sid cookie exists after login. If it does not appear, the server is not setting it. If it appears but is not sent, it is a CORS or SameSite issue.
SameSite Cookie Issues
Cookie set but not sent on cross-site requestsModern browsers enforce SameSite cookie policies. If your frontend and backend are on different domains (not just ports), you need sameSite: 'none' with secure: true.
app.use(session({
secret: process.env.SESSION_SECRET,
resave: false,
saveUninitialized: false,
cookie: {
// Same origin (localhost dev): 'lax' works
// Cross-origin (different domains): 'none' + secure: true
sameSite: process.env.NODE_ENV === 'production' ? 'none' : 'lax',
secure: process.env.NODE_ENV === 'production',
httpOnly: true,
maxAge: 86400000
}
}))sameSite: 'none' requires secure: true. Browsers reject sameSite: 'none' cookies without the Secure flag. This means cross-origin sessions only work in production over HTTPS.
Session vs JWT — When to Use Each
| Factor | Sessions (express-session) | JWT tokens |
|---|---|---|
| State | Server-side (in store) | Stateless (in token) |
| Revoke login | Instant — delete from store | Cannot revoke until expiry |
| Scalability | Needs shared store (Redis) | Scales horizontally easily |
| Best for | Traditional web apps, SSR | REST APIs, mobile, SPA |
| Security | More control | Token theft is harder to recover from |
How to Prevent Session Issues
- Always store session secret in .env — never hardcode it
- Use connect-mongo or connect-redis in production — never default memory store
- Set app.set('trust proxy', 1) when behind nginx or any reverse proxy
- Add credentials: true to CORS and credentials: 'include' to frontend fetch
- Use sameSite: 'none' with secure: true only in production over HTTPS
- Log req.sessionID on each request during debugging to trace session flow
Frequently Asked Questions
Why is req.session undefined in Express?+−
Express session not persisting between requests?+−
Session not working across different domains (CORS)?+−
What should I use as a session secret?+−
express-session vs JWT — which should I use?+−
Session cookie not being set in browser?+−
Need Expert Help?
We Build Production-Grade Node.js Apps
Softplix builds full-stack Node.js applications. Struggling with authentication or session management in production? We can help.
Talk to an Engineer