Maaz Zindani

Loading the index…

↑↓ move↵ openesc close4072 pages
Node.js, PHP and APIs

req.session is undefined in an Express route

ErrorTypeError: 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.

  • Applies to express-session 1.18, Express 5, Node.js 22, connect-redis 8
  • Updated
  • By Maaz Zindani, Senior Software Engineer

Fix it fast

  1. 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(); });
  2. 2Match what you see, then jump to its fix

    1. 1It is undefined on every request to that route, from the first callThe session middleware is mounted after the route that uses itFix
    2. 2It works after start-up, then fails once Redis or the database drops, and recovers after reconnectThe session store lost its connectionFix
    3. 3It is undefined for some URLs (such as /admin) and defined for othersThe request path is outside the session cookie pathFix

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

2Fix

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/views

Confirmed by raw.githubusercontent.com

Did this fix it?

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 ping

2Fix

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/views

Confirmed by raw.githubusercontent.com

Did this fix it?

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

2Fix

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/ping

Confirmed by raw.githubusercontent.com

Did this fix it?

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

Next step

Want this handled for good?

I look after servers, apps and releases end to end. Tell me what keeps breaking.