Skip to content

Conversation

nikosdouvlis
Copy link
Member

@nikosdouvlis nikosdouvlis commented Sep 15, 2025

Description

Removes all undefined values from the body of requests fired through fapiClient
This shouldn't change existing behavior - it's something that we used to do manually in the resources but we decided to move the logic to a more central place as we had to constantly do extra checks for boolean values or params that could take null | '' as valid values

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

  • Refactor
    • Non-FormData request bodies now omit top-level undefined fields for cleaner API payloads.
    • Sign-up flows send streamlined request bodies with consistent metadata normalization.
  • Tests
    • Added comprehensive tests validating filtering behavior across objects, FormData, arrays, primitives, empty/undefined-only cases, and nested (non-deep) behavior.
  • Chores
    • Added a changeset entry.

Copy link

changeset-bot bot commented Sep 15, 2025

🦋 Changeset detected

Latest commit: 3d74404

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

This PR includes changesets to release 0 packages

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

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

vercel bot commented Sep 15, 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 Sep 16, 2025 10:27am

Copy link
Contributor

coderabbitai bot commented Sep 15, 2025

Walkthrough

Adds a shallow filterUndefinedValues utility, re-exports it, applies it in fapiClient to remove top-level undefineds from non-FormData object request bodies, refactors SignUp methods to spread params and normalize unsafeMetadata, adds unit tests (including a duplicated fapiClient suite), and adds an empty changeset file.

Changes

Cohort / File(s) Summary
Request body filtering integration
packages/clerk-js/src/core/fapiClient.ts, packages/clerk-js/src/core/__tests__/fapiClient.spec.ts
fapiClient now applies filterUndefinedValues to non-FormData object bodies before encoding. Tests validate plain objects, FormData, strings, empty objects, and nested objects. The new test suite was inserted twice (duplicate).
Undefined filtering utility + exports
packages/clerk-js/src/utils/filterUndefinedValues.ts, packages/clerk-js/src/utils/__tests__/filterUndefinedValues.spec.ts, packages/clerk-js/src/utils/index.ts
Adds filterUndefinedValues (shallow: remove top-level undefined keys; preserve other falsy values), adds unit tests covering primitives/arrays/FormData/objects, and re-exports the utility; beforeUnloadTracker re-export order was moved below appearance.
SignUp body construction refactor
packages/clerk-js/src/core/resources/SignUp.ts
create, update, and password now assemble request bodies by spreading ...params and consistently include normalized unsafeMetadata, replacing explicit per-field mappings.
Changeset metadata
.changeset/fuzzy-books-win.md
Adds a changeset file containing an empty front-matter block (---) and no runtime/API changes.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor UI as UI
  participant SignUp as SignUp
  participant FApi as fapiClient
  participant Filter as filterUndefinedValues
  participant Net as Network

  UI->>SignUp: call create/update/password(params)
  SignUp->>SignUp: build body = {...params, unsafeMetadata: normalized}
  SignUp->>FApi: request({ method, body })
  alt body instanceof FormData
    FApi->>Net: send FormData as-is
  else body is object (non-FormData)
    FApi->>Filter: filterUndefinedValues(body)
    Filter-->>FApi: filteredBody
    FApi->>Net: encode & send filteredBody
  else
    FApi->>Net: send non-object body as-is
  end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Poem

I nibble keys and tidy the mess,
Top-level crumbs I gently address.
Sign-ups hop in with metadata neat,
Requests march onwards, no undefined sleet.
Two tests clap twice — a double-skip beat. 🐇

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 concisely and accurately summarizes the primary change: centralizing the filtering of undefined values from request bodies in clerk-js. It follows conventional commit style (feat(scope):) and is specific enough for a reviewer scanning PR history, aligning with the PR description and the code changes to fapiClient and the new filter utility.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
✨ Finishing touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch nikos/filter-undefined-values-from-body

📜 Recent 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 3c7f445 and 3d74404.

📒 Files selected for processing (1)
  • packages/clerk-js/src/utils/filterUndefinedValues.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/clerk-js/src/utils/filterUndefinedValues.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). (6)
  • GitHub Check: Build Packages
  • GitHub Check: Formatting | Dedupe | Changeset
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: semgrep/ci
  • GitHub Check: semgrep-cloud-platform/scan
  • GitHub Check: semgrep-cloud-platform/scan

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

