req.session is undefined in an Express route
TypeError: Cannot read properties of undefined (reading 'views')Short answer
express-session only attaches req.session when its middleware runs first and can reach its store. It skips the request, without an error, when it is mounted after the route, when the store reports disconnected, or when the request path falls outside the cookie path. Find which one applies, then fix the order, the store connection or the path.
Fix it fast
1Find out which cause you have
Log req.session at the top of the failing route, and again in a tiny middleware right after session(). If the second log is defined and the first is not, order or path is the cause.
app.use(session(sessionOptions)); app.use((req, res, next) => { console.log('after session:', typeof req.session); next(); });2Match what you see, then jump to its fix
- 1
It is undefined on every request to that route, from the first callThe session middleware is mounted after the route that uses itFix - 2
It works after start-up, then fails once Redis or the database drops, and recovers after reconnectThe session store lost its connectionFix - 3
It is undefined for some URLs (such as /admin) and defined for othersThe request path is outside the session cookie pathFix
- 1
What does the error look like?
TypeError: Cannot read properties of undefined (reading 'views')TypeError: Cannot set properties of undefined (setting 'user')req.session is undefined only on some requests
Cause 1 of 3
The session middleware is mounted after the route that uses it
1Check
Express runs middleware in the order it is added. The docs' own examples add session() before the routes that read req.session.
grep -n "session(\|app.use\|app.get\|app.post\|Router" app.js2Fix
Move app.use(session(...)) above every router and route that touches req.session.
app.use(session({ secret: process.env.SESSION_SECRET, resave: false, saveUninitialized: false }));
app.use('/api', apiRouter);3Verify
Hit the route and confirm the value is an object.
curl -s -c jar.txt -b jar.txt http://localhost:3000/viewsConfirmed by raw.githubusercontent.com
Cause 2 of 3
The session store lost its connection
1Check
The middleware listens for the store's disconnect event. While the store is marked disconnected, it calls next() and treats the request as if there were no session.
redis-cli ping2Fix
Restore the store connection, and make your code handle a missing session instead of crashing.
app.use((req, res, next) => {
if (!req.session) return next(new Error('session store unavailable'));
next();
});3Verify
Stop and restart the store while sending requests. You should see the 500 only during the outage.
curl -i http://localhost:3000/viewsConfirmed by raw.githubusercontent.com
Cause 3 of 3
The request path is outside the session cookie path
1Check
The middleware compares the request path with cookie.path (default '/'). When the path does not match, it skips the request and sets no session.
grep -n "path:" app.js2Fix
Leave cookie.path at '/' unless you want the session on a prefix only. If you set it, mount the middleware for that prefix and read the session only there.
app.use(session({
secret: process.env.SESSION_SECRET,
resave: false,
saveUninitialized: false,
cookie: { path: '/' },
}));3Verify
Request a route outside the old path and confirm it has a session.
curl -s -c jar.txt http://localhost:3000/admin/pingConfirmed by raw.githubusercontent.com
How do I stop it coming back?
- Register session() before any router, and keep it in one place.
- Use a production store with reconnect logging; the default MemoryStore is only for development.
- Keep cookie.path at the default unless a prefix-only session is a deliberate choice.
Sources
How was this page made?
I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.
Which stack is behind this page?
Projects of mine built on the same technologies:
Related fixes
Back end
Passport logs the user in but req.isAuthenticated() returns false on the next request
req.user is undefined on the next request
req.isAuthenticated() only checks that req.user is set.
4 causes, each with a fixBack end
Angular app shows 'Cannot GET /' when served by a Node.js server
Cannot GET /dashboard
Cannot GET / is Express saying no route or file matches the request.
3 causes, each with a fixBack end
Axios call from a React app comes back 404
404 (Not Found)
Status code 404 means a server answered, but it has nothing at that path.
3 causes, each with a fixBack end
bcrypt.hash throws 'data and salt arguments required'
Error: data and hash arguments required
The bcrypt package throws this when hash gets null or undefined for the password or for the salt.
4 causes, each with a fixBack end
bcryptjs rejects hash() or compare() with Illegal arguments
Error: Illegal arguments: string, undefined
bcryptjs checks the types of its two arguments and, when either is wrong, throws Illegal arguments followed by the typeof of the first and the second.
3 causes, each with a fixBack end
Express warns 'body-parser deprecated undefined extended'
body-parser deprecated undefined extended
The warning appears because urlencoded() was called without the extended option, which body-parser 1.x has warned about since version 1.4.0.
3 causes, each with a fix