Skip to content

Conversation

anagstef
Copy link
Member

@anagstef anagstef commented Oct 20, 2025

Description

Playwright released a breaking change on their 1.52 release that affects us. This is a fix for it.

Playwright changelog: https://playwright.dev/docs/release-notes#breaking-changes-2

Specific breaking change that affects us:

Glob URL patterns in methods like page.route() do not support ? and [] anymore. We recommend using regular expressions instead.

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
    • Improved Playwright route URL matching in testing utilities by switching to a more precise pattern approach, reducing false positives and ensuring consistent identification of API routes across configurations for more reliable test execution.

@changeset-bot
Copy link

changeset-bot bot commented Oct 20, 2025

🦋 Changeset detected

Latest commit: 684c26f

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

This PR includes changesets to release 1 package
Name Type
@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

@vercel
Copy link

vercel bot commented Oct 20, 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 Oct 20, 2025 6:27pm

💡 Enable Vercel Agent with $100 free credit for automated AI reviews

@anagstef anagstef requested review from a team and octoper October 20, 2025 18:03
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Oct 20, 2025

Walkthrough

Added a patch changeset and replaced a string/Glob-based Playwright API route matcher with a RegExp that escapes the Frontend API URL and enforces the v1 path plus optional query string.

Changes

Cohort / File(s) Summary
Changeset Documentation
\.changeset/cool-keys-scream.md
New patch-level changeset for @clerk/testing documenting the Playwright route matching fix.
Playwright Route Matching
packages/testing/src/playwright/setupClerkTestingToken.ts
Replaced string/Glob route matching with a RegExp built from the Frontend API URL (dots escaped), anchored to the /v1/... path and optional query string for more precise matching.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor Test as Playwright test
  participant Setup as setupClerkTestingToken()
  participant Router as Playwright Route matcher
  participant Backend as Clerk Frontend API

  Test->>Setup: initialize test fixture
  Setup->>Router: register route matcher (RegExp anchored to Frontend API URL + /v1/...)
  Note over Router,Backend: Router uses RegExp to match requests
  Test->>Backend: perform API request
  Backend-->>Router: request URL emitted
  Router-->>Setup: matched via RegExp (handled)
  Setup-->>Test: return mocked/handled response
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

🐰 Hopped through strings to find a clue,
Dots escaped, the pattern grew,
RegExp stitched the v1 line neat,
Playwright’s routes now click and meet,
A tiny patch — a rabbit's treat.

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The title "fix(testing): Update FAPI URL to use Regex on Playwright" directly and specifically describes the primary change in this pull request. The changeset documents a fix updating Playwright route URL matching from Glob patterns to RegExp, and the code change in setupClerkTestingToken.ts replaces string-based API route matching with a RegExp pattern. The title accurately captures this core objective: updating the Frontend API (FAPI) URL matching to use Regex for Playwright. The title is concise, uses clear terminology, avoids vague language, and includes the relevant context about the Playwright framework.
Docstring Coverage ✅ Passed No functions found in the changes. Docstring coverage check skipped.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch stefanos/user-3743-fix-interceptor-for-playwright-breaking-change-in-url

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

@anagstef anagstef removed the request for review from octoper October 20, 2025 18:04
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 (1)
packages/testing/src/playwright/setupClerkTestingToken.ts (1)

41-41: The RegExp pattern is correct and addresses the Playwright v1.52 breaking change.

The dot escaping and pattern construction work as intended. The .*?(\\?.*)? pattern correctly matches the path and optional query string.

Optional simplification:

The pattern could be simplified since the code manipulates URLs via the URL API rather than regex capture groups. Consider:

-  const apiUrl = new RegExp(`^https://${fapiUrl.replace(/\./g, '\\.')}/v1/.*?(\\?.*)?$`);
+  const apiUrl = new RegExp(`^https://${fapiUrl.replace(/\./g, '\\.')}/v1/.*$`);

The simpler .*$ pattern matches everything after /v1/ (including query strings) and is more straightforward, though both patterns are functionally equivalent for this use case.

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Disabled knowledge base sources:

  • 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 64d3135 and 9241825.

📒 Files selected for processing (2)
  • .changeset/cool-keys-scream.md (1 hunks)
  • packages/testing/src/playwright/setupClerkTestingToken.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:

  • packages/testing/src/playwright/setupClerkTestingToken.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/testing/src/playwright/setupClerkTestingToken.ts
packages/**/*.{ts,tsx}

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

TypeScript is required for all packages

Files:

  • packages/testing/src/playwright/setupClerkTestingToken.ts
packages/**/*.{ts,tsx,d.ts}

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

Packages should export TypeScript types alongside runtime code

Files:

  • packages/testing/src/playwright/setupClerkTestingToken.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/testing/src/playwright/setupClerkTestingToken.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/testing/src/playwright/setupClerkTestingToken.ts
