Skip to content

Commit ccc2bc6

Browse files
authored
fix(nextjs): settle onBeforeSetActive when cache invalidation fails (#10852)
1 parent a7870db commit ccc2bc6

3 files changed

Lines changed: 122 additions & 16 deletions

File tree

‎.changeset/quiet-pans-settle.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'@clerk/nextjs': patch
3+
---
4+
5+
Fix `setActive()` and `signOut()` hanging forever in App Router apps when the cache invalidation server action fails, for example after a redeploy or on a network error.

‎packages/nextjs/src/app-router/client/ClerkProvider.tsx‎

Lines changed: 14 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ const NextClientClerkProvider = <TUi extends Ui = Ui>(props: NextClerkProviderPr
2323
const replace = useAwaitableReplace();
2424

2525
useSafeLayoutEffect(() => {
26-
window.__internal_onBeforeSetActive = intent => {
26+
window.__internal_onBeforeSetActive = async intent => {
2727
/**
2828
* We need to invalidate the cache in case the user is navigating to a page that
2929
* was previously cached using the auth state that was active at the time.
@@ -43,22 +43,20 @@ const NextClientClerkProvider = <TUi extends Ui = Ui>(props: NextClerkProviderPr
4343
* For more information on cache invalidation, see:
4444
* https://nextjs.org/docs/app/building-your-application/caching#invalidation-1
4545
*/
46-
return new Promise(resolve => {
47-
const nextVersion = window?.next?.version || '';
46+
const nextVersion = window?.next?.version || '';
4847

49-
// On Next.js 15+ calling a server action that returns a 404 error when deployed on Vercel is prohibited, failing with 405 status code.
50-
// When a user transitions from "signed in" to "signed out", we clear the `__session` cookie, then we call `__internal_onBeforeSetActive`.
51-
// If we were to call `invalidateCacheAction` while the user is already signed out (deleted cookie), any page protected by `auth.protect()`
52-
// will result to the server action returning a 404 error (this happens because server actions inherit the protection rules of the page they are called from).
53-
// SOLUTION:
54-
// To mitigate this, since the router cache on version 15+ is much less aggressive, we can treat this as a noop and simply resolve the promise.
55-
// Once `setActive` performs the navigation, `__internal_onAfterSetActive` will kick in and perform a router.refresh ensuring shared layouts will also update with the correct authentication context.
56-
if ((nextVersion.startsWith('15') || nextVersion.startsWith('16')) && intent === 'sign-out') {
57-
resolve(); // noop
58-
} else {
59-
void invalidateCacheAction().then(() => resolve());
60-
}
61-
});
48+
// On Next.js 15+ calling a server action that returns a 404 error when deployed on Vercel is prohibited, failing with 405 status code.
49+
// When a user transitions from "signed in" to "signed out", we clear the `__session` cookie, then we call `__internal_onBeforeSetActive`.
50+
// If we were to call `invalidateCacheAction` while the user is already signed out (deleted cookie), any page protected by `auth.protect()`
51+
// will result to the server action returning a 404 error (this happens because server actions inherit the protection rules of the page they are called from).
52+
// SOLUTION:
53+
// To mitigate this, since the router cache on version 15+ is much less aggressive, we can treat this as a noop and simply resolve the promise.
54+
// Once `setActive` performs the navigation, `__internal_onAfterSetActive` will kick in and perform a router.refresh ensuring shared layouts will also update with the correct authentication context.
55+
if ((nextVersion.startsWith('15') || nextVersion.startsWith('16')) && intent === 'sign-out') {
56+
return;
57+
}
58+
59+
await invalidateCacheAction().catch(() => {});
6260
};
6361

6462
window.__internal_onAfterSetActive = () => {
Lines changed: 103 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,103 @@
1+
import { cleanup, render } from '@testing-library/react';
2+
import React from 'react';
3+
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
4+
5+
const { invalidateCacheAction, refresh } = vi.hoisted(() => ({ invalidateCacheAction: vi.fn(), refresh: vi.fn() }));
6+
7+
vi.mock('next/navigation', () => ({
8+
useRouter: () => ({ refresh, push: vi.fn(), replace: vi.fn() }),
9+
usePathname: () => '/',
10+
}));
11+
12+
vi.mock('@clerk/react/internal', () => ({
13+
InternalClerkProvider: ({ children }: { children: React.ReactNode }) => <>{children}</>,
14+
}));
15+
16+
vi.mock('../../server-actions', () => ({ invalidateCacheAction }));
17+
18+
vi.mock('../ClerkScripts', () => ({ ClerkScripts: () => null }));
19+
20+
vi.mock('../../../utils/router-telemetry', () => ({ RouterTelemetry: () => null }));
21+
22+
vi.mock('../../../utils/feature-flags', () => ({ canUseKeyless: false }));
23+
24+
import { ClientClerkProvider } from '../ClerkProvider';
25+
26+
describe('ClientClerkProvider __internal_onBeforeSetActive', () => {
27+
beforeEach(() => {
28+
invalidateCacheAction.mockReset();
29+
refresh.mockReset();
30+
render(
31+
<ClientClerkProvider publishableKey='pk_test_Y2xlcmsuZXhhbXBsZS5jb20k'>
32+
<div />
33+
</ClientClerkProvider>,
34+
);
35+
});
36+
37+
afterEach(() => {
38+
cleanup();
39+
delete (window as { next?: unknown }).next;
40+
});
41+
42+
it('waits for the cache invalidation before it resolves', async () => {
43+
let finishInvalidation!: () => void;
44+
invalidateCacheAction.mockReturnValue(new Promise<void>(resolve => (finishInvalidation = resolve)));
45+
46+
let settled = false;
47+
const hook = Promise.resolve(window.__internal_onBeforeSetActive()).then(() => (settled = true));
48+
await new Promise(resolve => setTimeout(resolve, 10));
49+
expect(settled).toBe(false);
50+
51+
finishInvalidation();
52+
await hook;
53+
expect(settled).toBe(true);
54+
});
55+
56+
it.each(['15.5.9', '16.2.6'])('skips the cache invalidation on sign-out with Next.js %s', async version => {
57+
(window as { next?: unknown }).next = { version };
58+
59+
await expect(window.__internal_onBeforeSetActive('sign-out')).resolves.toBeUndefined();
60+
expect(invalidateCacheAction).not.toHaveBeenCalled();
61+
});
62+
63+
it('invalidates the cache on Next.js 16 when no intent is passed', async () => {
64+
(window as { next?: unknown }).next = { version: '16.2.6' };
65+
invalidateCacheAction.mockResolvedValue(undefined);
66+
67+
await expect(window.__internal_onBeforeSetActive()).resolves.toBeUndefined();
68+
expect(invalidateCacheAction).toHaveBeenCalledTimes(1);
69+
});
70+
71+
it('does not leave an unhandled rejection when the cache invalidation action rejects', async () => {
72+
const unhandled: unknown[] = [];
73+
const onUnhandled = (reason: unknown) => unhandled.push(reason);
74+
process.on('unhandledRejection', onUnhandled);
75+
invalidateCacheAction.mockRejectedValue(new Error('Server Action was not found on the server'));
76+
77+
await expect(window.__internal_onBeforeSetActive()).resolves.toBeUndefined();
78+
await new Promise(resolve => setTimeout(resolve, 10));
79+
process.off('unhandledRejection', onUnhandled);
80+
81+
expect(unhandled).toEqual([]);
82+
});
83+
84+
it('resolves after the cache is invalidated', async () => {
85+
invalidateCacheAction.mockResolvedValue(undefined);
86+
87+
await expect(window.__internal_onBeforeSetActive()).resolves.toBeUndefined();
88+
expect(invalidateCacheAction).toHaveBeenCalledTimes(1);
89+
expect(refresh).not.toHaveBeenCalled();
90+
});
91+
92+
it('resolves when the cache invalidation action rejects', async () => {
93+
invalidateCacheAction.mockRejectedValue(new Error('Server Action was not found on the server'));
94+
95+
const outcome = await Promise.race([
96+
Promise.resolve(window.__internal_onBeforeSetActive()).then(() => 'settled'),
97+
new Promise(resolve => setTimeout(() => resolve('hung'), 100)),
98+
]);
99+
100+
expect(outcome).toBe('settled');
101+
expect(refresh).not.toHaveBeenCalled();
102+
});
103+
});

0 commit comments

Comments
 (0)