fix(vue-form): generate an SSR-safe default formId #2259
main fromrefs/pull/2259/head·merged by crutchcorn(GitHub profile, opens in a new tab) 🎯 Changes#
Fixes #2254.
FormApi falls back to uuid() when no formId is passed, and the Vue adapter never passes one — so the id differs between the server render and the client render, and binding it (<form :id="form.formId">) produces a hydration mismatch.
This uses Vue's useId for the default instead, which is exactly what the other adapters already do:
react-form/src/useFormId.ts—React.useId, falling back touseUUIDon React 17preact-form/src/useFormId.ts—useIdfrompreact/hooks
Vue had no equivalent, so packages/vue-form/src/useFormId.ts adds one and useForm now passes formId: opts?.formId ?? fallbackFormId, mirroring react-form/src/useForm.tsx.
The version constraint#
useId was added in vue@3.5, but @tanstack/vue-form declares peerDependencies: { "vue": "^3.4.0" }. So a straight import { useId } from 'vue' would break 3.4 consumers — and a named import of a missing export is a bundler resolution error, not a runtime undefined. It is therefore read off the namespace and typed as optional, with the same reasoning as the existing React comment (webpack/webpack#14814):
const vueUseId: { useId?: () => string } = Vue
export function useFormId(): string {
const useId = vueUseId.useId
if (useId && Vue.getCurrentInstance()) {
return useId()
}
return uuid()
}
The getCurrentInstance() guard matters too: outside a component instance useId cannot produce a stable value and warns in dev, so useForm called outside setup keeps the old uuid behaviour rather than emitting a warning.
If you would rather bump the peer range to ^3.5.0 and call useId unconditionally, happy to switch — this way keeps 3.4 working.
✅ Checklist#
- I have followed the steps in the Contributing guide.
- I have tested this code locally with
pnpm test:pr.
🚀 Release Impact#
- This change affects published code, and I have generated a changeset.
- This change is docs/CI/dev-only (no release).
Verification#
packages/vue-form/tests/useFormId.test.tsx covers this. Run against main with only the test applied (i.e. reverting useForm.tsx), it fails on the two default-id cases while the explicit-id control still passes:
| Test | Without the fix | With the fix |
|---|---|---|
uses the provided formId when one is given | ✅ (control) | ✅ |
same default formId across identical renders | ❌ 2902fb86-… vs 752902fb-… | ✅ |
default formId matches between server and client | ❌ fb8639db-… vs 02fb8639-… | ✅ |
The server/client case renders through renderToString from vue/server-renderer (reached via the vue subpath export, so it adds no new dependency) and compares against a client render.
Also run locally:
pnpm test:pr→ passes (test:sherif,test:knip,test:docs,test:eslint,test:lib,test:types,test:build,build)- full
@tanstack/vue-formsuite → 31 passed, no type errors
Disclosure: I used an AI assistant while investigating and preparing this change, including running the verification above.
Summary by CodeRabbit#
- New Features
- Added a new
useFormIdcomposable for generating SSR-safe, stable form identifiers. useFormnow defaults to an auto-generatedformIdwhen none is provided.
- Added a new
- Bug Fixes
- Prevented mismatches between server-rendered and client-hydrated form IDs.
- Ensured safe ID generation when
useIdisn’t available (including non-component usage).
- Tests
- Added Vitest coverage for provided IDs, deterministic defaults, and SSR/client consistency (including hydration without warnings).
- 1
Actionable comments posted: 1
🧹 Nitpick comments (1)
packages/vue-form/tests/useFormId.test.tsx (1)
39-47: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winExercise actual hydration, not only independent renders.
This compares SSR HTML with a new client render, but never mounts a client app onto the server markup. Hydrate the server-rendered container and assert the ID remains unchanged without hydration warnings.
🤖 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/vue-form/tests/useFormId.test.tsx` around lines 39 - 47, Update the test around the SSR render and client ID assertion to hydrate a Vue app onto the server-rendered markup instead of independently calling render(Comp). Mount the client app with hydration enabled using the existing server HTML container, capture or assert that no hydration warnings occur, and verify the hydrated form element retains the server-generated ID.🤖 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/vue-form/src/useFormId.ts`: - Around line 18-23: Update useFormId so supported Vue 3.4 environments cannot produce different server/client IDs: either raise the package’s Vue peer/support requirement to Vue 3.5+ and rely on vueUseId.useId, or replace the uuid() fallback with a deterministic SSR-aware ID generator while preserving the existing useId path. --- Nitpick comments: In `@packages/vue-form/tests/useFormId.test.tsx`: - Around line 39-47: Update the test around the SSR render and client ID assertion to hydrate a Vue app onto the server-rendered markup instead of independently calling render(Comp). Mount the client app with hydration enabled using the existing server HTML container, capture or assert that no hydration warnings occur, and verify the hydrated form element retains the server-generated ID.🪄 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 Plus
Run ID:
9f6168d0-4522-4573-8a99-8b17fdc2589f📥 Commits
Reviewing files that changed from the base of the PR and between 5d1128141a705ebb24ade1275b3117bb4c8b1bdc and 370716142834a1b08b18e6fa6ef6756180efd09a.
📒 Files selected for processing (4)
.changeset/lucky-donkeys-shout.mdpackages/vue-form/src/useForm.tsxpackages/vue-form/src/useFormId.tspackages/vue-form/tests/useFormId.test.tsx
@@ -0,0 +3,21 @@3+4+/**5+ * `useId` was added in vue@3.5, but this package supports `vue@^3.4.0`. It is6+ * read off the namespace, typed as optional, rather than imported by name: a7+ * named import would make bundlers fail to resolve it on 3.4.8+ * Read more: https://github.com/webpack/webpack/issues/148149+ */10+const vueUseId: { useId?: () => string } = Vue11+12+/**13+ * Returns an SSR-safe id for the form, so the server-rendered markup and the14+ * client hydration agree on it. Falls back to a random uuid when `useId` is15+ * unavailable, or when called outside of a component instance, where `useId`16+ * cannot produce a stable value.17+ */18+export function useFormId(): string {19+ const useId = vueUseId.useId20+ if (useId && Vue.getCurrentInstance()) {21+ return useId()22+ }23+ return uuid()🎯 Functional Correctness | 🟠 Major | 🏗️ Heavy lift
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash set -euo pipefail echo "== files ==" git ls-files | rg '(^|/)useFormId\.ts$|package\.json$|packages/vue-form|vue-useId|useId|useUUID' || true echo "== useFormId ==" if [ -f packages/vue-form/src/useFormId.ts ]; then cat -n packages/vue-form/src/useFormId.ts fi echo "== package manifests relevant ==" for f in package.json packages/vue-form/package.json; do if [ -f "$f" ]; then echo "-- $f" jq '{name,version,type,scripts,peerDependencies,dependencies,devDependencies,engines}' "$f" fi done echo "== references to useFormId ==" rg -n "useFormId|useid|useId|uuid\\(|vueUseId|Vue\\.use" -S .Repository: TanStack/form
Length of output: 11353
🌐 Web query:
Vue 3.4 useId not exported composition api helper useId💡 Result:
The useId composable was not exported or available in Vue 3.4 [1][2][3]. It was introduced as a new API in Vue 3.5 [2][3]. If you are using Vue 3.4 and attempt to import useId from 'vue', it will result in an error indicating that the export cannot be found [4]. To use this functionality, you must upgrade your project to Vue 3.5 or later [2][3]. In versions prior to 3.5, developers typically used custom implementations or relied on utilities provided by third-party libraries (such as Nuxt or Quasar) to generate unique IDs [2].
Citations:
- 1: https://github.com/vuejs/blog/blob/78b4193b/posts/vue-3-5.md
- 2: https://vue-land.github.io/faq/unique-element-ids
- 3: https://blog.vuejs.org/posts/vue-3-5
- 4: https://github.com/tailwindlabs/headlessui/discussions/3474
🌐 Web query:
Vue 3.5 useId SSR stable server client ID documentation💡 Result:
Vue 3.5 introduced the useId composable to generate unique, stable IDs that remain consistent between server-side rendering (SSR) and client-side hydration [1][2]. This feature addresses long-standing challenges in SSR, such as hydration mismatches caused by inconsistent ID generation [1][3]. Key features and behavior: - Stability: useId produces IDs that are guaranteed to match between server and client renders [1][4]. It achieves this by tracking the component tree structure and the positions of asynchronous boundaries (e.g., async components, async setup, and serverPrefetch) to ensure counters are synchronized [4][2]. - Usage: The API is straightforward to implement, requiring no arguments to return a unique string ID [1][3]: - Customization: IDs are unique per application instance [4]. By default, they use a prefix of v- (e.g., v:1-2-3), which can be customized at the application level using app.config.idPrefix [4][3]. Important considerations: - Async Boundaries: While useId is designed to be robust, edge cases involving asynchronous logic—such as the use of onServerPrefetch or treeshaking patterns in frameworks like Nuxt—have historically caused hydration issues when the server and client treat async boundaries differently [5][6]. These issues are tracked in the Vue core repository and are typically addressed by ensuring the component tree structure remains identical across environments [5][6]. - Legacy Alternatives: Before Vue 3.5, libraries like Nuxt and Quasar implemented their own ID generation strategies to handle SSR [2]. If you are using Vue 3.5 or later, the built-in useId is the recommended approach to replace those custom solutions [2].
Citations:
- 1: https://blog.vuejs.org/posts/vue-3-5
- 2: https://vue-land.github.io/faq/unique-element-ids
- 3: https://blog.ninja-squad.com/2024/09/05/what-is-new-vue-3.5
- 4: https://github.com/vuejs/core/pull/11404
- 5: https://github.com/vuejs/core/issues/12102
- 6: https://github.com/vuejs/core/issues/12591
Vue 3.4 supports still generate SSR/client mismatched form IDs.
useId()is unavailable in Vue 3.4, so package authors using@tanstack/vue-formwith the supported range fall back touuid()and can get different server/clientformIds. Either raise the Vue 3.4 support edge to Vue 3.5+ for the safe default, or replace the random UUID fallback with a deterministic SSR-aware implementation.🤖 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/vue-form/src/useFormId.ts` around lines 18 - 23, Update useFormId so supported Vue 3.4 environments cannot produce different server/client IDs: either raise the package’s Vue peer/support requirement to Vue 3.5+ and rely on vueUseId.useId, or replace the uuid() fallback with a deterministic SSR-aware ID generator while preserving the existing useId path.Thanks — both points addressed.
On the hydration test (nitpick): fair, the test compared SSR html against a fresh client render and never actually hydrated.
f3474c79mounts the server markup withcreateSSRApp().mount()and asserts Vue raises no hydration mismatch. It's a stronger test: revertinguseForm.tsxnow fails 3 of the 4 cases (the new hydration one included) while the explicit-formIdcontrol still passes.On vue@3.4 still producing mismatched ids: that's accurate, and it is a deliberate limitation rather than something the patch can solve. 3.4 has no
useId, and Vue exposes nothing else that is stable across the server and client render, so on 3.4 there is no correct id to fall back to — only the existinguuid()behaviour, which this PR leaves untouched. The net effect is 3.5+ gets fixed and 3.4 is no worse than today.The alternative is bumping
peerDependencies.vueto^3.5.0and callinguseIdunconditionally, which fixes it everywhere the package claims to support at the cost of dropping 3.4. That's a maintainer call on the support window, so I kept the compatible option and am happy to switch if you'd prefer the bump.crutchcorn(GitHub profile, opens in a new tab) approved these changes
Thanks for this!
View your CI Pipeline Execution ↗ for commit f3474c79beb28839b7a83e858e56c13e977d8eaa
Command Status Duration Result nx affected --targets=test:sherif,test:knip,tes...✅ Succeeded 2m 38s View ↗ nx run-many --target=build --exclude=examples/**✅ Succeeded 7s View ↗
☁️ Nx Cloud last updated this comment at
2026-08-01 08:33:56UTCMore templates
- @tanstack/form-example-angular-array
- @tanstack/form-example-angular-large-form
- @tanstack/form-example-angular-multi-step-wizard
- @tanstack/form-example-angular-simple
- @tanstack/form-example-angular-standard-schema
- @tanstack/form-example-lit-array
- @tanstack/form-example-lit-large-form
- @tanstack/form-example-lit-multi-step-wizard
- @tanstack/form-example-lit-simple
- @tanstack/form-example-lit-standard-schema
- @tanstack/form-example-lit-ui-libraries
- @tanstack/form-example-preact-multi-step-wizard
- @tanstack/form-example-preact-simple
- @tanstack/form-example-solid-array
- @tanstack/form-example-solid-devtools
- @tanstack/form-example-solid-large-form
- @tanstack/form-example-solid-multi-step-wizard
- @tanstack/form-example-solid-simple
- @tanstack/form-example-solid-standard-schema
- @tanstack/form-example-react-array
- @tanstack/form-example-react-compiler
- @tanstack/form-example-react-composition
- @tanstack/form-example-react-devtools
- @tanstack/form-example-react-dynamic
- @tanstack/form-example-react-expo
- @tanstack/field-errors-from-form-validators
- @tanstack/form-example-react-large-form
- @tanstack/form-example-react-multi-step-wizard
- @tanstack/form-example-react-next-server-actions
- @tanstack/form-example-react-next-server-actions-zod
- @tanstack/form-example-react-query-integration
- @tanstack/form-example-remix
- @tanstack/form-example-react-simple
- @tanstack/form-example-react-standard-schema
- @tanstack/form-example-react-tanstack-start
- @tanstack/form-example-react-ui-libraries
- @tanstack/form-example-svelte-array
- @tanstack/form-example-svelte-large-form
- @tanstack/form-example-svelte-multi-step-wizard
- @tanstack/form-example-svelte-simple
- @tanstack/form-example-svelte-standard-schema
- @tanstack/form-example-vue-array
- @tanstack/form-example-vue-multi-step-wizard
- @tanstack/form-example-vue-simple
- @tanstack/form-example-vue-standard-schema
@tanstack/angular-form
npm i https://pkg.pr.new/@tanstack/angular-form@2259@tanstack/form-core
npm i https://pkg.pr.new/@tanstack/form-core@2259@tanstack/form-devtools
npm i https://pkg.pr.new/@tanstack/form-devtools@2259@tanstack/lit-form
npm i https://pkg.pr.new/@tanstack/lit-form@2259@tanstack/preact-form
npm i https://pkg.pr.new/@tanstack/preact-form@2259@tanstack/react-form
npm i https://pkg.pr.new/@tanstack/react-form@2259@tanstack/react-form-devtools
npm i https://pkg.pr.new/@tanstack/react-form-devtools@2259@tanstack/react-form-nextjs
npm i https://pkg.pr.new/@tanstack/react-form-nextjs@2259@tanstack/react-form-remix
npm i https://pkg.pr.new/@tanstack/react-form-remix@2259@tanstack/react-form-start
npm i https://pkg.pr.new/@tanstack/react-form-start@2259@tanstack/solid-form
npm i https://pkg.pr.new/@tanstack/solid-form@2259@tanstack/solid-form-devtools
npm i https://pkg.pr.new/@tanstack/solid-form-devtools@2259@tanstack/svelte-form
npm i https://pkg.pr.new/@tanstack/svelte-form@2259@tanstack/vue-form
npm i https://pkg.pr.new/@tanstack/vue-form@2259commit:
f3474c7:warning: Please install the
to ensure uploads and comments are reliably processed by Codecov.
Codecov Report#
:x: Patch coverage is
87.50000%with1 linein your changes missing coverage. Please review. :white_check_mark: Project coverage is 95.19%. Comparing base (6892ed0) to head (f3474c7). :warning: Report is 260 commits behind head on main.Files with missing lines Patch % Lines packages/vue-form/src/useFormId.ts 83.33% 1 Missing :warning: :exclamation: Your organization needs to install the Codecov GitHub app to enable full functionality. Additional details and impacted files
@@ Coverage Diff @@ ## main #2259 +/- ## ========================================== + Coverage 90.35% 95.19% +4.83% ========================================== Files 38 4 -34 Lines 1752 104 -1648 Branches 444 6 -438 ========================================== - Hits 1583 99 -1484 + Misses 149 5 -144 + Partials 20 0 -20:umbrella: View full report in Codecov by Harness. :loudspeaker: Have feedback on the report? Share it here.
:rocket: New features to boost your workflow:
- :snowflake: Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
- :package: JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.
crutchcorn(GitHub profile, opens in a new tab) closed this
Sign in to join this conversation.
No actionable comments were generated in the recent review. 🎉
ℹ️ Recent review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro Plus
Run ID:
9914d3e4-6256-49f6-8fac-5247e5f52502📥 Commits
Reviewing files that changed from the base of the PR and between 370716142834a1b08b18e6fa6ef6756180efd09a and f3474c79beb28839b7a83e858e56c13e977d8eaa.
📒 Files selected for processing (1)
packages/vue-form/tests/useFormId.test.tsx🚧 Files skipped from review as they are similar to previous changes (1)
📝 Walkthrough
Walkthrough#
Vue form defaults now use a component-aware, SSR-safe identifier composable with UUID fallback.
useFormpreserves explicit IDs, and tests cover deterministic rendering, SSR/client consistency, and hydration.Changes#
Vue form identifier flow
packages/vue-form/src/useFormId.ts,packages/vue-form/src/useForm.tsxuseId-based form IDs with UUID fallback, and passes the generated ID toFormApiwhen no explicitformIdis provided.packages/vue-form/tests/useFormId.test.tsx,.changeset/lucky-donkeys-shout.mdEstimated code review effort: 2 (Simple) | ~10 minutes
Sequence Diagram(s)#
🚥 Pre-merge checks | ✅ 4 | ❌ 1
❌ Failed checks (1 warning)#
✅ Passed checks (4 passed)
#2254by generating a stable default formId with useId and falling back for Vue 3.4/component limits.✨ 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