Skip to content

fix(auth): make authContext a globalThis singleton - #180

Merged
cpojer merged 1 commit into
mainfrom
fix/auth-context-singleton
May 7, 2026
Merged

cpojer merged 1 commit into
mainfrom
fix/auth-context-singleton

Conversation

@TheAlexLichter

@TheAlexLichter TheAlexLichter commented May 5, 2026 •

Copy link
Copy Markdown
Member

This PR Fixes a dev bug where getUser() / getSession() from void/auth returned null even though runVoidAuthMiddleware had populated the request with a valid user.

The Root cause: runtime/auth.ts was evaluated twice:

  • Once by void's bundled runtime (which calls authContext.run(...) from the middleware)
  • Once by Vite's SSR module runner (which user code reaches through import { getUser } from "void/auth"). Each evaluation created its own top-level new AsyncLocalStorage()

The fix involves storing authContext on globalThis keyed by Symbol.for("void.authContext.v1"), so duplicate module evaluations within the same JS realm reuse a single AsyncLocalStorage.

In dev, Vite's SSR module runner and void's bundled runtime can each
evaluate runtime/auth.ts, producing two separate AsyncLocalStorage
instances. runVoidAuthMiddleware writes to the bundled instance while
user-land getUser()/getSession() read the SSR instance, so loaders
always saw a null user even when the cookie and session were valid.

Store the ALS on globalThis under Symbol.for("void.authContext.v1") so
duplicate module evaluations share a single instance. Add a regression
test that uses vi.resetModules() to force re-evaluation and verifies
both copies expose the same authContext, including write-through-static
read-through-fresh propagation.
@TheAlexLichter
TheAlexLichter marked this pull request as ready for review May 5, 2026 07:18
@cpojer

cpojer commented May 6, 2026

Copy link
Copy Markdown
Member

Is storing on globalThis the only option we have here? Is it possible to make a separate module that is deduplicated and loaded only once?

@TheAlexLichter

TheAlexLichter commented May 6, 2026 •

Copy link
Copy Markdown
Member Author

I don't think so, because of how the module is loaded via workerd and Vite's SSR runner.

A separate module would still run through both "envs"

@cpojer

cpojer commented May 6, 2026

Copy link
Copy Markdown
Member

Yeah, I figured. I'll take a look and merge/update this PR.

@cpojer cpojer left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Alright, looks like that's our only option.

@cpojer
cpojer merged commit 1ffc5f1 into main May 7, 2026
9 checks passed
@cpojer
cpojer deleted the fix/auth-context-singleton branch May 7, 2026 00:36
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.

2 participants