Skip to content

test(e2e): confirm Next.js 16.2.0 breaks cache-components tests#8122

Open
jacekradko wants to merge 5 commits intomainfrom
jacek/test-nextjs-16.2.0-cache-components
Open

test(e2e): confirm Next.js 16.2.0 breaks cache-components tests#8122
jacekradko wants to merge 5 commits intomainfrom
jacek/test-nextjs-16.2.0-cache-components

Conversation

@jacekradko
Copy link
Member

@jacekradko jacekradko commented Mar 19, 2026

Summary

This PR is a root cause analysis branch — not a proposed solution. It exists to diagnose and confirm why the cache-components test suite breaks on Next.js 16.2.0. The immediate CI unblock is #8121 (pins to 16.1.6).

Diagnostic Findings

Instrumented the failing test across 3 rounds to trace exactly where the sign-in breaks. Results are 100% consistent across all retries.

Round 1: Basic state capture

  • Clerk JS loads correctly (clerkLoaded: true, version 6.3.1, status ready)
  • Sign-in form renders, single identifier input (no Activity duplication)
  • __client_uat=0 — no authentication occurs
  • window.Clerk.session stays null

Round 2: Form interaction tracing

  • Identifier input: visible, enabled, fills correctly
  • Password field: appears after filling identifier (instant password flow works)
  • Continue button: visible, enabled, click fires
  • Only one API call observed: 200 POST /v1/client/sign_ins
  • No console errors, no network errors

Round 3: Event tracing + API response body

  • Password field receives focus and input events (trusted), DOM value set correctly
  • Field fully visible: opacity: 1, pointerEvents: auto
  • Sign-in API returns status=complete — the sign-in succeeded at the API level
  • But window.Clerk.session remains null, __client_uat=0, URL stays on /sign-in

Confirmed root cause

The sign-in completes successfully at the API level, but setActive() never finishes:

1. Form submits → POST /v1/client/sign_ins → 200, status=complete
2. Clerk calls setActive({ session })
3. setActive() calls await onBeforeSetActive()
4. onBeforeSetActive() calls invalidateCacheAction() (server action)
5. invalidateCacheAction() calls cookies() from next/headers
6. ⛔ Server action HANGS — never resolves
7. setActive() never reaches #updateAccessors()
8. window.Clerk.session stays null → test times out

invalidateCacheAction is a server action that calls cookies() to force router cache invalidation. This works on Next.js ≤16.1.6 but hangs on 16.2.0 with cacheComponents: true.

Verification

To confirm the root cause, the last commit skips invalidateCacheAction on Next.js 16 — and the tests pass. This proves the server action hang is the sole blocker; the actual fix approach needs further discussion.

Context

  • Next.js 16.2.0 was released 2026-03-18 at 17:17 UTC
  • The template uses "next": "^16.0.0-canary.0" with no lockfile — every CI run gets the latest version
  • The sign-out path already skips invalidateCacheAction on Next.js 15+/16+ (line 64 in ClerkProvider.tsx)
  • router.refresh() is already called in onAfterSetActive as a secondary cache invalidation mechanism
  • Existing Next.js issues related to cacheComponents + Activity breakage: vercel/next.js#86577

Test plan

@vercel
Copy link

vercel bot commented Mar 19, 2026

The latest updates on your projects. Learn more about Vercel for GitHub.

1 Skipped Deployment
Project Deployment Actions Updated (UTC)
clerk-js-sandbox Skipped Skipped Mar 19, 2026 4:18pm

Request Review

@changeset-bot
Copy link

changeset-bot bot commented Mar 19, 2026

⚠️ No Changeset found

Latest commit: 879aaad

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

@pkg-pr-new
Copy link

pkg-pr-new bot commented Mar 19, 2026

Open in StackBlitz

@clerk/agent-toolkit

npm i https://pkg.pr.new/@clerk/agent-toolkit@8122

@clerk/astro

npm i https://pkg.pr.new/@clerk/astro@8122

@clerk/backend

npm i https://pkg.pr.new/@clerk/backend@8122

@clerk/chrome-extension

npm i https://pkg.pr.new/@clerk/chrome-extension@8122

@clerk/clerk-js

npm i https://pkg.pr.new/@clerk/clerk-js@8122

@clerk/dev-cli

npm i https://pkg.pr.new/@clerk/dev-cli@8122

@clerk/expo

npm i https://pkg.pr.new/@clerk/expo@8122

@clerk/expo-passkeys

npm i https://pkg.pr.new/@clerk/expo-passkeys@8122

@clerk/express

npm i https://pkg.pr.new/@clerk/express@8122

