Skip to content

Commit 62abffc

Browse files
fix(auth): make authContext a globalThis singleton
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.
1 parent 680a55f commit 62abffc

2 files changed

Lines changed: 123 additions & 5 deletions

File tree

‎packages/void/src/runtime/auth.ts‎

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -25,12 +25,22 @@ export type VoidAuthConfig =
2525
/**
2626
* Shared AsyncLocalStorage that holds the authenticated Better Auth state for the
2727
* current request.
28+
*
29+
* Stored on `globalThis` under a `Symbol.for` key so duplicate module loads
30+
* (e.g. once by void's bundled runtime and once by Vite's SSR module runner
31+
* when user code imports from `void/auth`) share a single ALS instance. Without
32+
* this, the middleware writes to one instance and `getUser()` reads another,
33+
* always returning null.
2834
*/
29-
export const authContext: AsyncLocalStorage<{ user: AuthUser | null; state: AuthState | null }> =
30-
new AsyncLocalStorage<{
31-
user: AuthUser | null;
32-
state: AuthState | null;
33-
}>();
35+
type AuthContextStore = { user: AuthUser | null; state: AuthState | null };
36+
const AUTH_CONTEXT_SYMBOL: unique symbol = Symbol.for('void.authContext.v1');
37+
type GlobalWithAuthContext = {
38+
[AUTH_CONTEXT_SYMBOL]?: AsyncLocalStorage<AuthContextStore>;
39+
};
40+
const globalWithAuthContext = globalThis as GlobalWithAuthContext;
41+
export const authContext: AsyncLocalStorage<AuthContextStore> =
42+
globalWithAuthContext[AUTH_CONTEXT_SYMBOL] ??
43+
(globalWithAuthContext[AUTH_CONTEXT_SYMBOL] = new AsyncLocalStorage<AuthContextStore>());
3444

3545
export function defineAuth<T extends VoidAuthConfig>(config: T): T {
3646
return config;
Lines changed: 108 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,108 @@
1+
import { AsyncLocalStorage } from 'node:async_hooks';
2+
import { describe, expect, it, vi } from 'vitest';
3+
import {
4+
authContext,
5+
getSession,
6+
getUser,
7+
type AuthState,
8+
type AuthUser,
9+
} from '../../src/runtime/auth.ts';
10+
11+
const AUTH_CONTEXT_SYMBOL = Symbol.for('void.authContext.v1');
12+
13+
describe('authContext', () => {
14+
it('runs callback with provided store and exposes it via getUser/getSession', () => {
15+
const user = {
16+
id: 'u1',
17+
email: 'a@b.c',
18+
emailVerified: false,
19+
name: 'A',
20+
image: null,
21+
createdAt: new Date(0),
22+
updatedAt: new Date(0),
23+
} satisfies AuthUser;
24+
const state = {
25+
user,
26+
session: {
27+
id: 's1',
28+
token: 't1',
29+
userId: user.id,
30+
expiresAt: new Date(0),
31+
createdAt: new Date(0),
32+
updatedAt: new Date(0),
33+
},
34+
} satisfies AuthState;
35+
36+
expect(getUser()).toBeNull();
37+
expect(getSession()).toBeNull();
38+
39+
authContext.run({ user, state }, () => {
40+
expect(getUser()).toBe(user);
41+
expect(getSession()).toBe(state);
42+
});
43+
44+
expect(getUser()).toBeNull();
45+
expect(getSession()).toBeNull();
46+
});
47+
48+
it('is registered on globalThis under Symbol.for("void.authContext.v1")', () => {
49+
const stored = (globalThis as Record<symbol, unknown>)[AUTH_CONTEXT_SYMBOL];
50+
expect(stored).toBe(authContext);
51+
expect(stored).toBeInstanceOf(AsyncLocalStorage);
52+
});
53+
54+
it('returns the same ALS instance across module re-evaluations', async () => {
55+
// Regression guard for the original bug: when auth.ts is loaded twice
56+
// (e.g. once by void's bundled runtime, once by Vite's SSR module runner
57+
// resolving `void/auth` for user code), both evaluations must share one
58+
// AsyncLocalStorage. Otherwise middleware writes to one instance and
59+
// user-land getUser() reads another, always returning null.
60+
//
61+
// vi.resetModules() drops the module cache so the next dynamic import
62+
// re-evaluates auth.ts top-to-bottom — exactly the dual-load scenario.
63+
vi.resetModules();
64+
const first = await import('../../src/runtime/auth.ts');
65+
vi.resetModules();
66+
const second = await import('../../src/runtime/auth.ts');
67+
68+
expect(first.authContext).toBe(second.authContext);
69+
70+
// And the statically-imported binding at the top of this file is the same
71+
// instance as both re-evaluated copies — covers user-land import paths.
72+
expect(authContext).toBe(first.authContext);
73+
});
74+
75+
it('propagates store across a re-evaluated import boundary', async () => {
76+
// Tightens the previous test: the bug only surfaces when one side writes
77+
// and the other reads. Write through the statically-imported authContext,
78+
// read through a re-evaluated copy of getUser.
79+
vi.resetModules();
80+
const fresh = await import('../../src/runtime/auth.ts');
81+
82+
const user = {
83+
id: 'u2',
84+
email: 'c@d.e',
85+
emailVerified: false,
86+
name: 'B',
87+
image: null,
88+
createdAt: new Date(0),
89+
updatedAt: new Date(0),
90+
} satisfies AuthUser;
91+
const state = {
92+
user,
93+
session: {
94+
id: 's2',
95+
token: 't2',
96+
userId: user.id,
97+
expiresAt: new Date(0),
98+
createdAt: new Date(0),
99+
updatedAt: new Date(0),
100+
},
101+
} satisfies AuthState;
102+
103+
authContext.run({ user, state }, () => {
104+
expect(fresh.getUser()).toBe(user);
105+
expect(fresh.getSession()).toBe(state);
106+
});
107+
});
108+
});

0 commit comments

Comments
 (0)