Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions .changeset/invert-clerk-rq-ownership.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
---
'@clerk/shared': patch
'@clerk/clerk-js': patch
'@clerk/react': patch
---

Move ownership of the clerk-rq `QueryClient` from `@clerk/clerk-js` into `@clerk/shared`. The `QueryObserver` (constructed in `@clerk/shared`) and the `Query` objects it observes now always come from a single `@tanstack/query-core` resolution — the cross-bundle API contract that produced #8428 (`Query.isFetched is not a function`) no longer exists.

This removes the undocumented `clerk.__internal_queryClient` getter from both `@clerk/clerk-js` and `@clerk/react`'s `IsomorphicClerk`. The `QueryClient` is owned by an internal singleton in `@clerk/shared`, lazily instantiated on the browser only — server renders return `undefined`, preserving SSR safety and avoiding cross-request cache sharing.

`@tanstack/query-core` is no longer a direct dependency of `@clerk/clerk-js`; it remains a dep of `@clerk/shared` and resolves consumer-side as before.
1 change: 0 additions & 1 deletion packages/clerk-js/bundlewatch.config.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -9,7 +9,6 @@
{ "path": "./dist/coinbase*.js", "maxSize": "36KB" },
{ "path": "./dist/base-account-sdk*.js", "maxSize": "203KB" },
{ "path": "./dist/stripe-vendors*.js", "maxSize": "1KB" },
{ "path": "./dist/query-core-vendors*.js", "maxSize": "11KB" },
{ "path": "./dist/zxcvbn-ts-core*.js", "maxSize": "12KB" },
{ "path": "./dist/zxcvbn-common*.js", "maxSize": "226KB" }
]
Expand Down
1 change: 0 additions & 1 deletion packages/clerk-js/package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -91,7 +91,6 @@
"@solana/wallet-standard": "catalog:module-manager",
"@stripe/stripe-js": "5.6.0",
"@swc/helpers": "catalog:repo",
"@tanstack/query-core": "catalog:repo",
"@wallet-standard/core": "catalog:module-manager",
"@zxcvbn-ts/core": "catalog:module-manager",
"@zxcvbn-ts/language-common": "catalog:module-manager",
Expand Down
6 changes: 0 additions & 6 deletions packages/clerk-js/rspack.config.js
Original file line numberDiff line numberDiff line change
Expand Up@@ -110,12 +110,6 @@ const common = ({ mode, variant, disableRHC = false }) => {
chunks: 'all',
enforce: true,
},
queryCoreVendor: {
test: /[\\/]node_modules[\\/](@tanstack\/query-core)[\\/]/,
name: 'query-core-vendors',
chunks: 'all',
enforce: true,
},
defaultVendors: {
minChunks: 1,
test: module => {
Expand Down
24 changes: 0 additions & 24 deletions packages/clerk-js/src/core/clerk.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -138,7 +138,6 @@ import type {
import type { ClerkUI } from '@clerk/shared/ui';
import { addClerkPrefix, isAbsoluteUrl, stripScheme } from '@clerk/shared/url';
import { allSettled, handleValueOrFn, noop } from '@clerk/shared/utils';
import type { QueryClient } from '@tanstack/query-core';

import { debugLogger, initDebugLogger } from '@/utils/debug';
import { ModuleManager } from '@/utils/moduleManager';
Expand DownExpand Up@@ -248,7 +247,6 @@ export class Clerk implements ClerkInterface {
// converted to protected environment to support `updateEnvironment` type assertion
protected environment?: EnvironmentResource | null;

#queryClient: QueryClient | undefined;
#publishableKey = '';
#domain: DomainOrProxyUrl['domain'];
#proxyUrl: DomainOrProxyUrl['proxyUrl'];
Expand All@@ -268,28 +266,6 @@ export class Clerk implements ClerkInterface {
#touchThrottledUntil = 0;
#publicEventBus = createClerkEventBus();

get __internal_queryClient(): { __tag: 'clerk-rq-client'; client: QueryClient } | undefined {
if (!this.#queryClient) {
void import('./query-core')
.then(module => module.QueryClient)
.then(QueryClient => {
if (this.#queryClient) {
return;
}
this.#queryClient = new QueryClient();
// @ts-expect-error - queryClientStatus is not typed
this.#publicEventBus.emit('queryClientStatus', 'ready');
});
}

return this.#queryClient
? {
__tag: 'clerk-rq-client',
client: this.#queryClient,
}
: undefined;
}

public __internal_getCachedResources:
| (() => Promise<{ client: ClientJSONSnapshot | null; environment: EnvironmentJSONSnapshot | null }>)
| undefined;
Expand Down
3 changes: 0 additions & 3 deletions packages/clerk-js/src/core/query-core.ts

This file was deleted.

22 changes: 2 additions & 20 deletions packages/clerk-js/src/test/mock-helpers.ts
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
import { __createClerkTestQueryClient } from '@clerk/shared/react';
import type { ActiveSessionResource, LoadedClerk } from '@clerk/shared/types';
import { type Mocked, vi } from 'vitest';

import { QueryClient } from '../core/query-core';
import type { RouteContextValue } from '../ui/router';

type FunctionLike = (...args: any) => any;
Expand DownExpand Up@@ -46,19 +46,7 @@ export const mockClerkMethods = (clerk: LoadedClerk): DeepVitestMocked<LoadedCle
// Cast clerk to any to allow mocking properties
const clerkAny = clerk as any;

const defaultQueryClient = {
__tag: 'clerk-rq-client' as const,
client: new QueryClient({
defaultOptions: {
queries: {
retry: false,
// Setting staleTime to Infinity will not cause issues between tests as long as each test
// case has its own wrapper that initializes a Clerk instance with a new QueryClient.
staleTime: Infinity,
},
},
}),
};
__createClerkTestQueryClient();

mockMethodsOf(clerkAny);
if (clerkAny.client) {
Expand DownExpand Up@@ -92,12 +80,6 @@ export const mockClerkMethods = (clerk: LoadedClerk): DeepVitestMocked<LoadedCle
mockMethodsOf(clerkAny.billing);
}

// Mock the __internal_queryClient getter property
Object.defineProperty(clerkAny, '__internal_queryClient', {
get: vi.fn(() => defaultQueryClient),
configurable: true,
});

mockProp(clerkAny, 'navigate');
mockProp(clerkAny, 'setActive');
mockProp(clerkAny, 'redirectWithAuth');
Expand Down
12 changes: 0 additions & 12 deletions packages/react/src/isomorphicClerk.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -344,11 +344,6 @@ export class IsomorphicClerk implements IsomorphicLoadedClerk {
return this.clerkjs?.isStandardBrowser || this.options.standardBrowser || false;
}

get __internal_queryClient() {
// @ts-expect-error - __internal_queryClient is not typed
return this.clerkjs?.__internal_queryClient;
}

get isSatellite() {
// This getter can run in environments where window is not available.
// In those cases we should expect and use domain as a string
Expand DownExpand Up@@ -656,13 +651,6 @@ export class IsomorphicClerk implements IsomorphicLoadedClerk {
this.on('status', listener, { notify: true });
});

// @ts-expect-error - queryClientStatus is not typed
this.#eventBus.internal.retrieveListeners('queryClientStatus')?.forEach(listener => {
// Since clerkjs exists it will call `this.clerkjs.on('queryClientStatus', listener)`
// @ts-expect-error - queryClientStatus is not typed
this.on('queryClientStatus', listener, { notify: true });
});

if (this.preopenSignIn !== null) {
clerkjs.openSignIn(this.preopenSignIn);
}
Expand Down
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
import { QueryClient } from '@tanstack/query-core';
import { afterEach, describe, expect, it, vi } from 'vitest';

import {
__createClerkTestQueryClient,
__resetClerkQueryClientForTest,
__setClerkQueryClientForTest,
getClerkQueryClient,
} from '../clerk-query-client';

afterEach(() => {
vi.unstubAllGlobals();
__resetClerkQueryClientForTest();
});

describe('getClerkQueryClient', () => {
it('returns undefined when window is not defined (SSR)', () => {
vi.stubGlobal('window', undefined);

expect(getClerkQueryClient()).toBeUndefined();
});

it('does not cache the SSR undefined — a later browser call still creates a client', () => {
vi.stubGlobal('window', undefined);
expect(getClerkQueryClient()).toBeUndefined();

vi.unstubAllGlobals();
const client = getClerkQueryClient();
expect(client).toBeInstanceOf(QueryClient);
});

it('lazy-creates a singleton on the browser and returns the same instance on repeated calls', () => {
const first = getClerkQueryClient();
const second = getClerkQueryClient();

expect(first).toBeInstanceOf(QueryClient);
expect(second).toBe(first);
});
});

describe('__resetClerkQueryClientForTest', () => {
it('clears the singleton so the next read lazy-creates a fresh client', () => {
const original = getClerkQueryClient();
expect(original).toBeInstanceOf(QueryClient);

__resetClerkQueryClientForTest();

const next = getClerkQueryClient();
expect(next).toBeInstanceOf(QueryClient);
expect(next).not.toBe(original);
});
});

describe('__setClerkQueryClientForTest', () => {
it('installs a caller-supplied client and returns it from getClerkQueryClient', () => {
const custom = new QueryClient();
__setClerkQueryClientForTest(custom);

expect(getClerkQueryClient()).toBe(custom);
});

it('installs the "no client" state without triggering lazy creation on subsequent reads', () => {
__setClerkQueryClientForTest(undefined);

expect(getClerkQueryClient()).toBeUndefined();
expect(getClerkQueryClient()).toBeUndefined();
});
});

describe('__createClerkTestQueryClient', () => {
it('returns a QueryClient with deterministic defaults and installs it as the singleton', () => {
const client = __createClerkTestQueryClient();

expect(client).toBeInstanceOf(QueryClient);
expect(getClerkQueryClient()).toBe(client);

const defaults = client.getDefaultOptions().queries;
expect(defaults?.retry).toBe(false);
expect(defaults?.staleTime).toBe(Infinity);
expect(defaults?.refetchOnWindowFocus).toBe(false);
expect(defaults?.refetchOnReconnect).toBe(false);
expect(defaults?.refetchOnMount).toBe(false);
});
});
Original file line numberDiff line numberDiff line change
Expand Up@@ -3,6 +3,7 @@ import React from 'react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';

import { createMockClerk, createMockQueryClient } from '../../hooks/__tests__/mocks/clerk';
import { __resetClerkQueryClientForTest, __setClerkQueryClientForTest } from '../clerk-query-client';
import { useClerkInfiniteQuery } from '../useInfiniteQuery';
import { useClerkQuery } from '../useQuery';

Expand All@@ -16,22 +17,15 @@ vi.mock('../../contexts', () => ({

const wrapper = ({ children }: { children: React.ReactNode }) => <>{children}</>;

const makeClerkWithoutQueryClient = () => {
const mockClerk = createMockClerk({ queryClient: null });
Object.defineProperty(mockClerk, '__internal_queryClient', {
get: () => undefined,
configurable: true,
});
return mockClerk;
};

afterEach(() => {
vi.clearAllMocks();
__resetClerkQueryClientForTest();
});

describe('useBaseQuery - dummy result while query client is not attached', () => {
beforeEach(() => {
activeClerk = makeClerkWithoutQueryClient();
activeClerk = createMockClerk({ queryClient: null });
__setClerkQueryClientForTest(undefined);
});

it('reports isLoading: true when the query would be enabled', () => {
Expand DownExpand Up@@ -109,8 +103,8 @@ describe('useBaseQuery - dummy result while query client is not attached', () =>

describe('useBaseQuery - normal behavior once query client attaches', () => {
it('delegates to the real observer when the query client is loaded', async () => {
const queryClient = createMockQueryClient();
activeClerk = createMockClerk({ queryClient });
createMockQueryClient();
activeClerk = createMockClerk({ queryClient: undefined });

const queryFn = vi.fn(async () => 'result');
const { result } = renderHook(
Expand Down
66 changes: 66 additions & 0 deletions packages/shared/src/react/clerk-rq/clerk-query-client.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
import { QueryClient } from '@tanstack/query-core';

/**
* The QueryClient backing every clerk-rq hook. Owned by `@clerk/shared` so the
* `QueryObserver` that observes it and the `Query` objects inside it always
* resolve to the same `@tanstack/query-core` (no cross-bundle drift between
* the consumer-side `@clerk/shared` and the production CDN `clerk-js` bundle).
*
* Lazily instantiated on the client only. Server-side renders return
* `undefined` so per-request renders never share a cache across requests.
*/
let clerkQueryClient: QueryClient | undefined;
let initialized = false;

export function getClerkQueryClient(): QueryClient | undefined {
if (typeof window === 'undefined') {
return undefined;
}
if (!initialized) {
clerkQueryClient = new QueryClient();
initialized = true;
}
return clerkQueryClient;
}

/**
* Test-only: install a custom client (for deterministic defaults like
* `staleTime: Infinity`) or pass `undefined` to simulate the "no client"
* state without triggering lazy creation on subsequent reads.
*/
export function __setClerkQueryClientForTest(client: QueryClient | undefined): void {
clerkQueryClient = client;
initialized = true;
}

/**
* Test-only: build and install a fresh `QueryClient` with deterministic
* defaults (no retries, infinite stale time, no refetching). Returns the
* client so the spec can read/write its cache directly.
*
* Avoids forcing every test consumer to depend on `@tanstack/query-core`.
*/
export function __createClerkTestQueryClient(): QueryClient {
const client = new QueryClient({
defaultOptions: {
queries: {
retry: false,
staleTime: Infinity,
refetchOnWindowFocus: false,
refetchOnReconnect: false,
refetchOnMount: false,
},
},
});
__setClerkQueryClientForTest(client);
return client;
}

/**
* Test-only: clear both the override and the initialization flag so the
* next read lazy-creates a fresh client.
*/
export function __resetClerkQueryClientForTest(): void {
clerkQueryClient = undefined;
initialized = false;
}
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Add copy buttons to all
 blocks
(function() {
function addCopyButtons() {
document.querySelectorAll('pre code').forEach(function(codeBlock) {
if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;
codeBlock.parentElement.setAttribute('data-copy-added', 'true');
var btn = document.createElement('button');
btn.textContent = 'Copy';
btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';
btn.onmouseover = function() { this.style.opacity = '1'; };
btn.onmouseout = function() { this.style.opacity = '0.7'; };
btn.onclick = function() {
navigator.clipboard.writeText(codeBlock.textContent).then(function() {
btn.textContent = 'Copied!';
setTimeout(function() { btn.textContent = 'Copy'; }, 1500);
});
};
codeBlock.parentElement.style.position = 'relative';
codeBlock.parentElement.appendChild(btn);
});
}
addCopyButtons();
// Re-run on dynamic content
var observer = new MutationObserver(addCopyButtons);
observer.observe(document.body, { childList: true, subtree: true });
})();
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
refactor(shared,clerk-js,react): move QueryClient ownership into @clerk/shared by jacekradko · Pull Request #8434 · clerk/javascript · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions .changeset/invert-clerk-rq-ownership.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
---
'@clerk/shared': patch
'@clerk/clerk-js': patch
'@clerk/react': patch
---

Move ownership of the clerk-rq `QueryClient` from `@clerk/clerk-js` into `@clerk/shared`. The `QueryObserver` (constructed in `@clerk/shared`) and the `Query` objects it observes now always come from a single `@tanstack/query-core` resolution — the cross-bundle API contract that produced #8428 (`Query.isFetched is not a function`) no longer exists.

This removes the undocumented `clerk.__internal_queryClient` getter from both `@clerk/clerk-js` and `@clerk/react`'s `IsomorphicClerk`. The `QueryClient` is owned by an internal singleton in `@clerk/shared`, lazily instantiated on the browser only — server renders return `undefined`, preserving SSR safety and avoiding cross-request cache sharing.

`@tanstack/query-core` is no longer a direct dependency of `@clerk/clerk-js`; it remains a dep of `@clerk/shared` and resolves consumer-side as before.
1 change: 0 additions & 1 deletion packages/clerk-js/bundlewatch.config.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -9,7 +9,6 @@
{ "path": "./dist/coinbase*.js", "maxSize": "36KB" },
{ "path": "./dist/base-account-sdk*.js", "maxSize": "203KB" },
{ "path": "./dist/stripe-vendors*.js", "maxSize": "1KB" },
{ "path": "./dist/query-core-vendors*.js", "maxSize": "11KB" },
{ "path": "./dist/zxcvbn-ts-core*.js", "maxSize": "12KB" },
{ "path": "./dist/zxcvbn-common*.js", "maxSize": "226KB" }
]
Expand Down
1 change: 0 additions & 1 deletion packages/clerk-js/package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -91,7 +91,6 @@
"@solana/wallet-standard": "catalog:module-manager",
"@stripe/stripe-js": "5.6.0",
"@swc/helpers": "catalog:repo",
"@tanstack/query-core": "catalog:repo",
"@wallet-standard/core": "catalog:module-manager",
"@zxcvbn-ts/core": "catalog:module-manager",
"@zxcvbn-ts/language-common": "catalog:module-manager",
Expand Down
6 changes: 0 additions & 6 deletions packages/clerk-js/rspack.config.js
Original file line numberDiff line numberDiff line change
Expand Up@@ -110,12 +110,6 @@ const common = ({ mode, variant, disableRHC = false }) => {
chunks: 'all',
enforce: true,
},
queryCoreVendor: {
test: /[\\/]node_modules[\\/](@tanstack\/query-core)[\\/]/,
name: 'query-core-vendors',
chunks: 'all',
enforce: true,
},
defaultVendors: {
minChunks: 1,
test: module => {
Expand Down
24 changes: 0 additions & 24 deletions packages/clerk-js/src/core/clerk.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -138,7 +138,6 @@ import type {
import type { ClerkUI } from '@clerk/shared/ui';
import { addClerkPrefix, isAbsoluteUrl, stripScheme } from '@clerk/shared/url';
import { allSettled, handleValueOrFn, noop } from '@clerk/shared/utils';
import type { QueryClient } from '@tanstack/query-core';

import { debugLogger, initDebugLogger } from '@/utils/debug';
import { ModuleManager } from '@/utils/moduleManager';
Expand DownExpand Up@@ -248,7 +247,6 @@ export class Clerk implements ClerkInterface {
// converted to protected environment to support `updateEnvironment` type assertion
protected environment?: EnvironmentResource | null;

#queryClient: QueryClient | undefined;
#publishableKey = '';
#domain: DomainOrProxyUrl['domain'];
#proxyUrl: DomainOrProxyUrl['proxyUrl'];
Expand All@@ -268,28 +266,6 @@ export class Clerk implements ClerkInterface {
#touchThrottledUntil = 0;
#publicEventBus = createClerkEventBus();

get __internal_queryClient(): { __tag: 'clerk-rq-client'; client: QueryClient } | undefined {
if (!this.#queryClient) {
void import('./query-core')
.then(module => module.QueryClient)
.then(QueryClient => {
if (this.#queryClient) {
return;
}
this.#queryClient = new QueryClient();
// @ts-expect-error - queryClientStatus is not typed
this.#publicEventBus.emit('queryClientStatus', 'ready');
});
}

return this.#queryClient
? {
__tag: 'clerk-rq-client',
client: this.#queryClient,
}
: undefined;
}

public __internal_getCachedResources:
| (() => Promise<{ client: ClientJSONSnapshot | null; environment: EnvironmentJSONSnapshot | null }>)
| undefined;
Expand Down
3 changes: 0 additions & 3 deletions packages/clerk-js/src/core/query-core.ts

This file was deleted.

22 changes: 2 additions & 20 deletions packages/clerk-js/src/test/mock-helpers.ts
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
import { __createClerkTestQueryClient } from '@clerk/shared/react';
import type { ActiveSessionResource, LoadedClerk } from '@clerk/shared/types';
import { type Mocked, vi } from 'vitest';

import { QueryClient } from '../core/query-core';
import type { RouteContextValue } from '../ui/router';

type FunctionLike = (...args: any) => any;
Expand DownExpand Up@@ -46,19 +46,7 @@ export const mockClerkMethods = (clerk: LoadedClerk): DeepVitestMocked<LoadedCle
// Cast clerk to any to allow mocking properties
const clerkAny = clerk as any;

const defaultQueryClient = {
__tag: 'clerk-rq-client' as const,
client: new QueryClient({
defaultOptions: {
queries: {
retry: false,
// Setting staleTime to Infinity will not cause issues between tests as long as each test
// case has its own wrapper that initializes a Clerk instance with a new QueryClient.
staleTime: Infinity,
},
},
}),
};
__createClerkTestQueryClient();

mockMethodsOf(clerkAny);
if (clerkAny.client) {
Expand DownExpand Up@@ -92,12 +80,6 @@ export const mockClerkMethods = (clerk: LoadedClerk): DeepVitestMocked<LoadedCle
mockMethodsOf(clerkAny.billing);
}

// Mock the __internal_queryClient getter property
Object.defineProperty(clerkAny, '__internal_queryClient', {
get: vi.fn(() => defaultQueryClient),
configurable: true,
});

mockProp(clerkAny, 'navigate');
mockProp(clerkAny, 'setActive');
mockProp(clerkAny, 'redirectWithAuth');
Expand Down
12 changes: 0 additions & 12 deletions packages/react/src/isomorphicClerk.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -344,11 +344,6 @@ export class IsomorphicClerk implements IsomorphicLoadedClerk {
return this.clerkjs?.isStandardBrowser || this.options.standardBrowser || false;
}

get __internal_queryClient() {
// @ts-expect-error - __internal_queryClient is not typed
return this.clerkjs?.__internal_queryClient;
}

get isSatellite() {
// This getter can run in environments where window is not available.
// In those cases we should expect and use domain as a string
Expand DownExpand Up@@ -656,13 +651,6 @@ export class IsomorphicClerk implements IsomorphicLoadedClerk {
this.on('status', listener, { notify: true });
});

// @ts-expect-error - queryClientStatus is not typed
this.#eventBus.internal.retrieveListeners('queryClientStatus')?.forEach(listener => {
// Since clerkjs exists it will call `this.clerkjs.on('queryClientStatus', listener)`
// @ts-expect-error - queryClientStatus is not typed
this.on('queryClientStatus', listener, { notify: true });
});

if (this.preopenSignIn !== null) {
clerkjs.openSignIn(this.preopenSignIn);
}
Expand Down
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
import { QueryClient } from '@tanstack/query-core';
import { afterEach, describe, expect, it, vi } from 'vitest';

import {
__createClerkTestQueryClient,
__resetClerkQueryClientForTest,
__setClerkQueryClientForTest,
getClerkQueryClient,
} from '../clerk-query-client';

afterEach(() => {
vi.unstubAllGlobals();
__resetClerkQueryClientForTest();
});

describe('getClerkQueryClient', () => {
it('returns undefined when window is not defined (SSR)', () => {
vi.stubGlobal('window', undefined);

expect(getClerkQueryClient()).toBeUndefined();
});

it('does not cache the SSR undefined — a later browser call still creates a client', () => {
vi.stubGlobal('window', undefined);
expect(getClerkQueryClient()).toBeUndefined();

vi.unstubAllGlobals();
const client = getClerkQueryClient();
expect(client).toBeInstanceOf(QueryClient);
});

it('lazy-creates a singleton on the browser and returns the same instance on repeated calls', () => {
const first = getClerkQueryClient();
const second = getClerkQueryClient();

expect(first).toBeInstanceOf(QueryClient);
expect(second).toBe(first);
});
});

describe('__resetClerkQueryClientForTest', () => {
it('clears the singleton so the next read lazy-creates a fresh client', () => {
const original = getClerkQueryClient();
expect(original).toBeInstanceOf(QueryClient);

__resetClerkQueryClientForTest();

const next = getClerkQueryClient();
expect(next).toBeInstanceOf(QueryClient);
expect(next).not.toBe(original);
});
});

describe('__setClerkQueryClientForTest', () => {
it('installs a caller-supplied client and returns it from getClerkQueryClient', () => {
const custom = new QueryClient();
__setClerkQueryClientForTest(custom);

expect(getClerkQueryClient()).toBe(custom);
});

it('installs the "no client" state without triggering lazy creation on subsequent reads', () => {
__setClerkQueryClientForTest(undefined);

expect(getClerkQueryClient()).toBeUndefined();
expect(getClerkQueryClient()).toBeUndefined();
});
});

describe('__createClerkTestQueryClient', () => {
it('returns a QueryClient with deterministic defaults and installs it as the singleton', () => {
const client = __createClerkTestQueryClient();

expect(client).toBeInstanceOf(QueryClient);
expect(getClerkQueryClient()).toBe(client);

const defaults = client.getDefaultOptions().queries;
expect(defaults?.retry).toBe(false);
expect(defaults?.staleTime).toBe(Infinity);
expect(defaults?.refetchOnWindowFocus).toBe(false);
expect(defaults?.refetchOnReconnect).toBe(false);
expect(defaults?.refetchOnMount).toBe(false);
});
});
Original file line numberDiff line numberDiff line change
Expand Up@@ -3,6 +3,7 @@ import React from 'react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';

import { createMockClerk, createMockQueryClient } from '../../hooks/__tests__/mocks/clerk';
import { __resetClerkQueryClientForTest, __setClerkQueryClientForTest } from '../clerk-query-client';
import { useClerkInfiniteQuery } from '../useInfiniteQuery';
import { useClerkQuery } from '../useQuery';

Expand All@@ -16,22 +17,15 @@ vi.mock('../../contexts', () => ({

const wrapper = ({ children }: { children: React.ReactNode }) => <>{children}</>;

const makeClerkWithoutQueryClient = () => {
const mockClerk = createMockClerk({ queryClient: null });
Object.defineProperty(mockClerk, '__internal_queryClient', {
get: () => undefined,
configurable: true,
});
return mockClerk;
};

afterEach(() => {
vi.clearAllMocks();
__resetClerkQueryClientForTest();
});

describe('useBaseQuery - dummy result while query client is not attached', () => {
beforeEach(() => {
activeClerk = makeClerkWithoutQueryClient();
activeClerk = createMockClerk({ queryClient: null });
__setClerkQueryClientForTest(undefined);
});

it('reports isLoading: true when the query would be enabled', () => {
Expand DownExpand Up@@ -109,8 +103,8 @@ describe('useBaseQuery - dummy result while query client is not attached', () =>

describe('useBaseQuery - normal behavior once query client attaches', () => {
it('delegates to the real observer when the query client is loaded', async () => {
const queryClient = createMockQueryClient();
activeClerk = createMockClerk({ queryClient });
createMockQueryClient();
activeClerk = createMockClerk({ queryClient: undefined });

const queryFn = vi.fn(async () => 'result');
const { result } = renderHook(
Expand Down
66 changes: 66 additions & 0 deletions packages/shared/src/react/clerk-rq/clerk-query-client.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
import { QueryClient } from '@tanstack/query-core';

/**
* The QueryClient backing every clerk-rq hook. Owned by `@clerk/shared` so the
* `QueryObserver` that observes it and the `Query` objects inside it always
* resolve to the same `@tanstack/query-core` (no cross-bundle drift between
* the consumer-side `@clerk/shared` and the production CDN `clerk-js` bundle).
*
* Lazily instantiated on the client only. Server-side renders return
* `undefined` so per-request renders never share a cache across requests.
*/
let clerkQueryClient: QueryClient | undefined;
let initialized = false;

export function getClerkQueryClient(): QueryClient | undefined {
if (typeof window === 'undefined') {
return undefined;
}
if (!initialized) {
clerkQueryClient = new QueryClient();
initialized = true;
}
return clerkQueryClient;
}

/**
* Test-only: install a custom client (for deterministic defaults like
* `staleTime: Infinity`) or pass `undefined` to simulate the "no client"
* state without triggering lazy creation on subsequent reads.
*/
export function __setClerkQueryClientForTest(client: QueryClient | undefined): void {
clerkQueryClient = client;
initialized = true;
}

/**
* Test-only: build and install a fresh `QueryClient` with deterministic
* defaults (no retries, infinite stale time, no refetching). Returns the
* client so the spec can read/write its cache directly.
*
* Avoids forcing every test consumer to depend on `@tanstack/query-core`.
*/
export function __createClerkTestQueryClient(): QueryClient {
const client = new QueryClient({
defaultOptions: {
queries: {
retry: false,
staleTime: Infinity,
refetchOnWindowFocus: false,
refetchOnReconnect: false,
refetchOnMount: false,
},
},
});
__setClerkQueryClientForTest(client);
return client;
}

/**
* Test-only: clear both the override and the initialization flag so the
* next read lazy-creates a fresh client.
*/
export function __resetClerkQueryClientForTest(): void {
clerkQueryClient = undefined;
initialized = false;
}
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Force GitHub README to respect dark mode (function() { var style = document.createElement('style'); style.textContent = ' .markdown-body { color-scheme: dark light; } .markdown-body pre { background: #161b22 !important; } .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; } .markdown-body table th, .markdown-body table td { border-color: #30363d !important; } .markdown-body img { background: #0d1117; } .markdown-body blockquote { border-left-color: #8b949e; } .markdown-body hr { border-color: #30363d; } '; document.head.appendChild(style); })(); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' refactor(shared,clerk-js,react): move QueryClient ownership into @clerk/shared by jacekradko · Pull Request #8434 · clerk/javascript · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions .changeset/invert-clerk-rq-ownership.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
---
'@clerk/shared': patch
'@clerk/clerk-js': patch
'@clerk/react': patch
---

Move ownership of the clerk-rq `QueryClient` from `@clerk/clerk-js` into `@clerk/shared`. The `QueryObserver` (constructed in `@clerk/shared`) and the `Query` objects it observes now always come from a single `@tanstack/query-core` resolution — the cross-bundle API contract that produced #8428 (`Query.isFetched is not a function`) no longer exists.

This removes the undocumented `clerk.__internal_queryClient` getter from both `@clerk/clerk-js` and `@clerk/react`'s `IsomorphicClerk`. The `QueryClient` is owned by an internal singleton in `@clerk/shared`, lazily instantiated on the browser only — server renders return `undefined`, preserving SSR safety and avoiding cross-request cache sharing.

`@tanstack/query-core` is no longer a direct dependency of `@clerk/clerk-js`; it remains a dep of `@clerk/shared` and resolves consumer-side as before.
1 change: 0 additions & 1 deletion packages/clerk-js/bundlewatch.config.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -9,7 +9,6 @@
{ "path": "./dist/coinbase*.js", "maxSize": "36KB" },
{ "path": "./dist/base-account-sdk*.js", "maxSize": "203KB" },
{ "path": "./dist/stripe-vendors*.js", "maxSize": "1KB" },
{ "path": "./dist/query-core-vendors*.js", "maxSize": "11KB" },
{ "path": "./dist/zxcvbn-ts-core*.js", "maxSize": "12KB" },
{ "path": "./dist/zxcvbn-common*.js", "maxSize": "226KB" }
]
Expand Down
1 change: 0 additions & 1 deletion packages/clerk-js/package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -91,7 +91,6 @@
"@solana/wallet-standard": "catalog:module-manager",
"@stripe/stripe-js": "5.6.0",
"@swc/helpers": "catalog:repo",
"@tanstack/query-core": "catalog:repo",
"@wallet-standard/core": "catalog:module-manager",
"@zxcvbn-ts/core": "catalog:module-manager",
"@zxcvbn-ts/language-common": "catalog:module-manager",
Expand Down
6 changes: 0 additions & 6 deletions packages/clerk-js/rspack.config.js
Original file line numberDiff line numberDiff line change
Expand Up@@ -110,12 +110,6 @@ const common = ({ mode, variant, disableRHC = false }) => {
chunks: 'all',
enforce: true,
},
queryCoreVendor: {
test: /[\\/]node_modules[\\/](@tanstack\/query-core)[\\/]/,
name: 'query-core-vendors',
chunks: 'all',
enforce: true,
},
defaultVendors: {
minChunks: 1,
test: module => {
Expand Down
24 changes: 0 additions & 24 deletions packages/clerk-js/src/core/clerk.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -138,7 +138,6 @@ import type {
import type { ClerkUI } from '@clerk/shared/ui';
import { addClerkPrefix, isAbsoluteUrl, stripScheme } from '@clerk/shared/url';
import { allSettled, handleValueOrFn, noop } from '@clerk/shared/utils';
import type { QueryClient } from '@tanstack/query-core';

import { debugLogger, initDebugLogger } from '@/utils/debug';
import { ModuleManager } from '@/utils/moduleManager';
Expand DownExpand Up@@ -248,7 +247,6 @@ export class Clerk implements ClerkInterface {
// converted to protected environment to support `updateEnvironment` type assertion
protected environment?: EnvironmentResource | null;

#queryClient: QueryClient | undefined;
#publishableKey = '';
#domain: DomainOrProxyUrl['domain'];
#proxyUrl: DomainOrProxyUrl['proxyUrl'];
Expand All@@ -268,28 +266,6 @@ export class Clerk implements ClerkInterface {
#touchThrottledUntil = 0;
#publicEventBus = createClerkEventBus();

get __internal_queryClient(): { __tag: 'clerk-rq-client'; client: QueryClient } | undefined {
if (!this.#queryClient) {
void import('./query-core')
.then(module => module.QueryClient)
.then(QueryClient => {
if (this.#queryClient) {
return;
}
this.#queryClient = new QueryClient();
// @ts-expect-error - queryClientStatus is not typed
this.#publicEventBus.emit('queryClientStatus', 'ready');
});
}

return this.#queryClient
? {
__tag: 'clerk-rq-client',
client: this.#queryClient,
}
: undefined;
}

public __internal_getCachedResources:
| (() => Promise<{ client: ClientJSONSnapshot | null; environment: EnvironmentJSONSnapshot | null }>)
| undefined;
Expand Down
3 changes: 0 additions & 3 deletions packages/clerk-js/src/core/query-core.ts

This file was deleted.

22 changes: 2 additions & 20 deletions packages/clerk-js/src/test/mock-helpers.ts
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
import { __createClerkTestQueryClient } from '@clerk/shared/react';
import type { ActiveSessionResource, LoadedClerk } from '@clerk/shared/types';
import { type Mocked, vi } from 'vitest';

import { QueryClient } from '../core/query-core';
import type { RouteContextValue } from '../ui/router';

type FunctionLike = (...args: any) => any;
Expand DownExpand Up@@ -46,19 +46,7 @@ export const mockClerkMethods = (clerk: LoadedClerk): DeepVitestMocked<LoadedCle
// Cast clerk to any to allow mocking properties
const clerkAny = clerk as any;

const defaultQueryClient = {
__tag: 'clerk-rq-client' as const,
client: new QueryClient({
defaultOptions: {
queries: {
retry: false,
// Setting staleTime to Infinity will not cause issues between tests as long as each test
// case has its own wrapper that initializes a Clerk instance with a new QueryClient.
staleTime: Infinity,
},
},
}),
};
__createClerkTestQueryClient();

mockMethodsOf(clerkAny);
if (clerkAny.client) {
Expand DownExpand Up@@ -92,12 +80,6 @@ export const mockClerkMethods = (clerk: LoadedClerk): DeepVitestMocked<LoadedCle
mockMethodsOf(clerkAny.billing);
}

// Mock the __internal_queryClient getter property
Object.defineProperty(clerkAny, '__internal_queryClient', {
get: vi.fn(() => defaultQueryClient),
configurable: true,
});

mockProp(clerkAny, 'navigate');
mockProp(clerkAny, 'setActive');
mockProp(clerkAny, 'redirectWithAuth');
Expand Down
12 changes: 0 additions & 12 deletions packages/react/src/isomorphicClerk.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -344,11 +344,6 @@ export class IsomorphicClerk implements IsomorphicLoadedClerk {
return this.clerkjs?.isStandardBrowser || this.options.standardBrowser || false;
}

get __internal_queryClient() {
// @ts-expect-error - __internal_queryClient is not typed
return this.clerkjs?.__internal_queryClient;
}

get isSatellite() {
// This getter can run in environments where window is not available.
// In those cases we should expect and use domain as a string
Expand DownExpand Up@@ -656,13 +651,6 @@ export class IsomorphicClerk implements IsomorphicLoadedClerk {
this.on('status', listener, { notify: true });
});

// @ts-expect-error - queryClientStatus is not typed
this.#eventBus.internal.retrieveListeners('queryClientStatus')?.forEach(listener => {
// Since clerkjs exists it will call `this.clerkjs.on('queryClientStatus', listener)`
// @ts-expect-error - queryClientStatus is not typed
this.on('queryClientStatus', listener, { notify: true });
});

if (this.preopenSignIn !== null) {
clerkjs.openSignIn(this.preopenSignIn);
}
Expand Down
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
import { QueryClient } from '@tanstack/query-core';
import { afterEach, describe, expect, it, vi } from 'vitest';

import {
__createClerkTestQueryClient,
__resetClerkQueryClientForTest,
__setClerkQueryClientForTest,
getClerkQueryClient,
} from '../clerk-query-client';

afterEach(() => {
vi.unstubAllGlobals();
__resetClerkQueryClientForTest();
});

describe('getClerkQueryClient', () => {
it('returns undefined when window is not defined (SSR)', () => {
vi.stubGlobal('window', undefined);

expect(getClerkQueryClient()).toBeUndefined();
});

it('does not cache the SSR undefined — a later browser call still creates a client', () => {
vi.stubGlobal('window', undefined);
expect(getClerkQueryClient()).toBeUndefined();

vi.unstubAllGlobals();
const client = getClerkQueryClient();
expect(client).toBeInstanceOf(QueryClient);
});

it('lazy-creates a singleton on the browser and returns the same instance on repeated calls', () => {
const first = getClerkQueryClient();
const second = getClerkQueryClient();

expect(first).toBeInstanceOf(QueryClient);
expect(second).toBe(first);
});
});

describe('__resetClerkQueryClientForTest', () => {
it('clears the singleton so the next read lazy-creates a fresh client', () => {
const original = getClerkQueryClient();
expect(original).toBeInstanceOf(QueryClient);

__resetClerkQueryClientForTest();

const next = getClerkQueryClient();
expect(next).toBeInstanceOf(QueryClient);
expect(next).not.toBe(original);
});
});

describe('__setClerkQueryClientForTest', () => {
it('installs a caller-supplied client and returns it from getClerkQueryClient', () => {
const custom = new QueryClient();
__setClerkQueryClientForTest(custom);

expect(getClerkQueryClient()).toBe(custom);
});

it('installs the "no client" state without triggering lazy creation on subsequent reads', () => {
__setClerkQueryClientForTest(undefined);

expect(getClerkQueryClient()).toBeUndefined();
expect(getClerkQueryClient()).toBeUndefined();
});
});

describe('__createClerkTestQueryClient', () => {
it('returns a QueryClient with deterministic defaults and installs it as the singleton', () => {
const client = __createClerkTestQueryClient();

expect(client).toBeInstanceOf(QueryClient);
expect(getClerkQueryClient()).toBe(client);

const defaults = client.getDefaultOptions().queries;
expect(defaults?.retry).toBe(false);
expect(defaults?.staleTime).toBe(Infinity);
expect(defaults?.refetchOnWindowFocus).toBe(false);
expect(defaults?.refetchOnReconnect).toBe(false);
expect(defaults?.refetchOnMount).toBe(false);
});
});
Original file line numberDiff line numberDiff line change
Expand Up@@ -3,6 +3,7 @@ import React from 'react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';

import { createMockClerk, createMockQueryClient } from '../../hooks/__tests__/mocks/clerk';
import { __resetClerkQueryClientForTest, __setClerkQueryClientForTest } from '../clerk-query-client';
import { useClerkInfiniteQuery } from '../useInfiniteQuery';
import { useClerkQuery } from '../useQuery';

Expand All@@ -16,22 +17,15 @@ vi.mock('../../contexts', () => ({

const wrapper = ({ children }: { children: React.ReactNode }) => <>{children}</>;

const makeClerkWithoutQueryClient = () => {
const mockClerk = createMockClerk({ queryClient: null });
Object.defineProperty(mockClerk, '__internal_queryClient', {
get: () => undefined,
configurable: true,
});
return mockClerk;
};

afterEach(() => {
vi.clearAllMocks();
__resetClerkQueryClientForTest();
});

describe('useBaseQuery - dummy result while query client is not attached', () => {
beforeEach(() => {
activeClerk = makeClerkWithoutQueryClient();
activeClerk = createMockClerk({ queryClient: null });
__setClerkQueryClientForTest(undefined);
});

it('reports isLoading: true when the query would be enabled', () => {
Expand DownExpand Up@@ -109,8 +103,8 @@ describe('useBaseQuery - dummy result while query client is not attached', () =>

describe('useBaseQuery - normal behavior once query client attaches', () => {
it('delegates to the real observer when the query client is loaded', async () => {
const queryClient = createMockQueryClient();
activeClerk = createMockClerk({ queryClient });
createMockQueryClient();
activeClerk = createMockClerk({ queryClient: undefined });

const queryFn = vi.fn(async () => 'result');
const { result } = renderHook(
Expand Down
66 changes: 66 additions & 0 deletions packages/shared/src/react/clerk-rq/clerk-query-client.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
import { QueryClient } from '@tanstack/query-core';

/**
* The QueryClient backing every clerk-rq hook. Owned by `@clerk/shared` so the
* `QueryObserver` that observes it and the `Query` objects inside it always
* resolve to the same `@tanstack/query-core` (no cross-bundle drift between
* the consumer-side `@clerk/shared` and the production CDN `clerk-js` bundle).
*
* Lazily instantiated on the client only. Server-side renders return
* `undefined` so per-request renders never share a cache across requests.
*/
let clerkQueryClient: QueryClient | undefined;
let initialized = false;

export function getClerkQueryClient(): QueryClient | undefined {
if (typeof window === 'undefined') {
return undefined;
}
if (!initialized) {
clerkQueryClient = new QueryClient();
initialized = true;
}
return clerkQueryClient;
}

/**
* Test-only: install a custom client (for deterministic defaults like
* `staleTime: Infinity`) or pass `undefined` to simulate the "no client"
* state without triggering lazy creation on subsequent reads.
*/
export function __setClerkQueryClientForTest(client: QueryClient | undefined): void {
clerkQueryClient = client;
initialized = true;
}

/**
* Test-only: build and install a fresh `QueryClient` with deterministic
* defaults (no retries, infinite stale time, no refetching). Returns the
* client so the spec can read/write its cache directly.
*
* Avoids forcing every test consumer to depend on `@tanstack/query-core`.
*/
export function __createClerkTestQueryClient(): QueryClient {
const client = new QueryClient({
defaultOptions: {
queries: {
retry: false,
staleTime: Infinity,
refetchOnWindowFocus: false,
refetchOnReconnect: false,
refetchOnMount: false,
},
},
});
__setClerkQueryClientForTest(client);
return client;
}

/**
* Test-only: clear both the override and the initialization flag so the
* next read lazy-creates a fresh client.
*/
export function __resetClerkQueryClientForTest(): void {
clerkQueryClient = undefined;
initialized = false;
}
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Highlight search terms from Google/DuckDuckGo/Bing referrer (function() { var ref = document.referrer; var terms = []; if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) { var url = new URL(ref); var q = url.searchParams.get('q') || url.searchParams.get('p'); if (q) { terms = q.split(/\s+/).filter(function(t) { return t.length > 2; }); } } if (terms.length === 0) return; var style = document.createElement('style'); style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }'; document.head.appendChild(style); function highlight(node) { if (node.nodeType === 3) { // text node var text = node.textContent; var found = false; terms.forEach(function(term) { var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\]\\]/g, '\\') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' refactor(shared,clerk-js,react): move QueryClient ownership into @clerk/shared by jacekradko · Pull Request #8434 · clerk/javascript · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions .changeset/invert-clerk-rq-ownership.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
---
'@clerk/shared': patch
'@clerk/clerk-js': patch
'@clerk/react': patch
---

Move ownership of the clerk-rq `QueryClient` from `@clerk/clerk-js` into `@clerk/shared`. The `QueryObserver` (constructed in `@clerk/shared`) and the `Query` objects it observes now always come from a single `@tanstack/query-core` resolution — the cross-bundle API contract that produced #8428 (`Query.isFetched is not a function`) no longer exists.

This removes the undocumented `clerk.__internal_queryClient` getter from both `@clerk/clerk-js` and `@clerk/react`'s `IsomorphicClerk`. The `QueryClient` is owned by an internal singleton in `@clerk/shared`, lazily instantiated on the browser only — server renders return `undefined`, preserving SSR safety and avoiding cross-request cache sharing.

`@tanstack/query-core` is no longer a direct dependency of `@clerk/clerk-js`; it remains a dep of `@clerk/shared` and resolves consumer-side as before.
1 change: 0 additions & 1 deletion packages/clerk-js/bundlewatch.config.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -9,7 +9,6 @@
{ "path": "./dist/coinbase*.js", "maxSize": "36KB" },
{ "path": "./dist/base-account-sdk*.js", "maxSize": "203KB" },
{ "path": "./dist/stripe-vendors*.js", "maxSize": "1KB" },
{ "path": "./dist/query-core-vendors*.js", "maxSize": "11KB" },
{ "path": "./dist/zxcvbn-ts-core*.js", "maxSize": "12KB" },
{ "path": "./dist/zxcvbn-common*.js", "maxSize": "226KB" }
]
Expand Down
1 change: 0 additions & 1 deletion packages/clerk-js/package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -91,7 +91,6 @@
"@solana/wallet-standard": "catalog:module-manager",
"@stripe/stripe-js": "5.6.0",
"@swc/helpers": "catalog:repo",
"@tanstack/query-core": "catalog:repo",
"@wallet-standard/core": "catalog:module-manager",
"@zxcvbn-ts/core": "catalog:module-manager",
"@zxcvbn-ts/language-common": "catalog:module-manager",
Expand Down
6 changes: 0 additions & 6 deletions packages/clerk-js/rspack.config.js
Original file line numberDiff line numberDiff line change
Expand Up@@ -110,12 +110,6 @@ const common = ({ mode, variant, disableRHC = false }) => {
chunks: 'all',
enforce: true,
},
queryCoreVendor: {
test: /[\\/]node_modules[\\/](@tanstack\/query-core)[\\/]/,
name: 'query-core-vendors',
chunks: 'all',
enforce: true,
},
defaultVendors: {
minChunks: 1,
test: module => {
Expand Down
24 changes: 0 additions & 24 deletions packages/clerk-js/src/core/clerk.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -138,7 +138,6 @@ import type {
import type { ClerkUI } from '@clerk/shared/ui';
import { addClerkPrefix, isAbsoluteUrl, stripScheme } from '@clerk/shared/url';
import { allSettled, handleValueOrFn, noop } from '@clerk/shared/utils';
import type { QueryClient } from '@tanstack/query-core';

import { debugLogger, initDebugLogger } from '@/utils/debug';
import { ModuleManager } from '@/utils/moduleManager';
Expand DownExpand Up@@ -248,7 +247,6 @@ export class Clerk implements ClerkInterface {
// converted to protected environment to support `updateEnvironment` type assertion
protected environment?: EnvironmentResource | null;

#queryClient: QueryClient | undefined;
#publishableKey = '';
#domain: DomainOrProxyUrl['domain'];
#proxyUrl: DomainOrProxyUrl['proxyUrl'];
Expand All@@ -268,28 +266,6 @@ export class Clerk implements ClerkInterface {
#touchThrottledUntil = 0;
#publicEventBus = createClerkEventBus();

get __internal_queryClient(): { __tag: 'clerk-rq-client'; client: QueryClient } | undefined {
if (!this.#queryClient) {
void import('./query-core')
.then(module => module.QueryClient)
.then(QueryClient => {
if (this.#queryClient) {
return;
}
this.#queryClient = new QueryClient();
// @ts-expect-error - queryClientStatus is not typed
this.#publicEventBus.emit('queryClientStatus', 'ready');
});
}

return this.#queryClient
? {
__tag: 'clerk-rq-client',
client: this.#queryClient,
}
: undefined;
}

public __internal_getCachedResources:
| (() => Promise<{ client: ClientJSONSnapshot | null; environment: EnvironmentJSONSnapshot | null }>)
| undefined;
Expand Down
3 changes: 0 additions & 3 deletions packages/clerk-js/src/core/query-core.ts

This file was deleted.

22 changes: 2 additions & 20 deletions packages/clerk-js/src/test/mock-helpers.ts
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
import { __createClerkTestQueryClient } from '@clerk/shared/react';
import type { ActiveSessionResource, LoadedClerk } from '@clerk/shared/types';
import { type Mocked, vi } from 'vitest';

import { QueryClient } from '../core/query-core';
import type { RouteContextValue } from '../ui/router';

type FunctionLike = (...args: any) => any;
Expand DownExpand Up@@ -46,19 +46,7 @@ export const mockClerkMethods = (clerk: LoadedClerk): DeepVitestMocked<LoadedCle
// Cast clerk to any to allow mocking properties
const clerkAny = clerk as any;

const defaultQueryClient = {
__tag: 'clerk-rq-client' as const,
client: new QueryClient({
defaultOptions: {
queries: {
retry: false,
// Setting staleTime to Infinity will not cause issues between tests as long as each test
// case has its own wrapper that initializes a Clerk instance with a new QueryClient.
staleTime: Infinity,
},
},
}),
};
__createClerkTestQueryClient();

mockMethodsOf(clerkAny);
if (clerkAny.client) {
Expand DownExpand Up@@ -92,12 +80,6 @@ export const mockClerkMethods = (clerk: LoadedClerk): DeepVitestMocked<LoadedCle
mockMethodsOf(clerkAny.billing);
}

// Mock the __internal_queryClient getter property
Object.defineProperty(clerkAny, '__internal_queryClient', {
get: vi.fn(() => defaultQueryClient),
configurable: true,
});

mockProp(clerkAny, 'navigate');
mockProp(clerkAny, 'setActive');
mockProp(clerkAny, 'redirectWithAuth');
Expand Down
12 changes: 0 additions & 12 deletions packages/react/src/isomorphicClerk.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -344,11 +344,6 @@ export class IsomorphicClerk implements IsomorphicLoadedClerk {
return this.clerkjs?.isStandardBrowser || this.options.standardBrowser || false;
}

get __internal_queryClient() {
// @ts-expect-error - __internal_queryClient is not typed
return this.clerkjs?.__internal_queryClient;
}

get isSatellite() {
// This getter can run in environments where window is not available.
// In those cases we should expect and use domain as a string
Expand DownExpand Up@@ -656,13 +651,6 @@ export class IsomorphicClerk implements IsomorphicLoadedClerk {
this.on('status', listener, { notify: true });
});

// @ts-expect-error - queryClientStatus is not typed
this.#eventBus.internal.retrieveListeners('queryClientStatus')?.forEach(listener => {
// Since clerkjs exists it will call `this.clerkjs.on('queryClientStatus', listener)`
// @ts-expect-error - queryClientStatus is not typed
this.on('queryClientStatus', listener, { notify: true });
});

if (this.preopenSignIn !== null) {
clerkjs.openSignIn(this.preopenSignIn);
}
Expand Down
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
import { QueryClient } from '@tanstack/query-core';
import { afterEach, describe, expect, it, vi } from 'vitest';

import {
__createClerkTestQueryClient,
__resetClerkQueryClientForTest,
__setClerkQueryClientForTest,
getClerkQueryClient,
} from '../clerk-query-client';

afterEach(() => {
vi.unstubAllGlobals();
__resetClerkQueryClientForTest();
});

describe('getClerkQueryClient', () => {
it('returns undefined when window is not defined (SSR)', () => {
vi.stubGlobal('window', undefined);

expect(getClerkQueryClient()).toBeUndefined();
});

it('does not cache the SSR undefined — a later browser call still creates a client', () => {
vi.stubGlobal('window', undefined);
expect(getClerkQueryClient()).toBeUndefined();

vi.unstubAllGlobals();
const client = getClerkQueryClient();
expect(client).toBeInstanceOf(QueryClient);
});

it('lazy-creates a singleton on the browser and returns the same instance on repeated calls', () => {
const first = getClerkQueryClient();
const second = getClerkQueryClient();

expect(first).toBeInstanceOf(QueryClient);
expect(second).toBe(first);
});
});

describe('__resetClerkQueryClientForTest', () => {
it('clears the singleton so the next read lazy-creates a fresh client', () => {
const original = getClerkQueryClient();
expect(original).toBeInstanceOf(QueryClient);

__resetClerkQueryClientForTest();

const next = getClerkQueryClient();
expect(next).toBeInstanceOf(QueryClient);
expect(next).not.toBe(original);
});
});

describe('__setClerkQueryClientForTest', () => {
it('installs a caller-supplied client and returns it from getClerkQueryClient', () => {
const custom = new QueryClient();
__setClerkQueryClientForTest(custom);

expect(getClerkQueryClient()).toBe(custom);
});

it('installs the "no client" state without triggering lazy creation on subsequent reads', () => {
__setClerkQueryClientForTest(undefined);

expect(getClerkQueryClient()).toBeUndefined();
expect(getClerkQueryClient()).toBeUndefined();
});
});

describe('__createClerkTestQueryClient', () => {
it('returns a QueryClient with deterministic defaults and installs it as the singleton', () => {
const client = __createClerkTestQueryClient();

expect(client).toBeInstanceOf(QueryClient);
expect(getClerkQueryClient()).toBe(client);

const defaults = client.getDefaultOptions().queries;
expect(defaults?.retry).toBe(false);
expect(defaults?.staleTime).toBe(Infinity);
expect(defaults?.refetchOnWindowFocus).toBe(false);
expect(defaults?.refetchOnReconnect).toBe(false);
expect(defaults?.refetchOnMount).toBe(false);
});
});
Original file line numberDiff line numberDiff line change
Expand Up@@ -3,6 +3,7 @@ import React from 'react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';

import { createMockClerk, createMockQueryClient } from '../../hooks/__tests__/mocks/clerk';
import { __resetClerkQueryClientForTest, __setClerkQueryClientForTest } from '../clerk-query-client';
import { useClerkInfiniteQuery } from '../useInfiniteQuery';
import { useClerkQuery } from '../useQuery';

Expand All@@ -16,22 +17,15 @@ vi.mock('../../contexts', () => ({

const wrapper = ({ children }: { children: React.ReactNode }) => <>{children}</>;

const makeClerkWithoutQueryClient = () => {
const mockClerk = createMockClerk({ queryClient: null });
Object.defineProperty(mockClerk, '__internal_queryClient', {
get: () => undefined,
configurable: true,
});
return mockClerk;
};

afterEach(() => {
vi.clearAllMocks();
__resetClerkQueryClientForTest();
});

describe('useBaseQuery - dummy result while query client is not attached', () => {
beforeEach(() => {
activeClerk = makeClerkWithoutQueryClient();
activeClerk = createMockClerk({ queryClient: null });
__setClerkQueryClientForTest(undefined);
});

it('reports isLoading: true when the query would be enabled', () => {
Expand DownExpand Up@@ -109,8 +103,8 @@ describe('useBaseQuery - dummy result while query client is not attached', () =>

describe('useBaseQuery - normal behavior once query client attaches', () => {
it('delegates to the real observer when the query client is loaded', async () => {
const queryClient = createMockQueryClient();
activeClerk = createMockClerk({ queryClient });
createMockQueryClient();
activeClerk = createMockClerk({ queryClient: undefined });

const queryFn = vi.fn(async () => 'result');
const { result } = renderHook(
Expand Down
66 changes: 66 additions & 0 deletions packages/shared/src/react/clerk-rq/clerk-query-client.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
import { QueryClient } from '@tanstack/query-core';

/**
* The QueryClient backing every clerk-rq hook. Owned by `@clerk/shared` so the
* `QueryObserver` that observes it and the `Query` objects inside it always
* resolve to the same `@tanstack/query-core` (no cross-bundle drift between
* the consumer-side `@clerk/shared` and the production CDN `clerk-js` bundle).
*
* Lazily instantiated on the client only. Server-side renders return
* `undefined` so per-request renders never share a cache across requests.
*/
let clerkQueryClient: QueryClient | undefined;
let initialized = false;

export function getClerkQueryClient(): QueryClient | undefined {
if (typeof window === 'undefined') {
return undefined;
}
if (!initialized) {
clerkQueryClient = new QueryClient();
initialized = true;
}
return clerkQueryClient;
}

/**
* Test-only: install a custom client (for deterministic defaults like
* `staleTime: Infinity`) or pass `undefined` to simulate the "no client"
* state without triggering lazy creation on subsequent reads.
*/
export function __setClerkQueryClientForTest(client: QueryClient | undefined): void {
clerkQueryClient = client;
initialized = true;
}

/**
* Test-only: build and install a fresh `QueryClient` with deterministic
* defaults (no retries, infinite stale time, no refetching). Returns the
* client so the spec can read/write its cache directly.
*
* Avoids forcing every test consumer to depend on `@tanstack/query-core`.
*/
export function __createClerkTestQueryClient(): QueryClient {
const client = new QueryClient({
defaultOptions: {
queries: {
retry: false,
staleTime: Infinity,
refetchOnWindowFocus: false,
refetchOnReconnect: false,
refetchOnMount: false,
},
},
});
__setClerkQueryClientForTest(client);
return client;
}

/**
* Test-only: clear both the override and the initialization flag so the
* next read lazy-creates a fresh client.
*/
export function __resetClerkQueryClientForTest(): void {
clerkQueryClient = undefined;
initialized = false;
}
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + ' refactor(shared,clerk-js,react): move QueryClient ownership into @clerk/shared by jacekradko · Pull Request #8434 · clerk/javascript · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions .changeset/invert-clerk-rq-ownership.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
---
'@clerk/shared': patch
'@clerk/clerk-js': patch
'@clerk/react': patch
---

Move ownership of the clerk-rq `QueryClient` from `@clerk/clerk-js` into `@clerk/shared`. The `QueryObserver` (constructed in `@clerk/shared`) and the `Query` objects it observes now always come from a single `@tanstack/query-core` resolution — the cross-bundle API contract that produced #8428 (`Query.isFetched is not a function`) no longer exists.

This removes the undocumented `clerk.__internal_queryClient` getter from both `@clerk/clerk-js` and `@clerk/react`'s `IsomorphicClerk`. The `QueryClient` is owned by an internal singleton in `@clerk/shared`, lazily instantiated on the browser only — server renders return `undefined`, preserving SSR safety and avoiding cross-request cache sharing.

`@tanstack/query-core` is no longer a direct dependency of `@clerk/clerk-js`; it remains a dep of `@clerk/shared` and resolves consumer-side as before.
1 change: 0 additions & 1 deletion packages/clerk-js/bundlewatch.config.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -9,7 +9,6 @@
{ "path": "./dist/coinbase*.js", "maxSize": "36KB" },
{ "path": "./dist/base-account-sdk*.js", "maxSize": "203KB" },
{ "path": "./dist/stripe-vendors*.js", "maxSize": "1KB" },
{ "path": "./dist/query-core-vendors*.js", "maxSize": "11KB" },
{ "path": "./dist/zxcvbn-ts-core*.js", "maxSize": "12KB" },
{ "path": "./dist/zxcvbn-common*.js", "maxSize": "226KB" }
]
Expand Down
1 change: 0 additions & 1 deletion packages/clerk-js/package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -91,7 +91,6 @@
"@solana/wallet-standard": "catalog:module-manager",
"@stripe/stripe-js": "5.6.0",
"@swc/helpers": "catalog:repo",
"@tanstack/query-core": "catalog:repo",
"@wallet-standard/core": "catalog:module-manager",
"@zxcvbn-ts/core": "catalog:module-manager",
"@zxcvbn-ts/language-common": "catalog:module-manager",
Expand Down
6 changes: 0 additions & 6 deletions packages/clerk-js/rspack.config.js
Original file line numberDiff line numberDiff line change
Expand Up@@ -110,12 +110,6 @@ const common = ({ mode, variant, disableRHC = false }) => {
chunks: 'all',
enforce: true,
},
queryCoreVendor: {
test: /[\\/]node_modules[\\/](@tanstack\/query-core)[\\/]/,
name: 'query-core-vendors',
chunks: 'all',
enforce: true,
},
defaultVendors: {
minChunks: 1,
test: module => {
Expand Down
24 changes: 0 additions & 24 deletions packages/clerk-js/src/core/clerk.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -138,7 +138,6 @@ import type {
import type { ClerkUI } from '@clerk/shared/ui';
import { addClerkPrefix, isAbsoluteUrl, stripScheme } from '@clerk/shared/url';
import { allSettled, handleValueOrFn, noop } from '@clerk/shared/utils';
import type { QueryClient } from '@tanstack/query-core';

import { debugLogger, initDebugLogger } from '@/utils/debug';
import { ModuleManager } from '@/utils/moduleManager';
Expand DownExpand Up@@ -248,7 +247,6 @@ export class Clerk implements ClerkInterface {
// converted to protected environment to support `updateEnvironment` type assertion
protected environment?: EnvironmentResource | null;

#queryClient: QueryClient | undefined;
#publishableKey = '';
#domain: DomainOrProxyUrl['domain'];
#proxyUrl: DomainOrProxyUrl['proxyUrl'];
Expand All@@ -268,28 +266,6 @@ export class Clerk implements ClerkInterface {
#touchThrottledUntil = 0;
#publicEventBus = createClerkEventBus();

get __internal_queryClient(): { __tag: 'clerk-rq-client'; client: QueryClient } | undefined {
if (!this.#queryClient) {
void import('./query-core')
.then(module => module.QueryClient)
.then(QueryClient => {
if (this.#queryClient) {
return;
}
this.#queryClient = new QueryClient();
// @ts-expect-error - queryClientStatus is not typed
this.#publicEventBus.emit('queryClientStatus', 'ready');
});
}

return this.#queryClient
? {
__tag: 'clerk-rq-client',
client: this.#queryClient,
}
: undefined;
}

public __internal_getCachedResources:
| (() => Promise<{ client: ClientJSONSnapshot | null; environment: EnvironmentJSONSnapshot | null }>)
| undefined;
Expand Down
3 changes: 0 additions & 3 deletions packages/clerk-js/src/core/query-core.ts

This file was deleted.

22 changes: 2 additions & 20 deletions packages/clerk-js/src/test/mock-helpers.ts
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
import { __createClerkTestQueryClient } from '@clerk/shared/react';
import type { ActiveSessionResource, LoadedClerk } from '@clerk/shared/types';
import { type Mocked, vi } from 'vitest';

import { QueryClient } from '../core/query-core';
import type { RouteContextValue } from '../ui/router';

type FunctionLike = (...args: any) => any;
Expand DownExpand Up@@ -46,19 +46,7 @@ export const mockClerkMethods = (clerk: LoadedClerk): DeepVitestMocked<LoadedCle
// Cast clerk to any to allow mocking properties
const clerkAny = clerk as any;

const defaultQueryClient = {
__tag: 'clerk-rq-client' as const,
client: new QueryClient({
defaultOptions: {
queries: {
retry: false,
// Setting staleTime to Infinity will not cause issues between tests as long as each test
// case has its own wrapper that initializes a Clerk instance with a new QueryClient.
staleTime: Infinity,
},
},
}),
};
__createClerkTestQueryClient();

mockMethodsOf(clerkAny);
if (clerkAny.client) {
Expand DownExpand Up@@ -92,12 +80,6 @@ export const mockClerkMethods = (clerk: LoadedClerk): DeepVitestMocked<LoadedCle
mockMethodsOf(clerkAny.billing);
}

// Mock the __internal_queryClient getter property
Object.defineProperty(clerkAny, '__internal_queryClient', {
get: vi.fn(() => defaultQueryClient),
configurable: true,
});

mockProp(clerkAny, 'navigate');
mockProp(clerkAny, 'setActive');
mockProp(clerkAny, 'redirectWithAuth');
Expand Down
12 changes: 0 additions & 12 deletions packages/react/src/isomorphicClerk.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -344,11 +344,6 @@ export class IsomorphicClerk implements IsomorphicLoadedClerk {
return this.clerkjs?.isStandardBrowser || this.options.standardBrowser || false;
}

get __internal_queryClient() {
// @ts-expect-error - __internal_queryClient is not typed
return this.clerkjs?.__internal_queryClient;
}

get isSatellite() {
// This getter can run in environments where window is not available.
// In those cases we should expect and use domain as a string
Expand DownExpand Up@@ -656,13 +651,6 @@ export class IsomorphicClerk implements IsomorphicLoadedClerk {
this.on('status', listener, { notify: true });
});

// @ts-expect-error - queryClientStatus is not typed
this.#eventBus.internal.retrieveListeners('queryClientStatus')?.forEach(listener => {
// Since clerkjs exists it will call `this.clerkjs.on('queryClientStatus', listener)`
// @ts-expect-error - queryClientStatus is not typed
this.on('queryClientStatus', listener, { notify: true });
});

if (this.preopenSignIn !== null) {
clerkjs.openSignIn(this.preopenSignIn);
}
Expand Down
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
import { QueryClient } from '@tanstack/query-core';
import { afterEach, describe, expect, it, vi } from 'vitest';

import {
__createClerkTestQueryClient,
__resetClerkQueryClientForTest,
__setClerkQueryClientForTest,
getClerkQueryClient,
} from '../clerk-query-client';

afterEach(() => {
vi.unstubAllGlobals();
__resetClerkQueryClientForTest();
});

describe('getClerkQueryClient', () => {
it('returns undefined when window is not defined (SSR)', () => {
vi.stubGlobal('window', undefined);

expect(getClerkQueryClient()).toBeUndefined();
});

it('does not cache the SSR undefined — a later browser call still creates a client', () => {
vi.stubGlobal('window', undefined);
expect(getClerkQueryClient()).toBeUndefined();

vi.unstubAllGlobals();
const client = getClerkQueryClient();
expect(client).toBeInstanceOf(QueryClient);
});

it('lazy-creates a singleton on the browser and returns the same instance on repeated calls', () => {
const first = getClerkQueryClient();
const second = getClerkQueryClient();

expect(first).toBeInstanceOf(QueryClient);
expect(second).toBe(first);
});
});

describe('__resetClerkQueryClientForTest', () => {
it('clears the singleton so the next read lazy-creates a fresh client', () => {
const original = getClerkQueryClient();
expect(original).toBeInstanceOf(QueryClient);

__resetClerkQueryClientForTest();

const next = getClerkQueryClient();
expect(next).toBeInstanceOf(QueryClient);
expect(next).not.toBe(original);
});
});

describe('__setClerkQueryClientForTest', () => {
it('installs a caller-supplied client and returns it from getClerkQueryClient', () => {
const custom = new QueryClient();
__setClerkQueryClientForTest(custom);

expect(getClerkQueryClient()).toBe(custom);
});

it('installs the "no client" state without triggering lazy creation on subsequent reads', () => {
__setClerkQueryClientForTest(undefined);

expect(getClerkQueryClient()).toBeUndefined();
expect(getClerkQueryClient()).toBeUndefined();
});
});

describe('__createClerkTestQueryClient', () => {
it('returns a QueryClient with deterministic defaults and installs it as the singleton', () => {
const client = __createClerkTestQueryClient();

expect(client).toBeInstanceOf(QueryClient);
expect(getClerkQueryClient()).toBe(client);

const defaults = client.getDefaultOptions().queries;
expect(defaults?.retry).toBe(false);
expect(defaults?.staleTime).toBe(Infinity);
expect(defaults?.refetchOnWindowFocus).toBe(false);
expect(defaults?.refetchOnReconnect).toBe(false);
expect(defaults?.refetchOnMount).toBe(false);
});
});
Original file line numberDiff line numberDiff line change
Expand Up@@ -3,6 +3,7 @@ import React from 'react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';

import { createMockClerk, createMockQueryClient } from '../../hooks/__tests__/mocks/clerk';
import { __resetClerkQueryClientForTest, __setClerkQueryClientForTest } from '../clerk-query-client';
import { useClerkInfiniteQuery } from '../useInfiniteQuery';
import { useClerkQuery } from '../useQuery';

Expand All@@ -16,22 +17,15 @@ vi.mock('../../contexts', () => ({

const wrapper = ({ children }: { children: React.ReactNode }) => <>{children}</>;

const makeClerkWithoutQueryClient = () => {
const mockClerk = createMockClerk({ queryClient: null });
Object.defineProperty(mockClerk, '__internal_queryClient', {
get: () => undefined,
configurable: true,
});
return mockClerk;
};

afterEach(() => {
vi.clearAllMocks();
__resetClerkQueryClientForTest();
});

describe('useBaseQuery - dummy result while query client is not attached', () => {
beforeEach(() => {
activeClerk = makeClerkWithoutQueryClient();
activeClerk = createMockClerk({ queryClient: null });
__setClerkQueryClientForTest(undefined);
});

it('reports isLoading: true when the query would be enabled', () => {
Expand DownExpand Up@@ -109,8 +103,8 @@ describe('useBaseQuery - dummy result while query client is not attached', () =>

describe('useBaseQuery - normal behavior once query client attaches', () => {
it('delegates to the real observer when the query client is loaded', async () => {
const queryClient = createMockQueryClient();
activeClerk = createMockClerk({ queryClient });
createMockQueryClient();
activeClerk = createMockClerk({ queryClient: undefined });

const queryFn = vi.fn(async () => 'result');
const { result } = renderHook(
Expand Down
66 changes: 66 additions & 0 deletions packages/shared/src/react/clerk-rq/clerk-query-client.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
import { QueryClient } from '@tanstack/query-core';

/**
* The QueryClient backing every clerk-rq hook. Owned by `@clerk/shared` so the
* `QueryObserver` that observes it and the `Query` objects inside it always
* resolve to the same `@tanstack/query-core` (no cross-bundle drift between
* the consumer-side `@clerk/shared` and the production CDN `clerk-js` bundle).
*
* Lazily instantiated on the client only. Server-side renders return
* `undefined` so per-request renders never share a cache across requests.
*/
let clerkQueryClient: QueryClient | undefined;
let initialized = false;

export function getClerkQueryClient(): QueryClient | undefined {
if (typeof window === 'undefined') {
return undefined;
}
if (!initialized) {
clerkQueryClient = new QueryClient();
initialized = true;
}
return clerkQueryClient;
}

/**
* Test-only: install a custom client (for deterministic defaults like
* `staleTime: Infinity`) or pass `undefined` to simulate the "no client"
* state without triggering lazy creation on subsequent reads.
*/
export function __setClerkQueryClientForTest(client: QueryClient | undefined): void {
clerkQueryClient = client;
initialized = true;
}

/**
* Test-only: build and install a fresh `QueryClient` with deterministic
* defaults (no retries, infinite stale time, no refetching). Returns the
* client so the spec can read/write its cache directly.
*
* Avoids forcing every test consumer to depend on `@tanstack/query-core`.
*/
export function __createClerkTestQueryClient(): QueryClient {
const client = new QueryClient({
defaultOptions: {
queries: {
retry: false,
staleTime: Infinity,
refetchOnWindowFocus: false,
refetchOnReconnect: false,
refetchOnMount: false,
},
},
});
__setClerkQueryClientForTest(client);
return client;
}

/**
* Test-only: clear both the override and the initialization flag so the
* next read lazy-creates a fresh client.
*/
export function __resetClerkQueryClientForTest(): void {
clerkQueryClient = undefined;
initialized = false;
}
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' refactor(shared,clerk-js,react): move QueryClient ownership into @clerk/shared by jacekradko · Pull Request #8434 · clerk/javascript · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions .changeset/invert-clerk-rq-ownership.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
---
'@clerk/shared': patch
'@clerk/clerk-js': patch
'@clerk/react': patch
---

Move ownership of the clerk-rq `QueryClient` from `@clerk/clerk-js` into `@clerk/shared`. The `QueryObserver` (constructed in `@clerk/shared`) and the `Query` objects it observes now always come from a single `@tanstack/query-core` resolution — the cross-bundle API contract that produced #8428 (`Query.isFetched is not a function`) no longer exists.

This removes the undocumented `clerk.__internal_queryClient` getter from both `@clerk/clerk-js` and `@clerk/react`'s `IsomorphicClerk`. The `QueryClient` is owned by an internal singleton in `@clerk/shared`, lazily instantiated on the browser only — server renders return `undefined`, preserving SSR safety and avoiding cross-request cache sharing.

`@tanstack/query-core` is no longer a direct dependency of `@clerk/clerk-js`; it remains a dep of `@clerk/shared` and resolves consumer-side as before.
1 change: 0 additions & 1 deletion packages/clerk-js/bundlewatch.config.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -9,7 +9,6 @@
{ "path": "./dist/coinbase*.js", "maxSize": "36KB" },
{ "path": "./dist/base-account-sdk*.js", "maxSize": "203KB" },
{ "path": "./dist/stripe-vendors*.js", "maxSize": "1KB" },
{ "path": "./dist/query-core-vendors*.js", "maxSize": "11KB" },
{ "path": "./dist/zxcvbn-ts-core*.js", "maxSize": "12KB" },
{ "path": "./dist/zxcvbn-common*.js", "maxSize": "226KB" }
]
Expand Down
1 change: 0 additions & 1 deletion packages/clerk-js/package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -91,7 +91,6 @@
"@solana/wallet-standard": "catalog:module-manager",
"@stripe/stripe-js": "5.6.0",
"@swc/helpers": "catalog:repo",
"@tanstack/query-core": "catalog:repo",
"@wallet-standard/core": "catalog:module-manager",
"@zxcvbn-ts/core": "catalog:module-manager",
"@zxcvbn-ts/language-common": "catalog:module-manager",
Expand Down
6 changes: 0 additions & 6 deletions packages/clerk-js/rspack.config.js
Original file line numberDiff line numberDiff line change
Expand Up@@ -110,12 +110,6 @@ const common = ({ mode, variant, disableRHC = false }) => {
chunks: 'all',
enforce: true,
},
queryCoreVendor: {
test: /[\\/]node_modules[\\/](@tanstack\/query-core)[\\/]/,
name: 'query-core-vendors',
chunks: 'all',
enforce: true,
},
defaultVendors: {
minChunks: 1,
test: module => {
Expand Down
24 changes: 0 additions & 24 deletions packages/clerk-js/src/core/clerk.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -138,7 +138,6 @@ import type {
import type { ClerkUI } from '@clerk/shared/ui';
import { addClerkPrefix, isAbsoluteUrl, stripScheme } from '@clerk/shared/url';
import { allSettled, handleValueOrFn, noop } from '@clerk/shared/utils';
import type { QueryClient } from '@tanstack/query-core';

import { debugLogger, initDebugLogger } from '@/utils/debug';
import { ModuleManager } from '@/utils/moduleManager';
Expand DownExpand Up@@ -248,7 +247,6 @@ export class Clerk implements ClerkInterface {
// converted to protected environment to support `updateEnvironment` type assertion
protected environment?: EnvironmentResource | null;

#queryClient: QueryClient | undefined;
#publishableKey = '';
#domain: DomainOrProxyUrl['domain'];
#proxyUrl: DomainOrProxyUrl['proxyUrl'];
Expand All@@ -268,28 +266,6 @@ export class Clerk implements ClerkInterface {
#touchThrottledUntil = 0;
#publicEventBus = createClerkEventBus();

get __internal_queryClient(): { __tag: 'clerk-rq-client'; client: QueryClient } | undefined {
if (!this.#queryClient) {
void import('./query-core')
.then(module => module.QueryClient)
.then(QueryClient => {
if (this.#queryClient) {
return;
}
this.#queryClient = new QueryClient();
// @ts-expect-error - queryClientStatus is not typed
this.#publicEventBus.emit('queryClientStatus', 'ready');
});
}

return this.#queryClient
? {
__tag: 'clerk-rq-client',
client: this.#queryClient,
}
: undefined;
}

public __internal_getCachedResources:
| (() => Promise<{ client: ClientJSONSnapshot | null; environment: EnvironmentJSONSnapshot | null }>)
| undefined;
Expand Down
3 changes: 0 additions & 3 deletions packages/clerk-js/src/core/query-core.ts

This file was deleted.

22 changes: 2 additions & 20 deletions packages/clerk-js/src/test/mock-helpers.ts
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
import { __createClerkTestQueryClient } from '@clerk/shared/react';
import type { ActiveSessionResource, LoadedClerk } from '@clerk/shared/types';
import { type Mocked, vi } from 'vitest';

import { QueryClient } from '../core/query-core';
import type { RouteContextValue } from '../ui/router';

type FunctionLike = (...args: any) => any;
Expand DownExpand Up@@ -46,19 +46,7 @@ export const mockClerkMethods = (clerk: LoadedClerk): DeepVitestMocked<LoadedCle
// Cast clerk to any to allow mocking properties
const clerkAny = clerk as any;

const defaultQueryClient = {
__tag: 'clerk-rq-client' as const,
client: new QueryClient({
defaultOptions: {
queries: {
retry: false,
// Setting staleTime to Infinity will not cause issues between tests as long as each test
// case has its own wrapper that initializes a Clerk instance with a new QueryClient.
staleTime: Infinity,
},
},
}),
};
__createClerkTestQueryClient();

mockMethodsOf(clerkAny);
if (clerkAny.client) {
Expand DownExpand Up@@ -92,12 +80,6 @@ export const mockClerkMethods = (clerk: LoadedClerk): DeepVitestMocked<LoadedCle
mockMethodsOf(clerkAny.billing);
}

// Mock the __internal_queryClient getter property
Object.defineProperty(clerkAny, '__internal_queryClient', {
get: vi.fn(() => defaultQueryClient),
configurable: true,
});

mockProp(clerkAny, 'navigate');
mockProp(clerkAny, 'setActive');
mockProp(clerkAny, 'redirectWithAuth');
Expand Down
12 changes: 0 additions & 12 deletions packages/react/src/isomorphicClerk.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -344,11 +344,6 @@ export class IsomorphicClerk implements IsomorphicLoadedClerk {
return this.clerkjs?.isStandardBrowser || this.options.standardBrowser || false;
}

get __internal_queryClient() {
// @ts-expect-error - __internal_queryClient is not typed
return this.clerkjs?.__internal_queryClient;
}

get isSatellite() {
// This getter can run in environments where window is not available.
// In those cases we should expect and use domain as a string
Expand DownExpand Up@@ -656,13 +651,6 @@ export class IsomorphicClerk implements IsomorphicLoadedClerk {
this.on('status', listener, { notify: true });
});

// @ts-expect-error - queryClientStatus is not typed
this.#eventBus.internal.retrieveListeners('queryClientStatus')?.forEach(listener => {
// Since clerkjs exists it will call `this.clerkjs.on('queryClientStatus', listener)`
// @ts-expect-error - queryClientStatus is not typed
this.on('queryClientStatus', listener, { notify: true });
});

if (this.preopenSignIn !== null) {
clerkjs.openSignIn(this.preopenSignIn);
}
Expand Down
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
import { QueryClient } from '@tanstack/query-core';
import { afterEach, describe, expect, it, vi } from 'vitest';

import {
__createClerkTestQueryClient,
__resetClerkQueryClientForTest,
__setClerkQueryClientForTest,
getClerkQueryClient,
} from '../clerk-query-client';

afterEach(() => {
vi.unstubAllGlobals();
__resetClerkQueryClientForTest();
});

describe('getClerkQueryClient', () => {
it('returns undefined when window is not defined (SSR)', () => {
vi.stubGlobal('window', undefined);

expect(getClerkQueryClient()).toBeUndefined();
});

it('does not cache the SSR undefined — a later browser call still creates a client', () => {
vi.stubGlobal('window', undefined);
expect(getClerkQueryClient()).toBeUndefined();

vi.unstubAllGlobals();
const client = getClerkQueryClient();
expect(client).toBeInstanceOf(QueryClient);
});

it('lazy-creates a singleton on the browser and returns the same instance on repeated calls', () => {
const first = getClerkQueryClient();
const second = getClerkQueryClient();

expect(first).toBeInstanceOf(QueryClient);
expect(second).toBe(first);
});
});

describe('__resetClerkQueryClientForTest', () => {
it('clears the singleton so the next read lazy-creates a fresh client', () => {
const original = getClerkQueryClient();
expect(original).toBeInstanceOf(QueryClient);

__resetClerkQueryClientForTest();

const next = getClerkQueryClient();
expect(next).toBeInstanceOf(QueryClient);
expect(next).not.toBe(original);
});
});

describe('__setClerkQueryClientForTest', () => {
it('installs a caller-supplied client and returns it from getClerkQueryClient', () => {
const custom = new QueryClient();
__setClerkQueryClientForTest(custom);

expect(getClerkQueryClient()).toBe(custom);
});

it('installs the "no client" state without triggering lazy creation on subsequent reads', () => {
__setClerkQueryClientForTest(undefined);

expect(getClerkQueryClient()).toBeUndefined();
expect(getClerkQueryClient()).toBeUndefined();
});
});

describe('__createClerkTestQueryClient', () => {
it('returns a QueryClient with deterministic defaults and installs it as the singleton', () => {
const client = __createClerkTestQueryClient();

expect(client).toBeInstanceOf(QueryClient);
expect(getClerkQueryClient()).toBe(client);

const defaults = client.getDefaultOptions().queries;
expect(defaults?.retry).toBe(false);
expect(defaults?.staleTime).toBe(Infinity);
expect(defaults?.refetchOnWindowFocus).toBe(false);
expect(defaults?.refetchOnReconnect).toBe(false);
expect(defaults?.refetchOnMount).toBe(false);
});
});
Original file line numberDiff line numberDiff line change
Expand Up@@ -3,6 +3,7 @@ import React from 'react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';

import { createMockClerk, createMockQueryClient } from '../../hooks/__tests__/mocks/clerk';
import { __resetClerkQueryClientForTest, __setClerkQueryClientForTest } from '../clerk-query-client';
import { useClerkInfiniteQuery } from '../useInfiniteQuery';
import { useClerkQuery } from '../useQuery';

Expand All@@ -16,22 +17,15 @@ vi.mock('../../contexts', () => ({

const wrapper = ({ children }: { children: React.ReactNode }) => <>{children}</>;

const makeClerkWithoutQueryClient = () => {
const mockClerk = createMockClerk({ queryClient: null });
Object.defineProperty(mockClerk, '__internal_queryClient', {
get: () => undefined,
configurable: true,
});
return mockClerk;
};

afterEach(() => {
vi.clearAllMocks();
__resetClerkQueryClientForTest();
});

describe('useBaseQuery - dummy result while query client is not attached', () => {
beforeEach(() => {
activeClerk = makeClerkWithoutQueryClient();
activeClerk = createMockClerk({ queryClient: null });
__setClerkQueryClientForTest(undefined);
});

it('reports isLoading: true when the query would be enabled', () => {
Expand DownExpand Up@@ -109,8 +103,8 @@ describe('useBaseQuery - dummy result while query client is not attached', () =>

describe('useBaseQuery - normal behavior once query client attaches', () => {
it('delegates to the real observer when the query client is loaded', async () => {
const queryClient = createMockQueryClient();
activeClerk = createMockClerk({ queryClient });
createMockQueryClient();
activeClerk = createMockClerk({ queryClient: undefined });

const queryFn = vi.fn(async () => 'result');
const { result } = renderHook(
Expand Down
66 changes: 66 additions & 0 deletions packages/shared/src/react/clerk-rq/clerk-query-client.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
import { QueryClient } from '@tanstack/query-core';

/**
* The QueryClient backing every clerk-rq hook. Owned by `@clerk/shared` so the
* `QueryObserver` that observes it and the `Query` objects inside it always
* resolve to the same `@tanstack/query-core` (no cross-bundle drift between
* the consumer-side `@clerk/shared` and the production CDN `clerk-js` bundle).
*
* Lazily instantiated on the client only. Server-side renders return
* `undefined` so per-request renders never share a cache across requests.
*/
let clerkQueryClient: QueryClient | undefined;
let initialized = false;

export function getClerkQueryClient(): QueryClient | undefined {
if (typeof window === 'undefined') {
return undefined;
}
if (!initialized) {
clerkQueryClient = new QueryClient();
initialized = true;
}
return clerkQueryClient;
}

/**
* Test-only: install a custom client (for deterministic defaults like
* `staleTime: Infinity`) or pass `undefined` to simulate the "no client"
* state without triggering lazy creation on subsequent reads.
*/
export function __setClerkQueryClientForTest(client: QueryClient | undefined): void {
clerkQueryClient = client;
initialized = true;
}

/**
* Test-only: build and install a fresh `QueryClient` with deterministic
* defaults (no retries, infinite stale time, no refetching). Returns the
* client so the spec can read/write its cache directly.
*
* Avoids forcing every test consumer to depend on `@tanstack/query-core`.
*/
export function __createClerkTestQueryClient(): QueryClient {
const client = new QueryClient({
defaultOptions: {
queries: {
retry: false,
staleTime: Infinity,
refetchOnWindowFocus: false,
refetchOnReconnect: false,
refetchOnMount: false,
},
},
});
__setClerkQueryClientForTest(client);
return client;
}

/**
* Test-only: clear both the override and the initialization flag so the
* next read lazy-creates a fresh client.
*/
export function __resetClerkQueryClientForTest(): void {
clerkQueryClient = undefined;
initialized = false;
}
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' refactor(shared,clerk-js,react): move QueryClient ownership into @clerk/shared by jacekradko · Pull Request #8434 · clerk/javascript · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions .changeset/invert-clerk-rq-ownership.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
---
'@clerk/shared': patch
'@clerk/clerk-js': patch
'@clerk/react': patch
---

Move ownership of the clerk-rq `QueryClient` from `@clerk/clerk-js` into `@clerk/shared`. The `QueryObserver` (constructed in `@clerk/shared`) and the `Query` objects it observes now always come from a single `@tanstack/query-core` resolution — the cross-bundle API contract that produced #8428 (`Query.isFetched is not a function`) no longer exists.

This removes the undocumented `clerk.__internal_queryClient` getter from both `@clerk/clerk-js` and `@clerk/react`'s `IsomorphicClerk`. The `QueryClient` is owned by an internal singleton in `@clerk/shared`, lazily instantiated on the browser only — server renders return `undefined`, preserving SSR safety and avoiding cross-request cache sharing.

`@tanstack/query-core` is no longer a direct dependency of `@clerk/clerk-js`; it remains a dep of `@clerk/shared` and resolves consumer-side as before.
1 change: 0 additions & 1 deletion packages/clerk-js/bundlewatch.config.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -9,7 +9,6 @@
{ "path": "./dist/coinbase*.js", "maxSize": "36KB" },
{ "path": "./dist/base-account-sdk*.js", "maxSize": "203KB" },
{ "path": "./dist/stripe-vendors*.js", "maxSize": "1KB" },
{ "path": "./dist/query-core-vendors*.js", "maxSize": "11KB" },
{ "path": "./dist/zxcvbn-ts-core*.js", "maxSize": "12KB" },
{ "path": "./dist/zxcvbn-common*.js", "maxSize": "226KB" }
]
Expand Down
1 change: 0 additions & 1 deletion packages/clerk-js/package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -91,7 +91,6 @@
"@solana/wallet-standard": "catalog:module-manager",
"@stripe/stripe-js": "5.6.0",
"@swc/helpers": "catalog:repo",
"@tanstack/query-core": "catalog:repo",
"@wallet-standard/core": "catalog:module-manager",
"@zxcvbn-ts/core": "catalog:module-manager",
"@zxcvbn-ts/language-common": "catalog:module-manager",
Expand Down
6 changes: 0 additions & 6 deletions packages/clerk-js/rspack.config.js
Original file line numberDiff line numberDiff line change
Expand Up@@ -110,12 +110,6 @@ const common = ({ mode, variant, disableRHC = false }) => {
chunks: 'all',
enforce: true,
},
queryCoreVendor: {
test: /[\\/]node_modules[\\/](@tanstack\/query-core)[\\/]/,
name: 'query-core-vendors',
chunks: 'all',
enforce: true,
},
defaultVendors: {
minChunks: 1,
test: module => {
Expand Down
24 changes: 0 additions & 24 deletions packages/clerk-js/src/core/clerk.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -138,7 +138,6 @@ import type {
import type { ClerkUI } from '@clerk/shared/ui';
import { addClerkPrefix, isAbsoluteUrl, stripScheme } from '@clerk/shared/url';
import { allSettled, handleValueOrFn, noop } from '@clerk/shared/utils';
import type { QueryClient } from '@tanstack/query-core';

import { debugLogger, initDebugLogger } from '@/utils/debug';
import { ModuleManager } from '@/utils/moduleManager';
Expand DownExpand Up@@ -248,7 +247,6 @@ export class Clerk implements ClerkInterface {
// converted to protected environment to support `updateEnvironment` type assertion
protected environment?: EnvironmentResource | null;

#queryClient: QueryClient | undefined;
#publishableKey = '';
#domain: DomainOrProxyUrl['domain'];
#proxyUrl: DomainOrProxyUrl['proxyUrl'];
Expand All@@ -268,28 +266,6 @@ export class Clerk implements ClerkInterface {
#touchThrottledUntil = 0;
#publicEventBus = createClerkEventBus();

get __internal_queryClient(): { __tag: 'clerk-rq-client'; client: QueryClient } | undefined {
if (!this.#queryClient) {
void import('./query-core')
.then(module => module.QueryClient)
.then(QueryClient => {
if (this.#queryClient) {
return;
}
this.#queryClient = new QueryClient();
// @ts-expect-error - queryClientStatus is not typed
this.#publicEventBus.emit('queryClientStatus', 'ready');
});
}

return this.#queryClient
? {
__tag: 'clerk-rq-client',
client: this.#queryClient,
}
: undefined;
}

public __internal_getCachedResources:
| (() => Promise<{ client: ClientJSONSnapshot | null; environment: EnvironmentJSONSnapshot | null }>)
| undefined;
Expand Down
3 changes: 0 additions & 3 deletions packages/clerk-js/src/core/query-core.ts

This file was deleted.

22 changes: 2 additions & 20 deletions packages/clerk-js/src/test/mock-helpers.ts
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
import { __createClerkTestQueryClient } from '@clerk/shared/react';
import type { ActiveSessionResource, LoadedClerk } from '@clerk/shared/types';
import { type Mocked, vi } from 'vitest';

import { QueryClient } from '../core/query-core';
import type { RouteContextValue } from '../ui/router';

type FunctionLike = (...args: any) => any;
Expand DownExpand Up@@ -46,19 +46,7 @@ export const mockClerkMethods = (clerk: LoadedClerk): DeepVitestMocked<LoadedCle
// Cast clerk to any to allow mocking properties
const clerkAny = clerk as any;

const defaultQueryClient = {
__tag: 'clerk-rq-client' as const,
client: new QueryClient({
defaultOptions: {
queries: {
retry: false,
// Setting staleTime to Infinity will not cause issues between tests as long as each test
// case has its own wrapper that initializes a Clerk instance with a new QueryClient.
staleTime: Infinity,
},
},
}),
};
__createClerkTestQueryClient();

mockMethodsOf(clerkAny);
if (clerkAny.client) {
Expand DownExpand Up@@ -92,12 +80,6 @@ export const mockClerkMethods = (clerk: LoadedClerk): DeepVitestMocked<LoadedCle
mockMethodsOf(clerkAny.billing);
}

// Mock the __internal_queryClient getter property
Object.defineProperty(clerkAny, '__internal_queryClient', {
get: vi.fn(() => defaultQueryClient),
configurable: true,
});

mockProp(clerkAny, 'navigate');
mockProp(clerkAny, 'setActive');
mockProp(clerkAny, 'redirectWithAuth');
Expand Down
12 changes: 0 additions & 12 deletions packages/react/src/isomorphicClerk.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -344,11 +344,6 @@ export class IsomorphicClerk implements IsomorphicLoadedClerk {
return this.clerkjs?.isStandardBrowser || this.options.standardBrowser || false;
}

get __internal_queryClient() {
// @ts-expect-error - __internal_queryClient is not typed
return this.clerkjs?.__internal_queryClient;
}

get isSatellite() {
// This getter can run in environments where window is not available.
// In those cases we should expect and use domain as a string
Expand DownExpand Up@@ -656,13 +651,6 @@ export class IsomorphicClerk implements IsomorphicLoadedClerk {
this.on('status', listener, { notify: true });
});

// @ts-expect-error - queryClientStatus is not typed
this.#eventBus.internal.retrieveListeners('queryClientStatus')?.forEach(listener => {
// Since clerkjs exists it will call `this.clerkjs.on('queryClientStatus', listener)`
// @ts-expect-error - queryClientStatus is not typed
this.on('queryClientStatus', listener, { notify: true });
});

if (this.preopenSignIn !== null) {
clerkjs.openSignIn(this.preopenSignIn);
}
Expand Down
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
import { QueryClient } from '@tanstack/query-core';
import { afterEach, describe, expect, it, vi } from 'vitest';

import {
__createClerkTestQueryClient,
__resetClerkQueryClientForTest,
__setClerkQueryClientForTest,
getClerkQueryClient,
} from '../clerk-query-client';

afterEach(() => {
vi.unstubAllGlobals();
__resetClerkQueryClientForTest();
});

describe('getClerkQueryClient', () => {
it('returns undefined when window is not defined (SSR)', () => {
vi.stubGlobal('window', undefined);

expect(getClerkQueryClient()).toBeUndefined();
});

it('does not cache the SSR undefined — a later browser call still creates a client', () => {
vi.stubGlobal('window', undefined);
expect(getClerkQueryClient()).toBeUndefined();

vi.unstubAllGlobals();
const client = getClerkQueryClient();
expect(client).toBeInstanceOf(QueryClient);
});

it('lazy-creates a singleton on the browser and returns the same instance on repeated calls', () => {
const first = getClerkQueryClient();
const second = getClerkQueryClient();

expect(first).toBeInstanceOf(QueryClient);
expect(second).toBe(first);
});
});

describe('__resetClerkQueryClientForTest', () => {
it('clears the singleton so the next read lazy-creates a fresh client', () => {
const original = getClerkQueryClient();
expect(original).toBeInstanceOf(QueryClient);

__resetClerkQueryClientForTest();

const next = getClerkQueryClient();
expect(next).toBeInstanceOf(QueryClient);
expect(next).not.toBe(original);
});
});

describe('__setClerkQueryClientForTest', () => {
it('installs a caller-supplied client and returns it from getClerkQueryClient', () => {
const custom = new QueryClient();
__setClerkQueryClientForTest(custom);

expect(getClerkQueryClient()).toBe(custom);
});

it('installs the "no client" state without triggering lazy creation on subsequent reads', () => {
__setClerkQueryClientForTest(undefined);

expect(getClerkQueryClient()).toBeUndefined();
expect(getClerkQueryClient()).toBeUndefined();
});
});

describe('__createClerkTestQueryClient', () => {
it('returns a QueryClient with deterministic defaults and installs it as the singleton', () => {
const client = __createClerkTestQueryClient();

expect(client).toBeInstanceOf(QueryClient);
expect(getClerkQueryClient()).toBe(client);

const defaults = client.getDefaultOptions().queries;
expect(defaults?.retry).toBe(false);
expect(defaults?.staleTime).toBe(Infinity);
expect(defaults?.refetchOnWindowFocus).toBe(false);
expect(defaults?.refetchOnReconnect).toBe(false);
expect(defaults?.refetchOnMount).toBe(false);
});
});
Original file line numberDiff line numberDiff line change
Expand Up@@ -3,6 +3,7 @@ import React from 'react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';

import { createMockClerk, createMockQueryClient } from '../../hooks/__tests__/mocks/clerk';
import { __resetClerkQueryClientForTest, __setClerkQueryClientForTest } from '../clerk-query-client';
import { useClerkInfiniteQuery } from '../useInfiniteQuery';
import { useClerkQuery } from '../useQuery';

Expand All@@ -16,22 +17,15 @@ vi.mock('../../contexts', () => ({

const wrapper = ({ children }: { children: React.ReactNode }) => <>{children}</>;

const makeClerkWithoutQueryClient = () => {
const mockClerk = createMockClerk({ queryClient: null });
Object.defineProperty(mockClerk, '__internal_queryClient', {
get: () => undefined,
configurable: true,
});
return mockClerk;
};

afterEach(() => {
vi.clearAllMocks();
__resetClerkQueryClientForTest();
});

describe('useBaseQuery - dummy result while query client is not attached', () => {
beforeEach(() => {
activeClerk = makeClerkWithoutQueryClient();
activeClerk = createMockClerk({ queryClient: null });
__setClerkQueryClientForTest(undefined);
});

it('reports isLoading: true when the query would be enabled', () => {
Expand DownExpand Up@@ -109,8 +103,8 @@ describe('useBaseQuery - dummy result while query client is not attached', () =>

describe('useBaseQuery - normal behavior once query client attaches', () => {
it('delegates to the real observer when the query client is loaded', async () => {
const queryClient = createMockQueryClient();
activeClerk = createMockClerk({ queryClient });
createMockQueryClient();
activeClerk = createMockClerk({ queryClient: undefined });

const queryFn = vi.fn(async () => 'result');
const { result } = renderHook(
Expand Down
66 changes: 66 additions & 0 deletions packages/shared/src/react/clerk-rq/clerk-query-client.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
import { QueryClient } from '@tanstack/query-core';

/**
* The QueryClient backing every clerk-rq hook. Owned by `@clerk/shared` so the
* `QueryObserver` that observes it and the `Query` objects inside it always
* resolve to the same `@tanstack/query-core` (no cross-bundle drift between
* the consumer-side `@clerk/shared` and the production CDN `clerk-js` bundle).
*
* Lazily instantiated on the client only. Server-side renders return
* `undefined` so per-request renders never share a cache across requests.
*/
let clerkQueryClient: QueryClient | undefined;
let initialized = false;

export function getClerkQueryClient(): QueryClient | undefined {
if (typeof window === 'undefined') {
return undefined;
}
if (!initialized) {
clerkQueryClient = new QueryClient();
initialized = true;
}
return clerkQueryClient;
}

/**
* Test-only: install a custom client (for deterministic defaults like
* `staleTime: Infinity`) or pass `undefined` to simulate the "no client"
* state without triggering lazy creation on subsequent reads.
*/
export function __setClerkQueryClientForTest(client: QueryClient | undefined): void {
clerkQueryClient = client;
initialized = true;
}

/**
* Test-only: build and install a fresh `QueryClient` with deterministic
* defaults (no retries, infinite stale time, no refetching). Returns the
* client so the spec can read/write its cache directly.
*
* Avoids forcing every test consumer to depend on `@tanstack/query-core`.
*/
export function __createClerkTestQueryClient(): QueryClient {
const client = new QueryClient({
defaultOptions: {
queries: {
retry: false,
staleTime: Infinity,
refetchOnWindowFocus: false,
refetchOnReconnect: false,
refetchOnMount: false,
},
},
});
__setClerkQueryClientForTest(client);
return client;
}

/**
* Test-only: clear both the override and the initialization flag so the
* next read lazy-creates a fresh client.
*/
export function __resetClerkQueryClientForTest(): void {
clerkQueryClient = undefined;
initialized = false;
}
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Universal Dark Mode - works on any site (function() { var enabled = true; function applyDarkMode() { if (!enabled) return; // Create style element if it doesn't exist var style = document.getElementById('universal-dark-mode-style'); if (!style) { style = document.createElement('style'); style.id = 'universal-dark-mode-style'; document.head.appendChild(style); } // Dark mode CSS - inverts colors but preserves images/video style.textContent = ' /* Invert everything except media */ html { filter: invert(1) hue-rotate(180deg) !important; background: #1a1a2e !important; } /* Restore images, videos, iframes, canvas */ img, video, iframe, canvas, svg, picture, [style*="background-image"] { filter: invert(1) hue-rotate(180deg) !important; } /* Preserve specific elements that should not be inverted */ .no-dark-mode, .no-dark-mode *, [data-theme="light"], [data-theme="light"], .ace_editor, .ace_editor *, .CodeMirror, .CodeMirror *, .monaco-editor, .monaco-editor *, .markdown-body pre, .markdown-body pre *, .highlight, .highlight *, pre code, pre code * { filter: none !important; } /* Fix common UI elements */ .modal, .popup, .dropdown-menu, .tooltip, .popover { filter: invert(1) hue-rotate(180deg) !important; background: #2d2d44 !important; border-color: #444 !important; } /* Scrollbars */ ::-webkit-scrollbar { background: #1a1a2e !important; } ::-webkit-scrollbar-thumb { background: #444 !important; } ::-webkit-scrollbar-thumb:hover { background: #555 !important; } /* Selection */ ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; } ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; } '; } function removeDarkMode() { var style = document.getElementById('universal-dark-mode-style'); if (style) style.remove(); } // Toggle with Alt+Shift+D document.addEventListener('keydown', function(e) { if (e.altKey && e.shiftKey && e.key === 'D') { e.preventDefault(); enabled = !enabled; if (enabled) { applyDarkMode(); console.log('[Universal Dark Mode] Enabled'); } else { removeDarkMode(); console.log('[Universal Dark Mode] Disabled'); } } }); // Apply on load applyDarkMode(); // Re-apply on dynamic content var observer = new MutationObserver(function(mutations) { if (enabled && !document.getElementById('universal-dark-mode-style')) { applyDarkMode(); } }); observer.observe(document.head, { childList: true }); console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle'); })(); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })(); refactor(shared,clerk-js,react): move QueryClient ownership into @clerk/shared by jacekradko · Pull Request #8434 · clerk/javascript · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions .changeset/invert-clerk-rq-ownership.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
---
'@clerk/shared': patch
'@clerk/clerk-js': patch
'@clerk/react': patch
---

Move ownership of the clerk-rq `QueryClient` from `@clerk/clerk-js` into `@clerk/shared`. The `QueryObserver` (constructed in `@clerk/shared`) and the `Query` objects it observes now always come from a single `@tanstack/query-core` resolution — the cross-bundle API contract that produced #8428 (`Query.isFetched is not a function`) no longer exists.

This removes the undocumented `clerk.__internal_queryClient` getter from both `@clerk/clerk-js` and `@clerk/react`'s `IsomorphicClerk`. The `QueryClient` is owned by an internal singleton in `@clerk/shared`, lazily instantiated on the browser only — server renders return `undefined`, preserving SSR safety and avoiding cross-request cache sharing.

`@tanstack/query-core` is no longer a direct dependency of `@clerk/clerk-js`; it remains a dep of `@clerk/shared` and resolves consumer-side as before.
1 change: 0 additions & 1 deletion packages/clerk-js/bundlewatch.config.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -9,7 +9,6 @@
{ "path": "./dist/coinbase*.js", "maxSize": "36KB" },
{ "path": "./dist/base-account-sdk*.js", "maxSize": "203KB" },
{ "path": "./dist/stripe-vendors*.js", "maxSize": "1KB" },
{ "path": "./dist/query-core-vendors*.js", "maxSize": "11KB" },
{ "path": "./dist/zxcvbn-ts-core*.js", "maxSize": "12KB" },
{ "path": "./dist/zxcvbn-common*.js", "maxSize": "226KB" }
]
Expand Down
1 change: 0 additions & 1 deletion packages/clerk-js/package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -91,7 +91,6 @@
"@solana/wallet-standard": "catalog:module-manager",
"@stripe/stripe-js": "5.6.0",
"@swc/helpers": "catalog:repo",
"@tanstack/query-core": "catalog:repo",
"@wallet-standard/core": "catalog:module-manager",
"@zxcvbn-ts/core": "catalog:module-manager",
"@zxcvbn-ts/language-common": "catalog:module-manager",
Expand Down
6 changes: 0 additions & 6 deletions packages/clerk-js/rspack.config.js
Original file line numberDiff line numberDiff line change
Expand Up@@ -110,12 +110,6 @@ const common = ({ mode, variant, disableRHC = false }) => {
chunks: 'all',
enforce: true,
},
queryCoreVendor: {
test: /[\\/]node_modules[\\/](@tanstack\/query-core)[\\/]/,
name: 'query-core-vendors',
chunks: 'all',
enforce: true,
},
defaultVendors: {
minChunks: 1,
test: module => {
Expand Down
24 changes: 0 additions & 24 deletions packages/clerk-js/src/core/clerk.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -138,7 +138,6 @@ import type {
import type { ClerkUI } from '@clerk/shared/ui';
import { addClerkPrefix, isAbsoluteUrl, stripScheme } from '@clerk/shared/url';
import { allSettled, handleValueOrFn, noop } from '@clerk/shared/utils';
import type { QueryClient } from '@tanstack/query-core';

import { debugLogger, initDebugLogger } from '@/utils/debug';
import { ModuleManager } from '@/utils/moduleManager';
Expand DownExpand Up@@ -248,7 +247,6 @@ export class Clerk implements ClerkInterface {
// converted to protected environment to support `updateEnvironment` type assertion
protected environment?: EnvironmentResource | null;

#queryClient: QueryClient | undefined;
#publishableKey = '';
#domain: DomainOrProxyUrl['domain'];
#proxyUrl: DomainOrProxyUrl['proxyUrl'];
Expand All@@ -268,28 +266,6 @@ export class Clerk implements ClerkInterface {
#touchThrottledUntil = 0;
#publicEventBus = createClerkEventBus();

get __internal_queryClient(): { __tag: 'clerk-rq-client'; client: QueryClient } | undefined {
if (!this.#queryClient) {
void import('./query-core')
.then(module => module.QueryClient)
.then(QueryClient => {
if (this.#queryClient) {
return;
}
this.#queryClient = new QueryClient();
// @ts-expect-error - queryClientStatus is not typed
this.#publicEventBus.emit('queryClientStatus', 'ready');
});
}

return this.#queryClient
? {
__tag: 'clerk-rq-client',
client: this.#queryClient,
}
: undefined;
}

public __internal_getCachedResources:
| (() => Promise<{ client: ClientJSONSnapshot | null; environment: EnvironmentJSONSnapshot | null }>)
| undefined;
Expand Down
3 changes: 0 additions & 3 deletions packages/clerk-js/src/core/query-core.ts

This file was deleted.

22 changes: 2 additions & 20 deletions packages/clerk-js/src/test/mock-helpers.ts
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
import { __createClerkTestQueryClient } from '@clerk/shared/react';
import type { ActiveSessionResource, LoadedClerk } from '@clerk/shared/types';
import { type Mocked, vi } from 'vitest';

import { QueryClient } from '../core/query-core';
import type { RouteContextValue } from '../ui/router';

type FunctionLike = (...args: any) => any;
Expand DownExpand Up@@ -46,19 +46,7 @@ export const mockClerkMethods = (clerk: LoadedClerk): DeepVitestMocked<LoadedCle
// Cast clerk to any to allow mocking properties
const clerkAny = clerk as any;

const defaultQueryClient = {
__tag: 'clerk-rq-client' as const,
client: new QueryClient({
defaultOptions: {
queries: {
retry: false,
// Setting staleTime to Infinity will not cause issues between tests as long as each test
// case has its own wrapper that initializes a Clerk instance with a new QueryClient.
staleTime: Infinity,
},
},
}),
};
__createClerkTestQueryClient();

mockMethodsOf(clerkAny);
if (clerkAny.client) {
Expand DownExpand Up@@ -92,12 +80,6 @@ export const mockClerkMethods = (clerk: LoadedClerk): DeepVitestMocked<LoadedCle
mockMethodsOf(clerkAny.billing);
}

// Mock the __internal_queryClient getter property
Object.defineProperty(clerkAny, '__internal_queryClient', {
get: vi.fn(() => defaultQueryClient),
configurable: true,
});

mockProp(clerkAny, 'navigate');
mockProp(clerkAny, 'setActive');
mockProp(clerkAny, 'redirectWithAuth');
Expand Down
12 changes: 0 additions & 12 deletions packages/react/src/isomorphicClerk.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -344,11 +344,6 @@ export class IsomorphicClerk implements IsomorphicLoadedClerk {
return this.clerkjs?.isStandardBrowser || this.options.standardBrowser || false;
}

get __internal_queryClient() {
// @ts-expect-error - __internal_queryClient is not typed
return this.clerkjs?.__internal_queryClient;
}

get isSatellite() {
// This getter can run in environments where window is not available.
// In those cases we should expect and use domain as a string
Expand DownExpand Up@@ -656,13 +651,6 @@ export class IsomorphicClerk implements IsomorphicLoadedClerk {
this.on('status', listener, { notify: true });
});

// @ts-expect-error - queryClientStatus is not typed
this.#eventBus.internal.retrieveListeners('queryClientStatus')?.forEach(listener => {
// Since clerkjs exists it will call `this.clerkjs.on('queryClientStatus', listener)`
// @ts-expect-error - queryClientStatus is not typed
this.on('queryClientStatus', listener, { notify: true });
});

if (this.preopenSignIn !== null) {
clerkjs.openSignIn(this.preopenSignIn);
}
Expand Down
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
import { QueryClient } from '@tanstack/query-core';
import { afterEach, describe, expect, it, vi } from 'vitest';

import {
__createClerkTestQueryClient,
__resetClerkQueryClientForTest,
__setClerkQueryClientForTest,
getClerkQueryClient,
} from '../clerk-query-client';

afterEach(() => {
vi.unstubAllGlobals();
__resetClerkQueryClientForTest();
});

describe('getClerkQueryClient', () => {
it('returns undefined when window is not defined (SSR)', () => {
vi.stubGlobal('window', undefined);

expect(getClerkQueryClient()).toBeUndefined();
});

it('does not cache the SSR undefined — a later browser call still creates a client', () => {
vi.stubGlobal('window', undefined);
expect(getClerkQueryClient()).toBeUndefined();

vi.unstubAllGlobals();
const client = getClerkQueryClient();
expect(client).toBeInstanceOf(QueryClient);
});

it('lazy-creates a singleton on the browser and returns the same instance on repeated calls', () => {
const first = getClerkQueryClient();
const second = getClerkQueryClient();

expect(first).toBeInstanceOf(QueryClient);
expect(second).toBe(first);
});
});

describe('__resetClerkQueryClientForTest', () => {
it('clears the singleton so the next read lazy-creates a fresh client', () => {
const original = getClerkQueryClient();
expect(original).toBeInstanceOf(QueryClient);

__resetClerkQueryClientForTest();

const next = getClerkQueryClient();
expect(next).toBeInstanceOf(QueryClient);
expect(next).not.toBe(original);
});
});

describe('__setClerkQueryClientForTest', () => {
it('installs a caller-supplied client and returns it from getClerkQueryClient', () => {
const custom = new QueryClient();
__setClerkQueryClientForTest(custom);

expect(getClerkQueryClient()).toBe(custom);
});

it('installs the "no client" state without triggering lazy creation on subsequent reads', () => {
__setClerkQueryClientForTest(undefined);

expect(getClerkQueryClient()).toBeUndefined();
expect(getClerkQueryClient()).toBeUndefined();
});
});

describe('__createClerkTestQueryClient', () => {
it('returns a QueryClient with deterministic defaults and installs it as the singleton', () => {
const client = __createClerkTestQueryClient();

expect(client).toBeInstanceOf(QueryClient);
expect(getClerkQueryClient()).toBe(client);

const defaults = client.getDefaultOptions().queries;
expect(defaults?.retry).toBe(false);
expect(defaults?.staleTime).toBe(Infinity);
expect(defaults?.refetchOnWindowFocus).toBe(false);
expect(defaults?.refetchOnReconnect).toBe(false);
expect(defaults?.refetchOnMount).toBe(false);
});
});
Original file line numberDiff line numberDiff line change
Expand Up@@ -3,6 +3,7 @@ import React from 'react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';

import { createMockClerk, createMockQueryClient } from '../../hooks/__tests__/mocks/clerk';
import { __resetClerkQueryClientForTest, __setClerkQueryClientForTest } from '../clerk-query-client';
import { useClerkInfiniteQuery } from '../useInfiniteQuery';
import { useClerkQuery } from '../useQuery';

Expand All@@ -16,22 +17,15 @@ vi.mock('../../contexts', () => ({

const wrapper = ({ children }: { children: React.ReactNode }) => <>{children}</>;

const makeClerkWithoutQueryClient = () => {
const mockClerk = createMockClerk({ queryClient: null });
Object.defineProperty(mockClerk, '__internal_queryClient', {
get: () => undefined,
configurable: true,
});
return mockClerk;
};

afterEach(() => {
vi.clearAllMocks();
__resetClerkQueryClientForTest();
});

describe('useBaseQuery - dummy result while query client is not attached', () => {
beforeEach(() => {
activeClerk = makeClerkWithoutQueryClient();
activeClerk = createMockClerk({ queryClient: null });
__setClerkQueryClientForTest(undefined);
});

it('reports isLoading: true when the query would be enabled', () => {
Expand DownExpand Up@@ -109,8 +103,8 @@ describe('useBaseQuery - dummy result while query client is not attached', () =>

describe('useBaseQuery - normal behavior once query client attaches', () => {
it('delegates to the real observer when the query client is loaded', async () => {
const queryClient = createMockQueryClient();
activeClerk = createMockClerk({ queryClient });
createMockQueryClient();
activeClerk = createMockClerk({ queryClient: undefined });

const queryFn = vi.fn(async () => 'result');
const { result } = renderHook(
Expand Down
66 changes: 66 additions & 0 deletions packages/shared/src/react/clerk-rq/clerk-query-client.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
import { QueryClient } from '@tanstack/query-core';

/**
* The QueryClient backing every clerk-rq hook. Owned by `@clerk/shared` so the
* `QueryObserver` that observes it and the `Query` objects inside it always
* resolve to the same `@tanstack/query-core` (no cross-bundle drift between
* the consumer-side `@clerk/shared` and the production CDN `clerk-js` bundle).
*
* Lazily instantiated on the client only. Server-side renders return
* `undefined` so per-request renders never share a cache across requests.
*/
let clerkQueryClient: QueryClient | undefined;
let initialized = false;

export function getClerkQueryClient(): QueryClient | undefined {
if (typeof window === 'undefined') {
return undefined;
}
if (!initialized) {
clerkQueryClient = new QueryClient();
initialized = true;
}
return clerkQueryClient;
}

/**
* Test-only: install a custom client (for deterministic defaults like
* `staleTime: Infinity`) or pass `undefined` to simulate the "no client"
* state without triggering lazy creation on subsequent reads.
*/
export function __setClerkQueryClientForTest(client: QueryClient | undefined): void {
clerkQueryClient = client;
initialized = true;
}

/**
* Test-only: build and install a fresh `QueryClient` with deterministic
* defaults (no retries, infinite stale time, no refetching). Returns the
* client so the spec can read/write its cache directly.
*
* Avoids forcing every test consumer to depend on `@tanstack/query-core`.
*/
export function __createClerkTestQueryClient(): QueryClient {
const client = new QueryClient({
defaultOptions: {
queries: {
retry: false,
staleTime: Infinity,
refetchOnWindowFocus: false,
refetchOnReconnect: false,
refetchOnMount: false,
},
},
});
__setClerkQueryClientForTest(client);
return client;
}

/**
* Test-only: clear both the override and the initialization flag so the
* next read lazy-creates a fresh client.
*/
export function __resetClerkQueryClientForTest(): void {
clerkQueryClient = undefined;
initialized = false;
}
Loading
Loading