Skip to content

Conversation

@brkalow
Copy link
Member

@brkalow brkalow commented Aug 25, 2025

Description

  • Prevent a handshake from triggering in development after a handshake is resolved with a __clerk_db_jwt parameter
  • Reduce max-age of the redirect counter cookie to 2 to reduce false-positives during redirect detection
  • Update the org url sync logic to only consider a redirect loop when 3 or more redirects happen in quick succession, instead of just one

Checklist

  • pnpm test runs as expected.
  • pnpm build runs as expected.
  • (If applicable) JSDoc comments have been added or updated for any package exports
  • (If applicable) Documentation has been updated

Type of change

  • 🐛 Bug fix
  • 🌟 New feature
  • 🔨 Breaking change
  • 📖 Refactoring / dependency upgrade / documentation
  • other:

Summary by CodeRabbit

  • Bug Fixes

    • Reduced unintended activation handshake triggers in development by cleaning up redirect URLs during dev flows.
    • Allowed up to three redirects before treating the sequence as a loop, reducing false positives.
    • Shortened redirect-loop cookie lifespan for faster recovery during development.
  • Chores

    • Added a changeset to publish a patch release for the backend package.

…, and tighten redirect counter detection to reduce false positives
@vercel
Copy link

vercel bot commented Aug 25, 2025

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

Project Deployment Preview Comments Updated (UTC)
clerk-js-sandbox Ready Ready Preview Comment Aug 25, 2025 9:20pm

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Aug 25, 2025

Walkthrough

Adds a patch changeset and adjusts backend handshake behavior: removes DevBrowser from development redirect URLs, reduces the redirect-count cookie Max-Age to 2 seconds, and raises the redirect-loop threshold so the loop guard triggers only when the counter is >= 3.

Changes

Cohort / File(s) Summary
Release metadata
\.changeset/grumpy-groups-run.md
Adds a patch changeset for @clerk/backend describing a fix for excessive handshake triggering in development.
Handshake URL cleanup
packages/backend/src/tokens/handshake.ts
In resolveHandshake, when instanceType is 'development', also remove the DevBrowser query parameter from the redirect URL (in addition to Handshake and HandshakeHelp).
Redirect loop tracking
packages/backend/src/tokens/handshake.ts, packages/backend/src/tokens/request.ts, integration/tests/handshake.test.ts
checkAndTrackRedirectLoop now sets the RedirectCount cookie with Max-Age=2 (was 3). handleMaybeOrganizationSyncHandshake changes its loop guard to trigger when counter >= 3 (previously > 0). Test updated to set __clerk_redirect_count to 3.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant U as User Agent
  participant S as Backend
  participant H as resolveHandshake
  participant L as Loop Guard

  U->>S: Request (possible org activation)
  activate S
  S->>H: resolveHandshake(instanceType)
  activate H
  alt instanceType == development
    H->>H: Remove Handshake, HandshakeHelp, DevBrowser from redirect URL
  else
    H->>H: Remove Handshake, HandshakeHelp
  end
  H-->>S: Clean redirect URL
  deactivate H

  S->>U: Redirect response with RedirectCount cookie (Max-Age=2)
  deactivate S

  U->>S: Follow-up request with RedirectCount
  activate S
  S->>L: handleMaybeOrganizationSyncHandshake()
  activate L
  alt RedirectCount >= 3
    L-->>S: Treat as loop → skip activation, warn
  else RedirectCount < 3
    L-->>S: Continue activation/redirect flow
  end
  deactivate L
  deactivate S
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

I hop through loops, count one, then two—
on three I halt, reconsider through.
I prune dev crumbs from the redirect trail,
shrink cookie life so loops grow frail.
Patch packed light, I bound anew. 🐇✨

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch brk.fix/handshake-optimizations

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

