-
Notifications
You must be signed in to change notification settings - Fork 467
fix(nextjs): defer the post-setActive refresh until router transitions settle #9406
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
manovotny
wants to merge
3
commits into
main
Choose a base branch
from
manovotny/github-issue-9405-2acfc2
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| --- | ||
| '@clerk/nextjs': patch | ||
| --- | ||
|
|
||
| Fix the App Router hanging on the intermediate route after Clerk's post-authentication navigation lands on a page whose Server Component calls `redirect()`. `ClerkProvider` now waits for in-flight route transitions to settle before dispatching its post-`setActive` `router.refresh()`, so the refresh is no longer lost inside Next.js' router action queue while the server redirect is being followed. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
175 changes: 175 additions & 0 deletions
175
packages/nextjs/src/app-router/client/__tests__/useDeferredRefresh.test.tsx
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,175 @@ | ||
| import { act, cleanup, render, waitFor } from '@testing-library/react'; | ||
| import React, { useTransition } from 'react'; | ||
| import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; | ||
|
|
||
| import { useDeferredRefresh } from '../useDeferredRefresh'; | ||
|
|
||
| const mockRefresh = vi.fn(); | ||
|
|
||
| vi.mock('next/navigation', () => ({ | ||
| useRouter: () => ({ refresh: mockRefresh }), | ||
| })); | ||
|
|
||
| let currentRefresh: (() => void) | undefined; | ||
| let startHeldTransition: (() => void) | undefined; | ||
| let finishHeldTransition: (() => void) | undefined; | ||
|
|
||
| // Suspends inside a transition until the gate promise resolves, keeping | ||
| // React's transition lanes pending (the state the deferral gate protects) | ||
| const gate: { promise: Promise<void> | null; done: boolean } = { promise: null, done: false }; | ||
|
|
||
| const Suspender = () => { | ||
| if (!gate.done) { | ||
| // eslint-disable-next-line @typescript-eslint/only-throw-error | ||
| throw gate.promise; | ||
| } | ||
| return null; | ||
| }; | ||
|
|
||
| const Harness = () => { | ||
| currentRefresh = useDeferredRefresh(); | ||
| const [suspended, setSuspended] = React.useState(false); | ||
| const [, startTransition] = useTransition(); | ||
| startHeldTransition = () => { | ||
| gate.done = false; | ||
| let resolveGate!: () => void; | ||
| gate.promise = new Promise<void>(res => { | ||
| resolveGate = res; | ||
| }); | ||
| finishHeldTransition = () => { | ||
| gate.done = true; | ||
| resolveGate(); | ||
| }; | ||
| startTransition(() => setSuspended(true)); | ||
| }; | ||
| return <React.Suspense fallback={null}>{suspended ? <Suspender /> : null}</React.Suspense>; | ||
| }; | ||
|
|
||
| const refresh = () => { | ||
| if (!currentRefresh) { | ||
| throw new Error('refresh function is not initialized'); | ||
| } | ||
| currentRefresh(); | ||
| }; | ||
|
|
||
| describe('useDeferredRefresh', () => { | ||
| beforeEach(() => { | ||
| currentRefresh = undefined; | ||
| window.__clerk_internal_refresh = undefined; | ||
| vi.clearAllMocks(); | ||
| }); | ||
|
|
||
| afterEach(() => { | ||
| cleanup(); | ||
| }); | ||
|
|
||
| it('dispatches router.refresh once transitions settle', async () => { | ||
| render(<Harness />); | ||
|
|
||
| act(() => { | ||
| refresh(); | ||
| }); | ||
|
|
||
| await waitFor(() => { | ||
| expect(mockRefresh).toHaveBeenCalledTimes(1); | ||
| }); | ||
| }); | ||
|
|
||
| it('does not dispatch router.refresh while another transition is pending', async () => { | ||
| render(<Harness />); | ||
|
|
||
| act(() => { | ||
| startHeldTransition!(); | ||
| }); | ||
|
|
||
| act(() => { | ||
| refresh(); | ||
| }); | ||
|
|
||
| // Let effects and microtasks run; the refresh must stay parked while the | ||
| // held transition keeps React's transition lanes pending | ||
| await act(async () => { | ||
| await new Promise(res => setTimeout(res, 20)); | ||
| }); | ||
| expect(mockRefresh).not.toHaveBeenCalled(); | ||
| expect(window.__clerk_internal_refresh?.pending).toBe(true); | ||
|
|
||
| act(() => { | ||
| finishHeldTransition!(); | ||
| }); | ||
|
|
||
| await waitFor(() => { | ||
| expect(mockRefresh).toHaveBeenCalledTimes(1); | ||
| }); | ||
| expect(window.__clerk_internal_refresh?.pending).toBe(false); | ||
| }); | ||
|
|
||
| it('coalesces concurrent requests into a single router.refresh', async () => { | ||
| render(<Harness />); | ||
|
|
||
| act(() => { | ||
| refresh(); | ||
| refresh(); | ||
| }); | ||
|
|
||
| await waitFor(() => { | ||
| expect(mockRefresh).toHaveBeenCalledTimes(1); | ||
| }); | ||
| }); | ||
|
|
||
| it('does not call router.refresh when nothing was requested', async () => { | ||
| render(<Harness />); | ||
|
|
||
| // Give the isPending effect a chance to run on mount | ||
| await act(async () => { | ||
| await Promise.resolve(); | ||
| }); | ||
|
|
||
| expect(mockRefresh).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it('dispatches a refresh left pending by a previous instance on mount', async () => { | ||
| window.__clerk_internal_refresh = { pending: true }; | ||
|
|
||
| render(<Harness />); | ||
|
|
||
| await waitFor(() => { | ||
| expect(mockRefresh).toHaveBeenCalledTimes(1); | ||
| }); | ||
| expect(window.__clerk_internal_refresh?.pending).toBe(false); | ||
| }); | ||
|
|
||
| it('preserves a refresh requested after unmount for the next instance', async () => { | ||
| const { unmount } = render(<Harness />); | ||
| unmount(); | ||
|
|
||
| // Request while no instance is mounted (e.g. ClerkProvider remounting during a navigation) | ||
| refresh(); | ||
| expect(window.__clerk_internal_refresh?.pending).toBe(true); | ||
| expect(mockRefresh).not.toHaveBeenCalled(); | ||
|
|
||
| render(<Harness />); | ||
|
|
||
| await waitFor(() => { | ||
| expect(mockRefresh).toHaveBeenCalledTimes(1); | ||
| }); | ||
| }); | ||
|
|
||
| it('allows a fresh refresh after a previous dispatch', async () => { | ||
| render(<Harness />); | ||
|
|
||
| act(() => { | ||
| refresh(); | ||
| }); | ||
| await waitFor(() => { | ||
| expect(mockRefresh).toHaveBeenCalledTimes(1); | ||
| }); | ||
|
|
||
| act(() => { | ||
| refresh(); | ||
| }); | ||
| await waitFor(() => { | ||
| expect(mockRefresh).toHaveBeenCalledTimes(2); | ||
| }); | ||
| }); | ||
| }); | ||
55 changes: 55 additions & 0 deletions
55
packages/nextjs/src/app-router/client/useDeferredRefresh.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,55 @@ | ||
| 'use client'; | ||
|
|
||
| import { useRouter } from 'next/navigation'; | ||
| import { useCallback, useEffect, useTransition } from 'react'; | ||
|
|
||
| const getClerkRefreshObject = () => { | ||
| window.__clerk_internal_refresh ??= {}; | ||
| return window.__clerk_internal_refresh; | ||
| }; | ||
|
|
||
| /** | ||
| * Returns a fire-and-forget `router.refresh()` that waits for React's in-flight transitions to | ||
| * settle before dispatching the refresh. | ||
| * | ||
| * Dispatching a refresh synchronously after an awaitable navigation resolves can permanently wedge | ||
| * the App Router: when the pushed route's Server Component calls `redirect()`, Next follows it with | ||
| * a second navigation dispatched from its redirect boundary, and a refresh dispatched while that | ||
| * follow-up is in flight can end up appended behind a discarded entry in Next's router action | ||
| * queue (fixed upstream in next@16.3.0, broken in 15.5.1 through 16.2.x). It then never runs, and | ||
| * the unresolved state promise it handed to React suspends the router forever. | ||
| * | ||
| * An empty transition started here cannot settle while another transition (such as the redirect | ||
| * follow-up navigation) is still rendering, so waiting for `isPending` to flip back guarantees the | ||
| * refresh is dispatched onto an idle action queue. | ||
| * | ||
| * The returned function is intentionally not awaitable: a long-running app transition (e.g. a | ||
| * suspended `startTransition` held open by userland code) delays the refresh, and callers such as | ||
| * `setActive` must not block on it. The pending request lives on `window` so it survives | ||
| * `ClerkProvider` remounts; the next mounted instance dispatches it. | ||
| */ | ||
| export const useDeferredRefresh = (): (() => void) => { | ||
| const router = useRouter(); | ||
| const [isPending, startTransition] = useTransition(); | ||
|
|
||
| if (typeof window !== 'undefined') { | ||
| getClerkRefreshObject().fun = () => { | ||
| getClerkRefreshObject().pending = true; | ||
| startTransition(() => { | ||
| // Intentionally empty: used only to observe when in-flight transitions settle. | ||
| }); | ||
| }; | ||
| } | ||
|
|
||
| useEffect(() => { | ||
| if (!isPending && getClerkRefreshObject().pending) { | ||
| getClerkRefreshObject().pending = false; | ||
| router.refresh(); | ||
| } | ||
| // eslint-disable-next-line react-hooks/exhaustive-deps | ||
| }, [isPending]); | ||
|
|
||
| return useCallback(() => { | ||
| getClerkRefreshObject().fun?.(); | ||
| }, []); | ||
| }; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.