Copy link

pkg-pr-new bot commented Sep 16, 2025

Open in StackBlitz

@clerk/agent-toolkit

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

@clerk/astro

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

@clerk/backend

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

@clerk/chrome-extension

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

@clerk/clerk-js

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

@clerk/dev-cli

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

@clerk/elements

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

@clerk/clerk-expo

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

@clerk/expo-passkeys

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

@clerk/express

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

@clerk/fastify

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

@clerk/localizations

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

@clerk/nextjs

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

@clerk/nuxt

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

@clerk/clerk-react

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

@clerk/react-router

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

@clerk/remix

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

@clerk/shared

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

@clerk/tanstack-react-start

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

@clerk/testing

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

@clerk/themes

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

@clerk/types

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

@clerk/upgrade

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

@clerk/vue

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

commit: 3d74404

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

🧹 Nitpick comments (4)
packages/clerk-js/src/utils/filterUndefinedValues.ts (1)

1-6: Tiny docs touch‑up: clarify return value

 /**
  * Filters out undefined values from the first level of an object.
  * Preserves all other falsy values (null, false, 0, empty string).
  *
- * @param obj - The object to filter, or any other value
+ * @param obj - The value to filter; non-plain objects are returned unchanged
+ * @returns The same value if not a plain object; otherwise a shallow copy without undefined top-level properties
  */
packages/clerk-js/src/core/resources/SignUp.ts (1)

604-606: Remove redundant transfer assignment

transfer is also included via ...params, so this line is a no‑op and can be dropped.

-        transfer: params.transfer,
         captchaToken,
         captchaWidgetType,
         captchaError,
         ...params,

Also applies to: 608-608

packages/clerk-js/src/core/__tests__/fapiClient.spec.ts (1)

354-382: Rename test for clarity: nested undefined aren’t preserved after JSON stringify

The expectation is that nested undefined keys are dropped by JSON.stringify. Update the title to avoid confusion.

