Node.jsExpressError Fix2026 Updated

Express Session Not Working— Fixed [Complete Guide 2026]

January 20267 min readExpress · Node.js · All OS

⚡ Complete Working Setup

Install and configure express-session before all routes:

terminal
npm install express-session
server.js
const 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:

SymptomCauseFix
req.session is undefinedexpress-session not installed or configuredJump →
Session set but lost after page reloadCookie not sent back / wrong cookie configJump →
Sessions work locally, fail cross-originCORS credentials not configuredJump →
Session lost in production (HTTPS)secure: true but wrong proxy setupJump →
Sessions lost on server restartDefault memory store — use persistent storeJump →
Cookie visible in DevTools but ignoredSameSite or domain mismatchJump →
1

Install and Configure express-session

req.session is undefined
3 min
terminal
npm install express-session

Minimum working configuration

server.js
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

terminal
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.

2

Middleware Order Matters

Session undefined for some routes
1 min

Express applies middleware in the order it is defined. If session middleware is added after a route, that route cannot access req.session.

server.js
// ❌ 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.

3

Fix CORS with Credentials (Cross-Origin)

Session works locally but not cross-origin
3 min

When 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.

server.js — backend
const cors = require('cors')

app.use(cors({
  origin: 'http://localhost:3000',   // exact frontend origin
  credentials: true,                  // allow cookies
}))

Frontend — fetch API

Frontend JavaScript
// 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

Frontend JavaScript
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.

4

Fix Cookie Settings for Production (HTTPS)

Sessions work locally but fail in production
3 min

When 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.

server.js — production config
// 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.

5

Use Persistent Session Store (Production)

Sessions lost on server restart
5 min

The 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)

terminal
npm install connect-mongo
server.js
const 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)

terminal
npm install connect-redis redis
server.js
const { 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.

6

Session Not Persisting Between Requests

Session set but not available on next request
2 min

If 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

server.js — temporary debug
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.

7

SameSite Cookie Issues

Cookie set but not sent on cross-site requests
2 min

Modern browsers enforce SameSite cookie policies. If your frontend and backend are on different domains (not just ports), you need sameSite: 'none' with secure: true.

server.js
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

FactorSessions (express-session)JWT tokens
StateServer-side (in store)Stateless (in token)
Revoke loginInstant — delete from storeCannot revoke until expiry
ScalabilityNeeds shared store (Redis)Scales horizontally easily
Best forTraditional web apps, SSRREST APIs, mobile, SPA
SecurityMore controlToken theft is harder to recover from

How to Prevent Session Issues

Frequently Asked Questions

Why is req.session undefined in Express?+
express-session middleware is not installed or not added to your app. Install it with npm install express-session, then add app.use(session({ secret: 'your-secret', resave: false, saveUninitialized: false })) before your routes.
Express session not persisting between requests?+
The default memory store loses sessions on server restart and is not suitable for production. For development, check that the session cookie is being sent back with each request. For production, use connect-mongo or connect-redis as the session store.
Session not working across different domains (CORS)?+
Add credentials: true to your CORS config: app.use(cors({ origin: 'http://localhost:3000', credentials: true })). In your frontend, add credentials: 'include' to fetch calls or axios.defaults.withCredentials = true.
What should I use as a session secret?+
A long random string stored in your .env file. Generate one with: node -e "console.log(require('crypto').randomBytes(32).toString('hex'))". Never hardcode it in source code.
express-session vs JWT — which should I use?+
Sessions store state on the server and work well for traditional web apps with server-side rendering. JWT tokens are stateless and better for REST APIs, mobile apps, and microservices. Both are valid — choose based on your architecture.
Session cookie not being set in browser?+
Check three things: 1) secure: false in development (HTTP), 2) sameSite setting matches your setup, 3) If cross-origin: credentials: true in cors and credentials: 'include' in frontend fetch. Use browser DevTools > Application > Cookies to debug.

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