Skip to content

feat(clerk-js): Track fapi requests triggered by UI components #5299

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
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
5 changes: 5 additions & 0 deletions .changeset/fresh-pears-brake.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@clerk/clerk-js': minor
---

Track fapi requests triggered by UI components.
4 changes: 4 additions & 0 deletions packages/clerk-js/src/core/clerk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,7 @@ import {
windowNavigate,
} from '../utils';
import { assertNoLegacyProp } from '../utils/assertNoLegacyProp';
import { usageByUIComponents } from '../utils/detect-ui-caller';
import { memoizeListenerCallback } from '../utils/memoizeStateListenerCallback';
import { RedirectUrls } from '../utils/redirectUrls';
import { AuthCookieService } from './auth/AuthCookieService';
Expand Down Expand Up @@ -323,6 +324,9 @@ export class Clerk implements ClerkInterface {
getSessionId: () => {
return this.session?.id;
},
isTriggeredByUI: () => {
return usageByUIComponents.get();
},
proxyUrl: this.proxyUrl,
});
// This line is used for the piggy-backing mechanism
Expand Down
16 changes: 15 additions & 1 deletion packages/clerk-js/src/core/fapiClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ export type FapiRequestInit = RequestInit & {
path?: string;
search?: ConstructorParameters<typeof URLSearchParams>[0];
sessionId?: string;
uiTriggered?: boolean;
rotatingTokenNonce?: string;
pathPrefix?: string;
url?: URL;
Expand Down Expand Up @@ -67,6 +68,7 @@ type FapiClientOptions = {
proxyUrl?: string;
instanceType: InstanceType;
getSessionId: () => string | undefined;
isTriggeredByUI: () => boolean;
isSatellite?: boolean;
};

Expand Down Expand Up @@ -102,7 +104,14 @@ export function createFapiClient(options: FapiClientOptions): FapiClient {
return true;
}

function buildQueryString({ method, path, sessionId, search, rotatingTokenNonce }: FapiRequestInit): string {
function buildQueryString({
method,
path,
sessionId,
search,
rotatingTokenNonce,
uiTriggered,
}: FapiRequestInit): string {
const searchParams = new URLSearchParams(search as any);
// the above will parse {key: ['val1','val2']} as key: 'val1,val2' and we need to recreate the array bellow

Expand Down Expand Up @@ -130,6 +139,10 @@ export function createFapiClient(options: FapiClientOptions): FapiClient {
searchParams.append('_clerk_session_id', sessionId);
}

if (uiTriggered) {
searchParams.append('_clerk_ui_triggered', 'true');
}

// TODO: extract to generic helper
const objParams = [...searchParams.entries()].reduce(
(acc, [k, v]) => {
Expand Down Expand Up @@ -191,6 +204,7 @@ export function createFapiClient(options: FapiClientOptions): FapiClient {
...requestInit,
// TODO: Pass these values to the FAPI client instead of calculating them on the spot
sessionId: options.getSessionId(),
uiTriggered: options.isTriggeredByUI(),
});

// Normalize requestInit.headers
Expand Down
10 changes: 6 additions & 4 deletions packages/clerk-js/src/ui/contexts/CoreClerkContextWrapper.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
import type { Clerk, LoadedClerk, Resources } from '@clerk/types';
import React from 'react';

import { makeUICaller } from '../../utils/detect-ui-caller';
import { assertClerkSingletonExists } from './utils';

type CoreClerkContextWrapperProps = {
Expand Down Expand Up @@ -35,10 +36,11 @@ export function CoreClerkContextWrapper(props: CoreClerkContextWrapperProps): JS
}, []);

const { client, session, user, organization } = state;
const clerkCtx = React.useMemo(() => ({ value: clerk }), []);
const clientCtx = React.useMemo(() => ({ value: client }), [client]);
const sessionCtx = React.useMemo(() => ({ value: session }), [session]);
const userCtx = React.useMemo(() => ({ value: user }), [user]);
const clerkCtx = React.useMemo(() => ({ value: makeUICaller(clerk) }), []);
Copy link
Member

@LauraBeatris LauraBeatris Mar 10, 2025

Choose a reason for hiding this comment

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

💡Not against this approach, mostly curious regarding other options - have you thought of forwarding a property to Clerk if it loads on a React context, and then accessing this on the FAPI client?

Copy link
Member Author

Choose a reason for hiding this comment

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

Can you share more about this. Clerk is already loaded when we mount the providers and the UI components.

Copy link
Member

Choose a reason for hiding this comment

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

Once the CoreClerkContextWrapper loads, it sets a property in Clerk that can be accessed on the fapiClient

if (clerk.hasUIListeners) {
   searchParams.append('_clerk_ui_triggered', 'true');
 }

Copy link
Member Author

Choose a reason for hiding this comment

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

I think this increases the margin of faulty detections by a lot, since all requests triggered outside of a UI component will be flagged incorrectly while a UI component is mounted.

const clientCtx = React.useMemo(() => ({ value: makeUICaller(client) }), [client]);
const sessionCtx = React.useMemo(() => ({ value: makeUICaller(session) }), [session]);
const userCtx = React.useMemo(() => ({ value: makeUICaller(user) }), [user]);

const organizationCtx = React.useMemo(
() => ({
value: { organization: organization },
Expand Down
49 changes: 49 additions & 0 deletions packages/clerk-js/src/utils/detect-ui-caller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
function createStore(initialUsages: number) {
let state = initialUsages;

return {
get: () => state > 0,
increment: () => {
state++;
},
decrease: () => {
state = Math.max(state - 1, 0);
},
};
}

export const usageByUIComponents = createStore(0);

const isThenable = (value: unknown): value is Promise<unknown> => {
Copy link
Member

Choose a reason for hiding this comment

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

Suggested change
const isThenable = (value: unknown): value is Promise<unknown> => {
const isPromise = (value: unknown): value is Promise<unknown> => {

🙃 I'd suggest updating the name to match the type predicate as well, thenable was a bit hard to understand at a first glance

return !!value && typeof (value as any).then === 'function';
};

export const makeUICaller = <T>(resource: T): T => {
Copy link
Member

Choose a reason for hiding this comment

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

Suggested change
export const makeUICaller = <T>(resource: T): T => {
/** @internal **/
export const makeUICaller = <T>(resource: T): T => {

🙃 We could add JSDocs to indicate for external contributors that this is a tooling for internal usage

if (!resource) return null as T;
// return resource
const resourceProxy = new Proxy(resource, {
get(target, prop) {
// @ts-expect-error
const value = target[prop];
if (typeof value === 'function') {
// @ts-expect-error
return function (...args) {
usageByUIComponents.increment();
const result = value.apply(target, args);
if (isThenable(result)) {
return result.finally(() => usageByUIComponents.decrease());
}
usageByUIComponents.decrease();
return result;
};
}

// Allows for nested objects to be proxied (e.g. `client.signIn.create()`)
if (typeof value === 'object') {
return makeUICaller(value);
}
return value;
},
});
return resourceProxy;
};
Loading