TanStackT
TanStack5mo ago
24 replies
colossal-harlequin

Recommendations for Zod validated Nested Search Params

I've reviewed the docs on Search Params + Zod several times and haven't really found a nice way to deal with typing a nested object in my URL state.

I made this minimal example (see the /about route) that shows off some of the tricky pieces I can't seem to work around:

1. any params that use the fallback() function from @tanstack/zod-adapter force their key into the URL (which is just preference, but clutters up the URL bar)
Should I just accept that the URL is going to be a little ugly? Or do I have to give up the type safety to achieve it?

2. nested objects that use fallback() have to wrap every single key in the generic function, leading to defining the default values N times
Are deeply nested search params considered a good practice? Or is there some way to avoid needing to duplicate default values over and over?

To demonstrate the nesting issue:
  // this:
  nested_object: z
    .object({
      slightly_nested: z.boolean().catch(false),
      more_nesting: z.object({
        deeply_nested: z.string().catch(''),
      }),
    })
    .optional(),

  // turns into this with fallback:
  fallback_nested_object: fallback(
    z
      .object({
        slightly_nested: fallback(z.boolean(), false).default(false),
        more_nesting: fallback(
          z.object({
            deeply_nested: fallback(z.string(), '').default(''),
          }),
          {
            deeply_nested: '',
          }
        ).default({
          deeply_nested: '',
        }),
      })
      .optional(),
    {
      slightly_nested: false,
      more_nesting: {
        deeply_nested: '',
      },
    }
  ).default({
    slightly_nested: false,
    more_nesting: {
      deeply_nested: '',
    },
  }),


Curious if there is a better way!

SOLVED: upgrading to Zod v4 removes the need to use the fallback generic function.
StackBlitzKyle Gill
Run official live example code for Router Quickstart File Based, created by Tanstack on StackBlitz
TanStack Router + Zod (Deep nesting params with fallback) - StackBlitz
Was this page helpful?