-
Notifications
You must be signed in to change notification settings - Fork 386
feat(clerk-js): Filter undefined values from request body #6776
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Conversation
🦋 Changeset detectedLatest commit: 3d74404 The changes in this PR will be included in the next version bump. This PR includes changesets to release 0 packagesWhen 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 |
The latest updates on your projects. Learn more about Vercel for GitHub.
|
WalkthroughAdds a shallow 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
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Poem
Pre-merge checks and finishing touches✅ Passed checks (3 passed)
✨ Finishing touches
🧪 Generate unit tests
📜 Recent review detailsConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Disabled knowledge base sources:
📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
⏰ 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)
Comment |
@clerk/agent-toolkit
@clerk/astro
@clerk/backend
@clerk/chrome-extension
@clerk/clerk-js
@clerk/dev-cli
@clerk/elements
@clerk/clerk-expo
@clerk/expo-passkeys
@clerk/express
@clerk/fastify
@clerk/localizations
@clerk/nextjs
@clerk/nuxt
@clerk/clerk-react
@clerk/react-router
@clerk/remix
@clerk/shared
@clerk/tanstack-react-start
@clerk/testing
@clerk/themes
@clerk/types
@clerk/upgrade
@clerk/vue
commit: |
There was a problem hiding this 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 redundanttransfer
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 stringifyThe 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.
📒 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
Avoidany
type - preferunknown
when type is uncertain, then narrow with type guards
Useinterface
for object shapes that might be extended
Usetype
for unions, primitives, and computed types
Preferreadonly
properties for immutable data structures
Useprivate
for internal implementation details
Useprotected
for inheritance hierarchies
Usepublic
explicitly for clarity in public APIs
Preferreadonly
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
Useconst assertions
for literal types:as const
Usesatisfies
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 ...
Noany
types without justification
Proper error handling with typed errors
Consistent use ofreadonly
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: confirmnormalizeUnsafeMetadata
semanticsPassing the entire
finalParams
intonormalizeUnsafeMetadata
is tidy; confirm it only transformsunsafeMetadata
and doesn’t touch captcha fields or other params.
614-617
: LGTM: update body build is consistent and defers undefined filtering to fapiClientAlso applies to: 619-619
632-634
: LGTM: password body build mirrors create/update patternAlso 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 failFile: .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).
if (body && typeof body === 'object' && !(body instanceof FormData)) { | ||
requestInit.body = filterUndefinedValues(body); | ||
} | ||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
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) { |
There was a problem hiding this comment.
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
if (!obj || typeof obj !== 'object' || Array.isArray(obj) || obj instanceof FormData) { | |
if (!obj || typeof obj !== 'object' || Object.getPrototypeOf(obj) !== Object.prototype) { |
There was a problem hiding this comment.
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
…imple objects correctly
Description
Removes all undefined values from the
body
of requests fired throughfapiClient
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 takenull
|''
as valid valuesChecklist
pnpm test
runs as expected.pnpm build
runs as expected.Type of change
Summary by CodeRabbit