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
5 changes: 5 additions & 0 deletions .changeset/smart-socks-refuse.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@clerk/clerk-js': patch
---

Refactor after-auth flows to keep navigation internally
2 changes: 1 addition & 1 deletion packages/clerk-js/bundlewatch.config.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
{ "path": "./dist/organizationprofile*.js", "maxSize": "10KB" },
{ "path": "./dist/organizationswitcher*.js", "maxSize": "5KB" },
{ "path": "./dist/organizationlist*.js", "maxSize": "5.5KB" },
{ "path": "./dist/signin*.js", "maxSize": "14KB" },
{ "path": "./dist/signin*.js", "maxSize": "18KB" },
{ "path": "./dist/signup*.js", "maxSize": "8.86KB" },
{ "path": "./dist/userbutton*.js", "maxSize": "5KB" },
{ "path": "./dist/userprofile*.js", "maxSize": "16KB" },
Expand Down
4 changes: 2 additions & 2 deletions packages/clerk-js/src/core/__tests__/clerk.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2365,7 +2365,7 @@ describe('Clerk singleton', () => {
await sut.load(mockedLoadOptions);

await sut.setActive({ session: mockResource as any as PendingSessionResource });
await sut.__experimental_navigateToTask();
await sut.__internal_navigateToTaskIfAvailable();

expect(mockNavigate.mock.calls[0][0]).toBe('/sign-in#/tasks/add-organization');
});
Expand Down Expand Up @@ -2409,7 +2409,7 @@ describe('Clerk singleton', () => {
await sut.setActive({ session: mockSession as any as ActiveSessionResource });

const redirectUrlComplete = '/welcome-to-app';
await sut.__experimental_navigateToTask({ redirectUrlComplete });
await sut.__internal_navigateToTaskIfAvailable({ redirectUrlComplete });

console.log(mockNavigate.mock.calls);

Expand Down
30 changes: 3 additions & 27 deletions packages/clerk-js/src/core/clerk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1317,9 +1317,8 @@ export class Clerk implements ClerkInterface {
eventBus.emit(events.TokenUpdate, { token: null });
}

// Only triggers navigation for internal AIO components routing or multi-session switch
const isSwitchingSessions = this.session?.id != session.id;
const shouldNavigateOnSetActive = this.#componentNavigationContext || isSwitchingSessions;
// Only triggers navigation for internal AIO components routing
const shouldNavigateOnSetActive = this.#componentNavigationContext;
if (newSession?.currentTask && shouldNavigateOnSetActive) {
await navigateToTask(session.currentTask.key, {
options: this.#options,
Expand All @@ -1333,16 +1332,7 @@ export class Clerk implements ClerkInterface {
this.#emit();
};

public __experimental_navigateToTask = async ({ redirectUrlComplete }: NextTaskParams = {}): Promise<void> => {
/**
* Invalidate previously cached pages with auth state before navigating
*/
const onBeforeSetActive: SetActiveHook =
typeof window !== 'undefined' && typeof window.__unstable__onBeforeSetActive === 'function'
? window.__unstable__onBeforeSetActive
: noop;
await onBeforeSetActive();

public __internal_navigateToTaskIfAvailable = async ({ redirectUrlComplete }: NextTaskParams = {}): Promise<void> => {
const session = this.session;
if (!session || !this.environment) {
return;
Expand All @@ -1368,20 +1358,6 @@ export class Clerk implements ClerkInterface {
if (tracker.isUnloading()) {
return;
}

this.#setAccessors(session);
this.#emit();

/**
* Invoke the Next.js middleware to synchronize server and client state after resolving a session task.
* This ensures that any server-side logic depending on the session status (like middleware-based
* redirects or protected routes) correctly reflects the updated client authentication state.
*/
const onAfterSetActive: SetActiveHook =
typeof window !== 'undefined' && typeof window.__unstable__onAfterSetActive === 'function'
? window.__unstable__onAfterSetActive
: noop;
await onAfterSetActive();
Comment on lines -1372 to -1384

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

This is not needed anymore, as we already invalidate the server-side state on setActive and __internal_navigateToTaskIfAvailable would be called by AIOs right after.

};

public addListener = (listener: ListenerCallback): UnsubscribeCallback => {
Expand Down
6 changes: 4 additions & 2 deletions packages/clerk-js/src/ui/components/SessionTasks/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ const SessionTasksStart = () => {
useEffect(() => {
// Simulates additional latency to avoid a abrupt UI transition when navigating to the next task
const timeoutId = setTimeout(() => {
void clerk.__experimental_navigateToTask({ redirectUrlComplete });
void clerk.__internal_navigateToTaskIfAvailable({ redirectUrlComplete });
}, 500);
return () => clearTimeout(timeoutId);
}, [navigate, clerk, redirectUrlComplete]);
Expand Down Expand Up @@ -84,7 +84,9 @@ export const SessionTask = withCardStateProvider(() => {

const nextTask = useCallback(() => {
setIsNavigatingToTask(true);
return clerk.__experimental_navigateToTask({ redirectUrlComplete }).finally(() => setIsNavigatingToTask(false));
return clerk
.__internal_navigateToTaskIfAvailable({ redirectUrlComplete })
.finally(() => setIsNavigatingToTask(false));
}, [clerk, redirectUrlComplete]);

if (!clerk.session?.currentTask) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ type UseMultisessionActionsParams = {
} & Pick<UserButtonProps, 'userProfileMode' | 'appearance' | 'userProfileProps'>;

export const useMultisessionActions = (opts: UseMultisessionActionsParams) => {
const { setActive, signOut, openUserProfile } = useClerk();
const { setActive, signOut, openUserProfile, __internal_navigateToTaskIfAvailable } = useClerk();
const card = useCardState();
const { signedInSessions, otherSessions } = useMultipleSessions({ user: opts.user });
const { navigate } = useRouter();
Expand Down Expand Up @@ -69,10 +69,13 @@ export const useMultisessionActions = (opts: UseMultisessionActionsParams) => {

const handleSessionClicked = (session: SignedInSessionResource) => async () => {
card.setLoading();
return setActive({ session, redirectUrl: opts.afterSwitchSessionUrl }).finally(() => {
card.setIdle();
opts.actionCompleteCallback?.();
});

return setActive({ session, redirectUrl: opts.afterSwitchSessionUrl })
.then(() => __internal_navigateToTaskIfAvailable())
.finally(() => {
card.setIdle();
opts.actionCompleteCallback?.();
});
};

const handleAddAccountClicked = () => {
Expand Down
4 changes: 2 additions & 2 deletions packages/react/src/isomorphicClerk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -731,9 +731,9 @@ export class IsomorphicClerk implements IsomorphicLoadedClerk {
}
};

__experimental_navigateToTask = async (params?: NextTaskParams): Promise<void> => {
__internal_navigateToTaskIfAvailable = async (params?: NextTaskParams): Promise<void> => {
if (this.clerkjs) {
return this.clerkjs.__experimental_navigateToTask(params);
return this.clerkjs.__internal_navigateToTaskIfAvailable(params);
} else {
return Promise.reject();
}
Expand Down
4 changes: 2 additions & 2 deletions packages/types/src/clerk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -818,9 +818,9 @@
* Navigates to the next task or redirects to completion URL.
* If the current session has pending tasks, it navigates to the next task.
* If all tasks are complete, it navigates to the provided completion URL or defaults to the origin redirect URL (either from sign-in or sign-up).
* @experimental
* @internal
*/
__experimental_navigateToTask: (params?: NextTaskParams) => Promise<void>;
__internal_navigateToTaskIfAvailable: (params?: NextTaskParams) => Promise<void>;

/**
* This is an optional function.
Expand Down Expand Up @@ -1110,7 +1110,7 @@
*/
windowNavigate: (to: URL | string) => void;
},
) => Promise<unknown> | unknown;

Check warning on line 1113 in packages/types/src/clerk.ts

View workflow job for this annotation

GitHub Actions / Static analysis

'unknown' overrides all other types in this union type

export type WithoutRouting<T> = Omit<T, 'path' | 'routing'>;

Expand Down
Loading