@clerk/fastify

npm i https://pkg.pr.new/@clerk/fastify@8122

@clerk/hono

npm i https://pkg.pr.new/@clerk/hono@8122

@clerk/localizations

npm i https://pkg.pr.new/@clerk/localizations@8122

@clerk/nextjs

npm i https://pkg.pr.new/@clerk/nextjs@8122

@clerk/nuxt

npm i https://pkg.pr.new/@clerk/nuxt@8122

@clerk/react

npm i https://pkg.pr.new/@clerk/react@8122

@clerk/react-router

npm i https://pkg.pr.new/@clerk/react-router@8122

@clerk/shared

npm i https://pkg.pr.new/@clerk/shared@8122

@clerk/tanstack-react-start

npm i https://pkg.pr.new/@clerk/tanstack-react-start@8122

@clerk/testing

npm i https://pkg.pr.new/@clerk/testing@8122

@clerk/ui

npm i https://pkg.pr.new/@clerk/ui@8122

@clerk/upgrade

npm i https://pkg.pr.new/@clerk/upgrade@8122

@clerk/vue

npm i https://pkg.pr.new/@clerk/vue@8122

commit: 879aaad

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Mar 19, 2026

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Pinned next in integration/templates/next-cache-components/package.json from ^16.0.0-canary.0 to 16.2.0. Rewrote integration/tests/cache-components.test.ts to perform a UI-driven sign-in with Playwright listeners, network/response tracking, DOM instrumentation of the password field, explicit fills and Continue click, extensive diagnostics (URLs, DOM snapshots, Clerk globals, cookies), and a final page.waitForFunction(() => !!window.Clerk?.session, { timeout: 10_000 }). In packages/nextjs/src/app-router/client/ClerkProvider.tsx, Next.js 16 is treated as a cache-invalidation noop (resolves immediately instead of calling invalidateCacheAction()).

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The PR title accurately describes the primary change: pinning Next.js to 16.2.0 to reproduce and confirm test failures with cache-components, which directly matches the main objective.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

📝 Coding Plan
  • Generate coding plan for human review comments

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@integration/tests/cache-components.test.ts`:
- Around line 68-72: The diagnostic try/catch around passwordInput.waitFor(...)
is allowing the test to continue when the password step never appears, masking
upstream render failures as the regression under test; modify the blocks that
call passwordInput.waitFor (the ones around the "Continue" click and the later
similar blocks at lines referenced) to throw or explicitly fail the test when
the wait times out instead of only logging—i.e., replace the silent catch with a
test.fail/assertion (or rethrow) so the test stops immediately if
passwordInput.waitFor(...) does not resolve, preventing later waitForSession
timeouts from being misattributed to the targeted window.Clerk?.session
regression.
- Around line 74-75: Logs currently print sensitive auth data (formHTML and
document.cookie). Update the logging around
page.locator('.cl-signIn-root').innerHTML() and any console.log of
document.cookie (and the other instances at the ranges noted) to redact or mask
sensitive fields before writing to CI: truncate large HTML blobs, remove or
replace cookie values and any user identifiers with placeholders (e.g.,
"<REDACTED_COOKIE>" or "<TRUNCATED_HTML>"), and log only non-sensitive
diagnostics such as presence/length or a hashed/partial fingerprint if needed;
ensure all console.log calls referencing formHTML or document.cookie are changed
accordingly.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository YAML (base), Organization UI (inherited)

Review profile: ASSERTIVE

Plan: Pro

Run ID: b21079f1-d7a2-42f3-a7c8-1c10d70a32a5

📥 Commits

Reviewing files that changed from the base of the PR and between 6b7cf6a and c2f2542.

📒 Files selected for processing (1)
  • integration/tests/cache-components.test.ts

Comment on lines +68 to +72
try {
await passwordInput.waitFor({ state: 'visible', timeout: 5000 });
console.log('[DIAG] password field appeared after filling identifier');
} catch {
console.log('[DIAG] password field did NOT appear after 5s');
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical

Don’t let a pre-sign-in failure masquerade as the target regression.

If the password step never renders, this test still clicks Continue and can later throw waitForSession timed out. That makes an upstream form/rendering failure indistinguishable from the specific post-sign-in window.Clerk?.session regression this PR is supposed to isolate.

Suggested fix
       try {
         await passwordInput.waitFor({ state: 'visible', timeout: 5000 });
         console.log('[DIAG] password field appeared after filling identifier');
       } catch {
         console.log('[DIAG] password field did NOT appear after 5s');
         // Capture what the form looks like
         const formHTML = await page.locator('.cl-signIn-root').innerHTML();
         console.log('[DIAG] sign-in form HTML:', formHTML.substring(0, 3000));
+        throw new Error('Password step never rendered; aborting before session diagnostics');
       }

-      const isPasswordVisible = await passwordInput.isVisible();
-      console.log(`[DIAG] password visible: ${isPasswordVisible}`);
-      if (isPasswordVisible) {
-        await passwordInput.fill(fakeUser.password, { force: true });
-      }
+      await passwordInput.fill(fakeUser.password, { force: true });

Also applies to: 79-99, 119-129

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@integration/tests/cache-components.test.ts` around lines 68 - 72, The
diagnostic try/catch around passwordInput.waitFor(...) is allowing the test to
continue when the password step never appears, masking upstream render failures
as the regression under test; modify the blocks that call passwordInput.waitFor
(the ones around the "Continue" click and the later similar blocks at lines
referenced) to throw or explicitly fail the test when the wait times out instead
of only logging—i.e., replace the silent catch with a test.fail/assertion (or
rethrow) so the test stops immediately if passwordInput.waitFor(...) does not
resolve, preventing later waitForSession timeouts from being misattributed to
the targeted window.Clerk?.session regression.