-it('does not perform deep filtering - preserves nested undefined values', async () => {
+it('does not perform deep filtering — nested objects are JSON‑stringified (undefined omitted)', async () => {
packages/clerk-js/src/utils/__tests__/filterUndefinedValues.spec.ts (1)

137-144: Add coverage for non‑plain objects (Date/Map/Set/URLSearchParams)

Ensure we don’t accidentally coerce these to {}. With the proposed plain‑object guard, they should round‑trip unchanged.

   it('creates a new object reference', () => {
     const input = { a: 1, b: undefined };
     const result = filterUndefinedValues(input);
 
     expect(result).not.toBe(input);
     expect(result).toEqual({ a: 1 });
   });
+
+  it('returns non-plain objects unchanged (Date/Map/Set/URLSearchParams)', () => {
+    const d = new Date();
+    const m = new Map([['a', 1]]);
+    const s = new Set([1, 2]);
+    const usp = new URLSearchParams({ a: '1' });
+    expect(filterUndefinedValues(d)).toBe(d);
+    expect(filterUndefinedValues(m as any)).toBe(m);
+    expect(filterUndefinedValues(s as any)).toBe(s);
+    expect(filterUndefinedValues(usp as any)).toBe(usp);
+  });
 });
📜 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 1ceedad and efb512c.

📒 Files selected for processing (7)
  • .changeset/fuzzy-books-win.md (1 hunks)
  • packages/clerk-js/src/core/__tests__/fapiClient.spec.ts (1 hunks)
  • packages/clerk-js/src/core/fapiClient.ts (2 hunks)
  • packages/clerk-js/src/core/resources/SignUp.ts (2 hunks)
  • packages/clerk-js/src/utils/__tests__/filterUndefinedValues.spec.ts (1 hunks)
  • packages/clerk-js/src/utils/filterUndefinedValues.ts (1 hunks)
  • packages/clerk-js/src/utils/index.ts (2 hunks)
🧰 Additional context used
📓 Path-based instructions (12)
**/*.{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/clerk-js/src/utils/__tests__/filterUndefinedValues.spec.ts
  • packages/clerk-js/src/utils/index.ts
  • packages/clerk-js/src/utils/filterUndefinedValues.ts
  • packages/clerk-js/src/core/__tests__/fapiClient.spec.ts
  • packages/clerk-js/src/core/resources/SignUp.ts
  • packages/clerk-js/src/core/fapiClient.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/clerk-js/src/utils/__tests__/filterUndefinedValues.spec.ts
  • packages/clerk-js/src/utils/index.ts
  • packages/clerk-js/src/utils/filterUndefinedValues.ts
  • packages/clerk-js/src/core/__tests__/fapiClient.spec.ts
  • packages/clerk-js/src/core/resources/SignUp.ts
  • packages/clerk-js/src/core/fapiClient.ts
packages/**/*.{ts,tsx}

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

TypeScript is required for all packages

Files:

  • packages/clerk-js/src/utils/__tests__/filterUndefinedValues.spec.ts
  • packages/clerk-js/src/utils/index.ts
  • packages/clerk-js/src/utils/filterUndefinedValues.ts
  • packages/clerk-js/src/core/__tests__/fapiClient.spec.ts
  • packages/clerk-js/src/core/resources/SignUp.ts
  • packages/clerk-js/src/core/fapiClient.ts
packages/**/*.{ts,tsx,d.ts}

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

Packages should export TypeScript types alongside runtime code

Files:

  • packages/clerk-js/src/utils/__tests__/filterUndefinedValues.spec.ts
  • packages/clerk-js/src/utils/index.ts
  • packages/clerk-js/src/utils/filterUndefinedValues.ts
  • packages/clerk-js/src/core/__tests__/fapiClient.spec.ts
  • packages/clerk-js/src/core/resources/SignUp.ts
  • packages/clerk-js/src/core/fapiClient.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/clerk-js/src/utils/__tests__/filterUndefinedValues.spec.ts
  • packages/clerk-js/src/utils/index.ts
  • packages/clerk-js/src/utils/filterUndefinedValues.ts
  • packages/clerk-js/src/core/__tests__/fapiClient.spec.ts
  • packages/clerk-js/src/core/resources/SignUp.ts
  • packages/clerk-js/src/core/fapiClient.ts
packages/**/*.{test,spec}.{js,jsx,ts,tsx}

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

Unit tests should use Jest or Vitest as the test runner.

Files:

  • packages/clerk-js/src/utils/__tests__/filterUndefinedValues.spec.ts
  • packages/clerk-js/src/core/__tests__/fapiClient.spec.ts
packages/{clerk-js,elements,themes}/**/*.{test,spec}.{js,jsx,ts,tsx}

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

Visual regression testing should be performed for UI components.

Files:

  • packages/clerk-js/src/utils/__tests__/filterUndefinedValues.spec.ts
  • packages/clerk-js/src/core/__tests__/fapiClient.spec.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/clerk-js/src/utils/__tests__/filterUndefinedValues.spec.ts
  • packages/clerk-js/src/utils/index.ts
  • packages/clerk-js/src/utils/filterUndefinedValues.ts
  • packages/clerk-js/src/core/__tests__/fapiClient.spec.ts
  • packages/clerk-js/src/core/resources/SignUp.ts
  • packages/clerk-js/src/core/fapiClient.ts
**/__tests__/**/*.{ts,tsx}

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

**/__tests__/**/*.{ts,tsx}: Create type-safe test builders/factories
Use branded types for test isolation
Implement proper mock types that match interfaces

Files:

  • packages/clerk-js/src/utils/__tests__/filterUndefinedValues.spec.ts
  • packages/clerk-js/src/core/__tests__/fapiClient.spec.ts
.changeset/**

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

Automated releases must use Changesets.

Files:

  • .changeset/fuzzy-books-win.md
packages/**/index.{js,ts}

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

Use tree-shaking friendly exports

Files:

  • packages/clerk-js/src/utils/index.ts
**/index.ts

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

Use index.ts files for clean imports but avoid deep barrel exports

Avoid barrel files (index.ts re-exports) as they can cause circular dependencies

Files:

  • packages/clerk-js/src/utils/index.ts
🧬 Code graph analysis (3)
packages/clerk-js/src/utils/__tests__/filterUndefinedValues.spec.ts (1)
packages/clerk-js/src/utils/filterUndefinedValues.ts (1)
  • filterUndefinedValues (7-22)
packages/clerk-js/src/core/resources/SignUp.ts (2)
packages/types/src/signUpFuture.ts (1)
  • SignUpFutureUpdateParams (18-18)
packages/clerk-js/src/utils/runAsyncResourceTask.ts (1)
  • runAsyncResourceTask (8-30)
packages/clerk-js/src/core/fapiClient.ts (1)
packages/clerk-js/src/utils/filterUndefinedValues.ts (1)
  • filterUndefinedValues (7-22)
🔇 Additional comments (6)
packages/clerk-js/src/core/resources/SignUp.ts (3)

170-173: Whole‑object normalization: confirm normalizeUnsafeMetadata semantics

Passing the entire finalParams into normalizeUnsafeMetadata is tidy; confirm it only transforms unsafeMetadata and doesn’t touch captcha fields or other params.


614-617: LGTM: update body build is consistent and defers undefined filtering to fapiClient

Also applies to: 619-619


632-634: LGTM: password body build mirrors create/update pattern

Also applies to: 636-636

packages/clerk-js/src/core/fapiClient.ts (1)

8-13: Import looks good

.changeset/fuzzy-books-win.md (1)

1-2: Fix empty Changeset front‑matter — releases will be skipped or fail

File: .changeset/fuzzy-books-win.md (lines 1–2) — front‑matter is empty; specify package, bump type, and add a short summary.

Apply something like:

----
----
+---
+'@clerk/clerk-js': patch
+---
+
+Filter undefined values from non‑FormData request bodies in fapiClient; add filterUndefinedValues utility and export; normalize SignUp body builders.

Verify the exact package name in this repo (e.g., '@clerk/clerk-js').

packages/clerk-js/src/utils/index.ts (1)

2-2: No import-time side effects — beforeUnloadTracker safe to re-export.
beforeUnloadTracker.ts only declares factory functions; addEventListener is called inside startListening()/createBeforeUnloadTracker when enabled, not at import time (packages/clerk-js/src/utils/beforeUnloadTracker.ts; CLERK_BEFORE_UNLOAD_EVENT is a const in packages/clerk-js/src/utils/windowNavigate.ts).

Comment on lines +200 to +203
if (body && typeof body === 'object' && !(body instanceof FormData)) {
requestInit.body = filterUndefinedValues(body);
}

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

Use the filtered body for encoding; current code reuses the stale body constant

requestInit.body is filtered, but the subsequent logic (content-type check and form-encoding) still references the original body, negating the filter. Use the updated requestInit.body (or mutate the local body) for all downstream checks/serialization.

-    const { method = 'GET', body } = requestInit;
+    let { method = 'GET', body } = requestInit;
@@
-    if (body && typeof body === 'object' && !(body instanceof FormData)) {
-      requestInit.body = filterUndefinedValues(body);
-    }
+    if (body && typeof body === 'object' && !(body instanceof FormData)) {
+      body = filterUndefinedValues(body as any);
+      requestInit.body = body as any;
+    }
@@
-    if (method !== 'GET' && !(body instanceof FormData) && !requestInit.headers.has('content-type')) {
+    if (method !== 'GET' && !(requestInit.body instanceof FormData) && !requestInit.headers.has('content-type')) {
       requestInit.headers.set('content-type', 'application/x-www-form-urlencoded');
     }
@@
-      requestInit.body = body
-        ? stringifyQueryParams(body as any as Record<string, string>, { keyEncoder: camelToSnake })
-        : body;
+      const payload = requestInit.body as any as Record<string, string> | undefined;
+      requestInit.body = payload ? stringifyQueryParams(payload, { keyEncoder: camelToSnake }) : payload;

Also applies to: 216-218, 224-230

*/
export function filterUndefinedValues<T>(obj: T): T {
// Return non-objects as-is (including FormData, arrays, primitives, etc.)
if (!obj || typeof obj !== 'object' || Array.isArray(obj) || obj instanceof FormData) {
Copy link
Member

Choose a reason for hiding this comment

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

If we want to handle instances of different classes not just FormData, we can do

Suggested change
if (!obj || typeof obj !== 'object' || Array.isArray(obj) || obj instanceof FormData) {
if (!obj || typeof obj !== 'object' || Object.getPrototypeOf(obj) !== Object.prototype) {

Copy link
Member Author

Choose a reason for hiding this comment

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

I think thats better, let me change it

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