const newCounterValue = this.authenticateContext.handshakeRedirectLoopCounter + 1;
const cookieName = constants.Cookies.RedirectCount;
headers.append('Set-Cookie', `${cookieName}=${newCounterValue}; SameSite=Lax; HttpOnly; Max-Age=3`);
headers.append('Set-Cookie', `${cookieName}=${newCounterValue}; SameSite=Lax; HttpOnly; Max-Age=2`);
Copy link
Member Author

Choose a reason for hiding this comment

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

3 was an arbitrary choice here, I'm reducing to 2 to mitigate the case where someone switches between orgs quickly when using org url sync

return null;
}
if (authenticateContext.handshakeRedirectLoopCounter > 0) {
if (authenticateContext.handshakeRedirectLoopCounter >= 3) {
Copy link
Member Author

Choose a reason for hiding this comment

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

Again, reducing the case where someone might be switching quickly. this should help, in addition to the max-age change, reduce false-positives of redirect loop detection

@pkg-pr-new
Copy link

pkg-pr-new bot commented Aug 25, 2025

Open in StackBlitz

@clerk/agent-toolkit

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

@clerk/astro

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

@clerk/backend

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

@clerk/chrome-extension

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

@clerk/clerk-js

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

@clerk/dev-cli

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

@clerk/elements

npm i https://pkg.pr.new/@clerk/elements@6635

@clerk/clerk-expo

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

@clerk/expo-passkeys

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

@clerk/express

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

@clerk/fastify

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

@clerk/localizations

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

@clerk/nextjs

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

@clerk/nuxt

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

@clerk/clerk-react

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

@clerk/react-router

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

@clerk/remix

npm i https://pkg.pr.new/@clerk/remix@6635

@clerk/shared

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

@clerk/tanstack-react-start

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

@clerk/testing

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

@clerk/themes

npm i https://pkg.pr.new/@clerk/themes@6635

@clerk/types

npm i https://pkg.pr.new/@clerk/types@6635

@clerk/upgrade

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

@clerk/vue

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

commit: db961af

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: 0

🧹 Nitpick comments (5)
.changeset/grumpy-groups-run.md (1)

1-5: Broaden the changeset note to reflect all user-visible behavior changes.

The note currently mentions the dev handshake trigger fix, but this PR also:

  • Lowers the redirect loop cookie Max-Age to 2s.
  • Raises the redirect-loop threshold for org activation to 3 redirects.

Consider expanding the description so downstream consumers understand the full behavioral impact.

Proposed wording:

---
-'@clerk/backend': patch
---
-Fixes an issue where a handshake would trigger more than intended in development.
+'@clerk/backend': patch
+---
+Fixes excessive dev handshakes and adjusts redirect loop detection:
+- Dev: remove the __clerk_db_jwt (DevBrowser) query param from the app URL after handshake resolution to avoid re-triggering.
+- Loop detection: lower redirect counter cookie Max-Age to 2s and only consider a loop after ≥3 rapid redirects.
packages/backend/src/tokens/handshake.ts (3)

221-228: Also strip LegacyDevBrowser in dev redirect, or reuse the existing helper for consistency.

In dev, you delete Handshake, HandshakeHelp, and DevBrowser. We already have removeDevBrowserFromURL which deletes both DevBrowser and LegacyDevBrowser. Reusing it here prevents stale legacy params from keeping the loop alive.

-    if (this.authenticateContext.instanceType === 'development') {
-      const newUrl = new URL(this.authenticateContext.clerkUrl);
-      newUrl.searchParams.delete(constants.QueryParameters.Handshake);
-      newUrl.searchParams.delete(constants.QueryParameters.HandshakeHelp);
-      newUrl.searchParams.delete(constants.QueryParameters.DevBrowser);
-      headers.append(constants.Headers.Location, newUrl.toString());
-      headers.set(constants.Headers.CacheControl, 'no-store');
-    }
+    if (this.authenticateContext.instanceType === 'development') {
+      const newUrl = this.removeDevBrowserFromURL(this.authenticateContext.clerkUrl);
+      newUrl.searchParams.delete(constants.QueryParameters.Handshake);
+      newUrl.searchParams.delete(constants.QueryParameters.HandshakeHelp);
+      headers.append(constants.Headers.Location, newUrl.toString());
+      headers.set(constants.Headers.CacheControl, 'no-store');
+    }

321-323: Use a non-strict threshold (>= 3) to align with request.ts and harden against drift.

request.ts treats a loop as >= 3. Using >= here avoids off-by-one surprises if the counter gets out of sync.

-    if (this.authenticateContext.handshakeRedirectLoopCounter === 3) {
+    if (this.authenticateContext.handshakeRedirectLoopCounter >= 3) {
       return true;
     }

325-329: Ensure the RedirectCount cookie is scoped to the root path

All occurrences of Set-Cookie with the RedirectCount name have been located only in handshake.ts, so adding Path=/ here will consistently apply across all routes without side effects.

• File: packages/backend/src/tokens/handshake.ts
Line 327 (zero-based index may differ):

-   headers.append('Set-Cookie', `${cookieName}=${newCounterValue}; SameSite=Lax; HttpOnly; Max-Age=2`);
+   headers.append('Set-Cookie', `${cookieName}=${newCounterValue}; Path=/; SameSite=Lax; HttpOnly; Max-Age=2`);

No other Set-Cookie calls for RedirectCount were found in the codebase, so this change is isolated and safe.

packages/backend/src/tokens/request.ts (1)

389-398: LGTM on raising the org-activation loop threshold to ≥3. Consider centralizing the threshold.

This matches the intent to allow a couple of redirects before considering it a loop. To avoid future drift with HandshakeService.checkAndTrackRedirectLoop, consider extracting a shared constant (e.g., REDIRECT_LOOP_THRESHOLD = 3) in constants.ts and referencing it in both places.

If you want, I can open a follow-up to introduce the shared constant and update both call-sites.

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 35a8cae and b73afbf.

📒 Files selected for processing (3)
  • .changeset/grumpy-groups-run.md (1 hunks)
  • packages/backend/src/tokens/handshake.ts (2 hunks)
  • packages/backend/src/tokens/request.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (7)
.changeset/**

📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)

Automated releases must use Changesets.

Files:

  • .changeset/grumpy-groups-run.md
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

**/*.{js,jsx,ts,tsx}: All code must pass ESLint checks with the project's configuration
Follow established naming conventions (PascalCase for components, camelCase for variables)
Maintain comprehensive JSDoc comments for public APIs
Use dynamic imports for optional features
All public APIs must be documented with JSDoc
Provide meaningful error messages to developers
Include error recovery suggestions where applicable
Log errors appropriately for debugging
Lazy load components and features when possible
Implement proper caching strategies
Use efficient data structures and algorithms
Profile and optimize critical paths
Validate all inputs and sanitize outputs
Implement proper logging with different levels

Files:

  • packages/backend/src/tokens/handshake.ts
  • packages/backend/src/tokens/request.ts
**/*.{js,jsx,ts,tsx,json,css,scss,md,yaml,yml}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Use Prettier for consistent code formatting

Files:

  • packages/backend/src/tokens/handshake.ts
  • packages/backend/src/tokens/request.ts
packages/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

TypeScript is required for all packages

Files:

  • packages/backend/src/tokens/handshake.ts
  • packages/backend/src/tokens/request.ts
packages/**/*.{ts,tsx,d.ts}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Packages should export TypeScript types alongside runtime code

Files:

  • packages/backend/src/tokens/handshake.ts
  • packages/backend/src/tokens/request.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Use proper TypeScript error types

**/*.{ts,tsx}: Always define explicit return types for functions, especially public APIs
Use proper type annotations for variables and parameters where inference isn't clear
Avoid any type - prefer unknown when type is uncertain, then narrow with type guards
Use interface for object shapes that might be extended
Use type for unions, primitives, and computed types
Prefer readonly properties for immutable data structures
Use private for internal implementation details
Use protected for inheritance hierarchies
Use public explicitly for clarity in public APIs
Prefer readonly for properties that shouldn't change after construction
Prefer composition and interfaces over deep inheritance chains
Use mixins for shared behavior across unrelated classes
Implement dependency injection for loose coupling
Let TypeScript infer when types are obvious
Use const assertions for literal types: as const
Use satisfies operator for type checking without widening
Use mapped types for transforming object types
Use conditional types for type-level logic
Leverage template literal types for string manipulation
Use ES6 imports/exports consistently
Use default exports sparingly, prefer named exports
Use type-only imports: import type { ... } from ...
No any types without justification
Proper error handling with typed errors
Consistent use of readonly for immutable data
Proper generic constraints
No unused type parameters
Proper use of utility types instead of manual type construction
Type-only imports where possible
Proper tree-shaking friendly exports
No circular dependencies
Efficient type computations (avoid deep recursion)

Files:

  • packages/backend/src/tokens/handshake.ts
  • packages/backend/src/tokens/request.ts
**/*.{js,ts,tsx,jsx}

📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)

Support multiple Clerk environment variables (CLERK_, NEXT_PUBLIC_CLERK_, etc.) for configuration.

Files:

  • packages/backend/src/tokens/handshake.ts
  • packages/backend/src/tokens/request.ts
🧬 Code graph analysis (1)
packages/backend/src/tokens/handshake.ts (1)
packages/backend/src/constants.ts (1)
  • constants (79-85)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (5)
  • GitHub Check: Build Packages
  • GitHub Check: Formatting | Dedupe | Changeset
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: semgrep-cloud-platform/scan
  • GitHub Check: semgrep-cloud-platform/scan

@changeset-bot
Copy link

changeset-bot bot commented Aug 25, 2025

🦋 Changeset detected

Latest commit: db961af

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 11 packages
Name Type
@clerk/backend Patch
@clerk/agent-toolkit Patch
@clerk/astro Patch
@clerk/express Patch
@clerk/fastify Patch
@clerk/nextjs Patch
@clerk/nuxt Patch
@clerk/react-router Patch
@clerk/remix Patch
@clerk/tanstack-react-start Patch
@clerk/testing Patch

Not sure what this means? Click here to learn what changesets are.

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

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: 0

🧹 Nitpick comments (4)
integration/tests/handshake.test.ts (4)

1448-1451: Avoid parsing a missing Location header on 200 responses

On 200, there should be no Location header. Parsing new URLSearchParams(res.headers.get('location')) relies on implementation quirks (e.g., treating null as a string) and is brittle across runtimes. Assert explicitly that the header is absent instead.

Apply this diff:

-    expect(res.status).toBe(200);
-    const redirectSearchParams = new URLSearchParams(res.headers.get('location'));
-    expect(redirectSearchParams.get('organization_id')).toBe(null);
+    expect(res.status).toBe(200);
+    expect(res.headers.get('location')).toBeNull();

1418-1421: Lock in the new cookie TTL: assert Max-Age=2

Given the PR reduces the redirect-tracking cookie lifetime to 2 seconds, assert it in the test to prevent regressions. A regex keeps the assertion resilient to attribute ordering.

     // read the set-cookie directives
     const setCookie = res.headers.get('set-cookie');

-    expect(setCookie).toContain(`__clerk_redirect_count=1`); // <-- Critical
+    expect(setCookie).toContain(`__clerk_redirect_count=1`); // <-- Critical
+    // Also assert the new TTL
+    expect(setCookie).toMatch(/__clerk_redirect_count=1(?:;[^;]*)*;\s*Max-Age=2\b/i);

837-861: Add a follow-up request to ensure no post-handshake re-trigger in dev after __clerk_db_jwt resolution

One objective is to stop retriggering a handshake in development after resolving a handshake that set __clerk_db_jwt. You’re setting the cookie in “Handshake result - dev - new devbrowser”, but we don’t verify the very next navigation returns 200 without another handshake.

Proposed test to add right after this block:

test('No re-handshake in dev immediately after handshake that set __clerk_db_jwt', async () => {
  const config = generateConfig({ mode: 'test' });
  const { token } = config.generateToken({ state: 'active' });

  // Simulate a handshake result that sets both session and devbrowser cookies
  const cookiesToSet = [`__session=${token};path=/`, '__clerk_db_jwt=asdf;path=/'];
  const handshake = await config.generateHandshakeToken(cookiesToSet);

  const res1 = await fetch(app.serverUrl + '/?__clerk_handshake=' + handshake, {
    headers: new Headers({
      Cookie: `${devBrowserCookie}`,
      'X-Publishable-Key': config.pk,
      'X-Secret-Key': config.sk,
      'Sec-Fetch-Dest': 'document',
    }),
    redirect: 'manual',
  });

  expect(res1.status).toBe(307);
  expect(res1.headers.get('location')).toBe('/');

  // Build Cookie header from Set-Cookie lines to mimic the browser carrying them forward
  const setCookieLines = [...res1.headers.entries()]
    .filter(([k]) => k.toLowerCase() === 'set-cookie')
    .map(([, v]) => v.split(';')[0]); // take "name=value"
  const carryCookies = setCookieLines.join('; ');

  // Next navigation to "/" should NOT handshake again
  const res2 = await fetch(app.serverUrl + '/', {
    headers: new Headers({
      Cookie: `${carryCookies}`,
      'X-Publishable-Key': config.pk,
      'X-Secret-Key': config.sk,
      'Sec-Fetch-Dest': 'document',
    }),
    redirect: 'manual',
  });

  expect(res2.status).toBe(200);
  expect(res2.headers.get('location')).toBeNull();
});

This asserts the fix end-to-end: once the devbrowser cookie is set from a resolved handshake, a subsequent visit does not re-enter the handshake path.


1339-1343: Remove stray console.log calls from the test suite

These logs add noise to CI output and aren’t needed for assertions.

-      if (testCase.name === 'Header-based auth should not handshake with expired auth') {
-        console.log(testCase.name);
-        console.log(res.headers.get('x-clerk-auth-status'));
-        console.log(res.headers.get('x-clerk-auth-reason'));
-      }
+      // (removed noisy debug logs)
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between b73afbf and db961af.

📒 Files selected for processing (1)
  • integration/tests/handshake.test.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (7)
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

**/*.{js,jsx,ts,tsx}: All code must pass ESLint checks with the project's configuration
Follow established naming conventions (PascalCase for components, camelCase for variables)
Maintain comprehensive JSDoc comments for public APIs
Use dynamic imports for optional features
All public APIs must be documented with JSDoc
Provide meaningful error messages to developers
Include error recovery suggestions where applicable
Log errors appropriately for debugging
Lazy load components and features when possible
Implement proper caching strategies
Use efficient data structures and algorithms
Profile and optimize critical paths
Validate all inputs and sanitize outputs
Implement proper logging with different levels

Files:

  • integration/tests/handshake.test.ts
**/*.{js,jsx,ts,tsx,json,css,scss,md,yaml,yml}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Use Prettier for consistent code formatting

Files:

  • integration/tests/handshake.test.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Use proper TypeScript error types

**/*.{ts,tsx}: Always define explicit return types for functions, especially public APIs
Use proper type annotations for variables and parameters where inference isn't clear
Avoid any type - prefer unknown when type is uncertain, then narrow with type guards
Use interface for object shapes that might be extended
Use type for unions, primitives, and computed types
Prefer readonly properties for immutable data structures
Use private for internal implementation details
Use protected for inheritance hierarchies
Use public explicitly for clarity in public APIs
Prefer readonly for properties that shouldn't change after construction
Prefer composition and interfaces over deep inheritance chains
Use mixins for shared behavior across unrelated classes
Implement dependency injection for loose coupling
Let TypeScript infer when types are obvious
Use const assertions for literal types: as const
Use satisfies operator for type checking without widening
Use mapped types for transforming object types
Use conditional types for type-level logic
Leverage template literal types for string manipulation
Use ES6 imports/exports consistently
Use default exports sparingly, prefer named exports
Use type-only imports: import type { ... } from ...
No any types without justification
Proper error handling with typed errors
Consistent use of readonly for immutable data
Proper generic constraints
No unused type parameters
Proper use of utility types instead of manual type construction
Type-only imports where possible
Proper tree-shaking friendly exports
No circular dependencies
Efficient type computations (avoid deep recursion)

Files:

  • integration/tests/handshake.test.ts
integration/**

📄 CodeRabbit inference engine (.cursor/rules/global.mdc)

Framework integration templates and E2E tests should be placed under the integration/ directory

Files:

  • integration/tests/handshake.test.ts
integration/**/*

📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)

End-to-end tests and integration templates must be located in the 'integration/' directory.

Files:

  • integration/tests/handshake.test.ts
integration/**/*.{test,spec}.{js,ts}

📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)