Comment on lines +74 to +75
const formHTML = await page.locator('.cl-signIn-root').innerHTML();
console.log('[DIAG] sign-in form HTML:', formHTML.substring(0, 3000));
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical

Redact auth diagnostics before writing them to CI logs.

formHTML and document.cookie are being logged verbatim here. Those dumps can expose user identifiers, CSRF/session cookies, or other auth state in persisted Actions logs, which is unsafe to merge.

Suggested fix
-        const formHTML = await page.locator('.cl-signIn-root').innerHTML();
-        console.log('[DIAG] sign-in form HTML:', formHTML.substring(0, 3000));
+        const formShape = await page.locator('.cl-signIn-root').evaluate(root => ({
+          inputNames: Array.from(root.querySelectorAll('input')).map(input => input.getAttribute('name')),
+          buttonLabels: Array.from(root.querySelectorAll('button')).map(
+            button => button.textContent?.trim() ?? '',
+          ),
+        }));
+        console.log('[DIAG] sign-in form shape:', JSON.stringify(formShape));

       const diagAfterWait = await page.evaluate(() => {
         return {
           url: window.location.href,
           clerkLoaded: !!(window as any).Clerk?.loaded,
           hasSession: !!(window as any).Clerk?.session,
           hasUser: !!(window as any).Clerk?.user,
-          cookies: document.cookie,
+          cookieNames: document.cookie
+            .split(';')
+            .map(cookie => cookie.trim().split('=')[0])
+            .filter(Boolean),
           signInCardClass: document.querySelector('.cl-cardBox')?.className ?? 'NOT_FOUND',
         };
       });
@@
         const finalState = await page.evaluate(() => ({
           url: window.location.href,
           hasSession: !!(window as any).Clerk?.session,
-          cookies: document.cookie,
+          cookieNames: document.cookie
+            .split(';')
+            .map(cookie => cookie.trim().split('=')[0])
+            .filter(Boolean),
         }));

Also applies to: 104-117, 123-128

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@integration/tests/cache-components.test.ts` around lines 74 - 75, Logs
currently print sensitive auth data (formHTML and document.cookie). Update the
logging around page.locator('.cl-signIn-root').innerHTML() and any console.log
of document.cookie (and the other instances at the ranges noted) to redact or
mask sensitive fields before writing to CI: truncate large HTML blobs, remove or
replace cookie values and any user identifiers with placeholders (e.g.,
"<REDACTED_COOKIE>" or "<TRUNCATED_HTML>"), and log only non-sensitive
diagnostics such as presence/length or a hashed/partial fingerprint if needed;
ensure all console.log calls referencing formHTML or document.cookie are changed
accordingly.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

♻️ Duplicate comments (2)
integration/tests/cache-components.test.ts (2)

68-75: ⚠️ Potential issue | 🔴 Critical

Fail fast if the password step never renders.

This catch only logs and then continues without a password, so an upstream render/form failure becomes indistinguishable from the missing attempt_first_factor / session progression regression this PR is supposed to isolate.

Suggested fix
       try {
         await passwordInput.waitFor({ state: 'visible', timeout: 5000 });
         console.log('[DIAG] password field appeared after filling identifier');
       } catch {
         console.log('[DIAG] password field did NOT appear after 5s');
+        throw new Error('Password step never rendered; aborting before session diagnostics');
       }
@@
-      const isPasswordVisible = await passwordInput.isVisible();
-      console.log(`[DIAG] password visible: ${isPasswordVisible}`);
-      if (isPasswordVisible) {
-        await passwordInput.fill(fakeUser.password, { force: true });
-      }
+      await passwordInput.fill(fakeUser.password, { force: true });

Also applies to: 109-113

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@integration/tests/cache-components.test.ts` around lines 68 - 75, The catch
block after awaiting passwordInput.waitFor currently only logs diagnostics and
lets the test continue without a password step; change it to fail the test
immediately by throwing an Error (or using test.fail/assert) that includes the
diagnostic details (e.g., the console message and the captured formHTML from
page.locator('.cl-signIn-root')), and apply the same change to the similar block
around the code handling the second occurrence (lines 109-113) so any missing
password-step render causes a hard test failure rather than silently continuing.

73-74: ⚠️ Potential issue | 🔴 Critical

Redact auth diagnostics before writing them to CI logs.

innerHTML(), pwDiag.domValue, and document.cookie can dump identifiers, passwords, and session cookies into persisted job logs. That is unsafe to merge.

Suggested fix
-        const formHTML = await page.locator('.cl-signIn-root').innerHTML();
-        console.log('[DIAG] sign-in form HTML:', formHTML.substring(0, 3000));
+        const formShape = await page.locator('.cl-signIn-root').evaluate(root => ({
+          inputNames: Array.from(root.querySelectorAll('input')).map(input => input.getAttribute('name')),
+          buttonLabels: Array.from(root.querySelectorAll('button')).map(
+            button => button.textContent?.trim() ?? '',
+          ),
+        }));
+        console.log('[DIAG] sign-in form shape:', JSON.stringify(formShape));
@@
-          domValue: pwInput?.value ?? 'NOT_FOUND',
           domValueLength: pwInput?.value?.length ?? 0,
@@
-          cookies: document.cookie,
+          cookieNames: document.cookie
+            .split(';')
+            .map(cookie => cookie.trim().split('=')[0])
+            .filter(Boolean),

Also applies to: 116-135, 180-185

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@integration/tests/cache-components.test.ts` around lines 73 - 74, The test is
logging sensitive auth data (formHTML from
page.locator('.cl-signIn-root').innerHTML(), pwDiag.domValue, and
document.cookie) to CI; replace those direct dumps with safe diagnostics by
removing or redacting sensitive fields before logging (e.g., mask input values
and cookie contents or only log non-sensitive metadata), or avoid logging
innerHTML/domValue/cookies entirely and instead log a fixed-safe message or
specific non-secret attributes (use element IDs/data-test attributes) in the
test functions where formHTML, pwDiag.domValue, or document.cookie are
referenced (also update similar logging at the other occurrences noted around
the same file).
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Duplicate comments:
In `@integration/tests/cache-components.test.ts`:
- Around line 68-75: The catch block after awaiting passwordInput.waitFor
currently only logs diagnostics and lets the test continue without a password
step; change it to fail the test immediately by throwing an Error (or using
test.fail/assert) that includes the diagnostic details (e.g., the console
message and the captured formHTML from page.locator('.cl-signIn-root')), and
apply the same change to the similar block around the code handling the second
occurrence (lines 109-113) so any missing password-step render causes a hard
test failure rather than silently continuing.
- Around line 73-74: The test is logging sensitive auth data (formHTML from
page.locator('.cl-signIn-root').innerHTML(), pwDiag.domValue, and
document.cookie) to CI; replace those direct dumps with safe diagnostics by
removing or redacting sensitive fields before logging (e.g., mask input values
and cookie contents or only log non-sensitive metadata), or avoid logging
innerHTML/domValue/cookies entirely and instead log a fixed-safe message or
specific non-secret attributes (use element IDs/data-test attributes) in the
test functions where formHTML, pwDiag.domValue, or document.cookie are
referenced (also update similar logging at the other occurrences noted around
the same file).

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository YAML (base), Organization UI (inherited)

Review profile: ASSERTIVE

Plan: Pro

Run ID: f898c158-862b-43a7-bbc8-09eeb563b1bb

📥 Commits

Reviewing files that changed from the base of the PR and between c2f2542 and e9dfc01.

📒 Files selected for processing (1)
  • integration/tests/cache-components.test.ts

…ctive

On Next.js 16.2.0 with cacheComponents, the invalidateCacheAction server
action (which calls cookies() from next/headers) hangs indefinitely,
blocking setActive() from completing after sign-in. The sign-in API
returns complete but the session is never set because setActive is
stuck awaiting the server action.

Skip the server action on Next.js 16 and rely on router.refresh() in
onAfterSetActive for cache invalidation instead.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant