Skip to content

Commit 3a2b439

Browse files
authored
fix(astro): Construct derived state when als is empty (#5567)
1 parent 3ad3bc8 commit 3a2b439

File tree

2 files changed

+26
-6
lines changed

2 files changed

+26
-6
lines changed

.changeset/deep-moose-slide.md

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'@clerk/astro': patch
3+
---
4+
5+
Fixes issue with `useAuth()` erroring due to missing auth context on static output.

packages/astro/src/react/hooks.ts

+21-6
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { resolveAuthState } from '@clerk/shared/authorization';
2+
import { deriveState } from '@clerk/shared/deriveState';
23
import type {
34
CheckAuthorizationWithCustomPermissions,
45
Clerk,
@@ -83,7 +84,7 @@ type UseAuth = (options?: PendingSessionOptions) => UseAuthReturn;
8384
* }
8485
*/
8586
export const useAuth: UseAuth = ({ treatPendingAsSignedOut } = {}) => {
86-
const authContext = useStore($authStore);
87+
const authContext = useAuthStore();
8788
const clerkContext = useStore($clerkStore);
8889

8990
const getToken: GetToken = useCallback(createGetToken(), []);
@@ -139,14 +140,18 @@ export const useAuth: UseAuth = ({ treatPendingAsSignedOut } = {}) => {
139140
return payload;
140141
};
141142

143+
function useStore<T extends Store, SV extends StoreValue<T>>(store: T, getServerSnapshot?: () => SV): SV {
144+
const get = store.get.bind(store);
145+
return useSyncExternalStore<SV>(store.listen, get, getServerSnapshot || get);
146+
}
147+
142148
/**
143149
* This implementation of `useStore` is an alternative solution to the hook exported by nanostores
144150
* Reference: https://github.com/nanostores/react/blob/main/index.js
145151
*/
146-
function useStore<T extends Store, SV extends StoreValue<T>>(store: T): SV {
147-
const get = store.get.bind(store);
148-
149-
return useSyncExternalStore<SV>(store.listen, get, () => {
152+
function useAuthStore() {
153+
const get = $authStore.get.bind($authStore);
154+
return useStore($authStore, () => {
150155
// Per react docs
151156
/**
152157
* optional getServerSnapshot:
@@ -160,7 +165,17 @@ function useStore<T extends Store, SV extends StoreValue<T>>(store: T): SV {
160165
* When this runs on the server we want to grab the content from the async-local-storage.
161166
*/
162167
if (typeof window === 'undefined') {
163-
return authAsyncStorage.getStore();
168+
return deriveState(
169+
false,
170+
{
171+
user: null,
172+
session: null,
173+
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
174+
client: null!,
175+
organization: null,
176+
},
177+
authAsyncStorage.getStore() as any,
178+
);
164179
}
165180

166181
/**

0 commit comments

Comments
 (0)