.changeset/**

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

Automated releases must use Changesets.

Files:

  • .changeset/cool-keys-scream.md
⏰ 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: Formatting | Dedupe | Changeset
  • GitHub Check: Build Packages
  • GitHub Check: semgrep-cloud-platform/scan
  • GitHub Check: semgrep-cloud-platform/scan
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (1)
.changeset/cool-keys-scream.md (1)

1-5: LGTM! Changeset correctly documents the patch.

The changeset properly categorizes this as a patch-level change for @clerk/testing with a clear description of the fix.

@pkg-pr-new
Copy link

pkg-pr-new bot commented Oct 20, 2025

Open in StackBlitz

@clerk/agent-toolkit

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

@clerk/astro

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

@clerk/backend

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

@clerk/chrome-extension

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

@clerk/clerk-js

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

@clerk/dev-cli

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

@clerk/elements

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

@clerk/clerk-expo

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

@clerk/expo-passkeys

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

@clerk/express

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

@clerk/fastify

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

@clerk/localizations

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

@clerk/nextjs

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

@clerk/nuxt

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

@clerk/clerk-react

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

@clerk/react-router

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

@clerk/remix

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

@clerk/shared

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

@clerk/tanstack-react-start

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

@clerk/testing

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

@clerk/themes

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

@clerk/types

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

@clerk/upgrade

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

@clerk/vue

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

commit: 684c26f

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

♻️ Duplicate comments (1)
packages/testing/src/playwright/setupClerkTestingToken.ts (1)

42-43: Backslash escaping is now covered—resolves prior alert

/[.*+?^${}()|[\]\\]/g escapes \ and ], addressing the previous “incomplete escaping” warning.

🧹 Nitpick comments (4)
packages/testing/src/playwright/setupClerkTestingToken.ts (4)

42-44: Good fix; harden matcher with normalization and cheaper pattern

The escape is correct. To make the matcher more robust and reduce backtracking, normalize the host, use a case‑insensitive host match, and avoid lazy .*? before an optional group.

Apply:

-  const escapedFapiUrl = fapiUrl.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
-  const apiUrl = new RegExp(`^https://${escapedFapiUrl}/v1/.*?(\\?.*)?$`);
+  const normalizedHost = fapiUrl.replace(/^\s*https?:\/\//i, '').replace(/\/+$/, '');
+  const escapedHost = normalizedHost.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
+  // If you need to support http for local setups, change ^https:// to ^https?://
+  const apiUrl = new RegExp(`^https://${escapedHost}/v1(?:/[^?]*)?(?:\\?.*)?$`, 'i');

49-51: Don’t overwrite an existing testing token in the URL

Avoid clobbering a pre‑set token.

-    if (testingToken) {
-      originalUrl.searchParams.set(TESTING_TOKEN_PARAM, testingToken);
-    }
+    if (testingToken && !originalUrl.searchParams.has(TESTING_TOKEN_PARAM)) {
+      originalUrl.searchParams.set(TESTING_TOKEN_PARAM, testingToken);
+    }

53-80: Avoid extra network round‑trip for non‑JSON responses

Currently, a non‑JSON response triggers route.fetch() then route.continue(), sending a second request. Fulfill with the first response when it’s not JSON; only parse/patch when JSON.

     try {
-      const response = await route.fetch({
-        url: originalUrl.toString(),
-      });
-
-      const json = await response.json();
+      const response = await route.fetch({ url: originalUrl.toString() });
+      const contentType = (response.headers()['content-type'] || '').toLowerCase();
+      if (!contentType.includes('application/json')) {
+        await route.fulfill({ response });
+        return;
+      }
+      const json = await response.json();
@@
-      await route.fulfill({
-        response,
-        json,
-      });
-    } catch {
+      await route.fulfill({ response, json });
+    } catch (err) {
       await route
         .continue({
           url: originalUrl.toString(),
         })
         .catch(console.error);
     }

30-30: Add explicit return type per project guidelines

Declare Promise<void> for this exported function.

-export const setupClerkTestingToken = async ({ context, options, page }: SetupClerkTestingTokenParams) => {
+export const setupClerkTestingToken = async (
+  { context, options, page }: SetupClerkTestingTokenParams,
+): Promise<void> => {
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Disabled knowledge base sources:

  • 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 9241825 and 6c1825f.

📒 Files selected for processing (1)
  • packages/testing/src/playwright/setupClerkTestingToken.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (6)
**/*.{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/testing/src/playwright/setupClerkTestingToken.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/testing/src/playwright/setupClerkTestingToken.ts
packages/**/*.{ts,tsx}

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

TypeScript is required for all packages

Files:

  • packages/testing/src/playwright/setupClerkTestingToken.ts
packages/**/*.{ts,tsx,d.ts}

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

Packages should export TypeScript types alongside runtime code

Files:

  • packages/testing/src/playwright/setupClerkTestingToken.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/testing/src/playwright/setupClerkTestingToken.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/testing/src/playwright/setupClerkTestingToken.ts
🪛 ast-grep (0.39.6)
packages/testing/src/playwright/setupClerkTestingToken.ts

[warning] 42-42: Regular expression constructed from variable input detected. This can lead to Regular Expression Denial of Service (ReDoS) attacks if the variable contains malicious patterns. Use libraries like 'recheck' to validate regex safety or use static patterns.
Context: new RegExp(^https://${escapedFapiUrl}/v1/.*?(\\?.*)?$)
Note: [CWE-1333] Inefficient Regular Expression Complexity [REFERENCES]
- https://owasp.org/www-community/attacks/Regular_expression_Denial_of_Service_-_ReDoS
- https://cwe.mitre.org/data/definitions/1333.html

(regexp-from-variable)

⏰ 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

@anagstef anagstef merged commit 04fb9e2 into main Oct 21, 2025
39 checks passed
@anagstef anagstef deleted the stefanos/user-3743-fix-interceptor-for-playwright-breaking-change-in-url branch October 21, 2025 07:20
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants