镜像站点 · 本页由第三方 GitHub 只读镜像提供,非 GitHub 官方站点,不接受任何登录或凭据输入。前往 github.com
Skip to content

fix: a store shared by two session() middlewares uses the last one's genid and cookie options - #1151

Open
yxshee wants to merge 1 commit into
expressjs:masterfrom
yxshee:fix/shared-store-generate
Open

yxshee wants to merge 1 commit into
expressjs:masterfrom
yxshee:fix/shared-store-generate

Conversation

@yxshee

@yxshee yxshee commented Nov 4, 2026

Copy link
Copy Markdown

Fixes #521.

When one store is passed to two session() middlewares, every request uses the options of the middleware registered last: its genid, cookie options and trust proxy setting. This also applies on req.session.regenerate().

const store = new session.MemoryStore()
app.use('/a', session({ name: 'a.sid', secret, store, genid: () => 'AAA-' + uid() }))
app.use('/b', session({ name: 'b.sid', secret, store, genid: () => 'BBB-' + uid() }))
// GET /a on master -> Set-Cookie: a.sid=s%3ABBB-...

Root cause: session() assigns its generator to store.generate, so the last middleware to be created overwrites it for every middleware sharing that store. Store.prototype.regenerate calls this.generate(req) too.

Fix: each middleware keeps its own generateSession. It records that function on the request in a non-enumerable property, next to req.sessionStore. store.generate(req) then calls the generator recorded on the request, and falls back to the last-created one as before. So a single-middleware app behaves the same, and so does code that calls store.generate directly. Stores that inherit Store.prototype.regenerate get the right generator with no change.

Tests: two cases under genid option, "when the store is shared". One checks the initial id and cookie, the other checks regenerate(). Both fail on master:

AssertionError: should set cookie apple.sid to s%3Aapple.D8Y...
Error: expected 'apple' response body, got 'banana'

With the fix: npm test 175 passing, npm run lint clean. A HISTORY.md entry is included.

session() assigned its generator to store.generate, so with one store passed
to several middlewares every request got the last middleware's genid and
cookie options, including on req.session.regenerate().

fixes expressjs#521
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Sharing session store between multiple session instances doesn't work

1 participant