Integration tests should use Playwright.

Files:

  • integration/tests/handshake.test.ts
**/*.{js,ts,tsx,jsx}

📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)

Support multiple Clerk environment variables (CLERK_, NEXT_PUBLIC_CLERK_, etc.) for configuration.

Files:

  • integration/tests/handshake.test.ts
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (27)
  • GitHub Check: Integration Tests (quickstart, chrome)
  • GitHub Check: Integration Tests (vue, chrome)
  • GitHub Check: Integration Tests (nextjs, chrome, 14)
  • GitHub Check: Integration Tests (nextjs, chrome, 15)
  • GitHub Check: Integration Tests (billing, chrome)
  • GitHub Check: Integration Tests (localhost, chrome)
  • GitHub Check: Integration Tests (tanstack-react-router, chrome)
  • GitHub Check: Integration Tests (react-router, chrome)
  • GitHub Check: Integration Tests (tanstack-react-start, chrome)
  • GitHub Check: Integration Tests (nuxt, chrome)
  • GitHub Check: Integration Tests (machine, chrome)
  • GitHub Check: Integration Tests (expo-web, chrome)
  • GitHub Check: Integration Tests (astro, chrome)
  • GitHub Check: Integration Tests (sessions, chrome)
  • GitHub Check: Integration Tests (elements, chrome)
  • GitHub Check: Integration Tests (express, chrome)
  • GitHub Check: Integration Tests (ap-flows, chrome)
  • GitHub Check: Integration Tests (generic, chrome)
  • GitHub Check: Publish with pkg-pr-new
  • GitHub Check: Unit Tests (18, --filter=@clerk/astro --filter=@clerk/backend --filter=@clerk/express --filter=@c...
  • GitHub Check: Unit Tests (22, **)
  • GitHub Check: Static analysis
  • GitHub Check: Formatting | Dedupe | Changeset
  • GitHub Check: semgrep/ci
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: semgrep-cloud-platform/scan
  • GitHub Check: semgrep-cloud-platform/scan
🔇 Additional comments (1)
integration/tests/handshake.test.ts (1)

1437-1441: Redirect-loop threshold updated to 3 — test change matches backend behavior

Bumping __clerk_redirect_count to 3 here aligns the test with the new ">= 3 redirects" loop-guard logic. Looks good.

@brkalow brkalow requested a review from a team August 25, 2025 21:27
@brkalow brkalow merged commit 9036427 into main Aug 26, 2025
39 checks passed
@brkalow brkalow deleted the brk.fix/handshake-optimizations branch August 26, 2025 01:49
const newUrl = new URL(this.authenticateContext.clerkUrl);
newUrl.searchParams.delete(constants.QueryParameters.Handshake);
newUrl.searchParams.delete(constants.QueryParameters.HandshakeHelp);
newUrl.searchParams.delete(constants.QueryParameters.DevBrowser);
Copy link
Member

Choose a reason for hiding this comment

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

This looks good to me. Was there any reason we used to delete it from the clerk-js side only or just an omission?

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.

5 participants