fix(router-core): safely format Standard Schema validation issues #7782
main fromrefs/pull/7782/head·opened Closes #7779.
Problem#
Two places serialize Standard Schema validator issues the same way:
execValidatorinstart-client-core/src/createServerFn.tsdidthrow new Error(JSON.stringify(result.issues, undefined, 2)).validateSearchinrouter-core/src/router.tsdidthrow new SearchParamError(JSON.stringify(result.issues, undefined, 2), { cause: result }).
The Standard Schema spec allows an issue path to contain any PropertyKey, and a segment can be either a raw key or a { key } object. JSON.stringify throws on a symbol key or a bigint, and on any circular reference an issue object happens to carry. When that happens the thrown error is the serializer's error, not the validation failure, so the actual reason the input was rejected is lost right at the point a developer needs it.
Approach#
I started by looking at what a "safe" version of the existing output would be, and a plain JSON.stringify with a replacer that drops non-serializable values felt wrong: it keeps the JSON shape but still leaks the whole internal issue object, and the output is noisy. The useful information in an issue is really just the message and the path, so I settled on a small formatter that reads only those two fields and never touches anything else on the object. That also sidesteps the circular-reference case for free, because it never walks into arbitrary properties.
The path rendering took a couple of tries. A dot path like user.name reads well until a key legitimately contains a dot or a bracket, at which point a.b is ambiguous between one key "a.b" and the nested path a -> b. So each segment is bracketed and quoted with JSON.stringify of the key: ["user"]["name"][0]. Numbers render as [0] so array indices stay readable, and symbols render via String(key) instead of throwing. Because every string key goes through JSON.stringify rather than being used to index into an object, a key named __proto__ is only ever printed as text and can never walk the prototype chain. Root issues with no path render as (root).
The formatter lives in router-core (src/validationError.ts) so both call sites share one implementation. The issue asks to avoid growing the public router-core surface unless there is a supported use case. start-client-core consumes it across the package boundary through workspace:*, which resolves through the published exports map, so it does need to be reachable. I exported it from the main entry to match how existing shared helpers like isRedirect and parseRedirect are shared today. If you would rather keep it off the primary barrel and expose it through a dedicated subpath instead, I am happy to move it.
I also added an optional path field to AnyStandardSchemaValidateIssue in validators.ts so the formatter can read it in a typed way. It is optional, so it does not change any existing usage.
Tests#
packages/router-core/tests/validationError.test.ts covers:
- root issues with no path,
- nested string paths,
- numeric (array index) segments,
{ key }object segments,- a literal dotted key vs a real nested path (to prove they do not collide),
__proto__rendered as text without prototype access,- symbol segments,
- multiple issues joined on separate lines,
- a circular issue object, which previously threw and now formats cleanly.
I have not added the server-function E2E scenarios across multiple Standard Schema libraries or the bundle-size run mentioned in the issue, since those touch a wider surface. Happy to follow up in a separate PR if you would like them in here.
Summary by CodeRabbit#
New Features
- Added clearer validation error messages with readable field paths, including nested fields and list items.
- Exposed a validation-error formatting utility for consistent error presentation.
Bug Fixes
- Validation errors from server functions and asynchronous checks are now formatted consistently instead of displayed as raw JSON.
- Improved handling for root-level, symbol-based, and unusual field names without causing additional errors.
- 1
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. Inline comments: In `@packages/start-client-core/src/createServerFn.ts`: - Line 904: Update the if statement handling result.issues to use curly braces around the throw statement, following the project’s control-flow style guidelines.🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID:
7833e68a-61cf-4f6c-8e09-e95351fc1014📥 Commits
Reviewing files that changed from the base of the PR and between a3e24c35a58d9ac149a05d6321f68aa5d541b6b4 and 86fde1c1a5e7858150291087095f04e2bc21e9c5.
📒 Files selected for processing (6)
packages/router-core/src/index.tspackages/router-core/src/router.tspackages/router-core/src/validationError.tspackages/router-core/src/validators.tspackages/router-core/tests/validationError.test.tspackages/start-client-core/src/createServerFn.ts
packages/start-client-core/src/createServerFn.ts line 904@@ -897,5 +901,4 @@897901 if ('~standard' in validator) {898902 const result = await validator['~standard'].validate(input)899903900- if (result.issues)901- throw new Error(JSON.stringify(result.issues, undefined, 2))904+ if (result.issues) throw new Error(formatValidationError(result.issues))📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win
Add curly braces to the
ifstatement.Per the project's coding guidelines for
**/*.{ts,tsx,js,jsx}: "Always use curly braces forif,else, loops, and similar control statements. Never write one-line bodies likeif (foo) x = 1."♻️ Proposed fix
- if (result.issues) throw new Error(formatValidationError(result.issues)) + if (result.issues) { + throw new Error(formatValidationError(result.issues)) + }📝 Committable suggestion
‼️ IMPORTANT Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
if (result.issues) { throw new Error(formatValidationError(result.issues)) }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/start-client-core/src/createServerFn.ts` at line 904, Update the if statement handling result.issues to use curly braces around the throw statement, following the project’s control-flow style guidelines.Source: Coding guidelines
TemRevil(GitHub profile, opens in a new tab) linked this to fix #7779
Sign in to join this conversation.
📝 Walkthrough
Walkthrough#
Adds a shared Standard Schema validation-error formatter, exposes it from
router-core, and uses it for router search and server-function validation failures. The formatter supports structured paths, special keys, symbols, multiple issues, and non-serializable issue objects.Changes#
Validation error formatting
packages/router-core/src/validators.ts,packages/router-core/src/validationError.ts,packages/router-core/src/index.ts,packages/router-core/tests/validationError.test.tspackages/router-core/src/router.tsformatValidationErrorfor asynchronous search-parameter validation failures.packages/start-client-core/src/createServerFn.tsformatValidationErrorwhen server-function validation returns issues.Estimated code review effort: 3 (Moderate) | ~20 minutes
Suggested labels:
package: router-core🚥 Pre-merge checks | ✅ 3 | ❌ 2
❌ Failed checks (2 warnings)#
✅ Passed checks (3 passed)
✨ Finishing Touches
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
❤️ Share