Repository navigation
Replies: 2 comments
|
When Zod validation fails on route params, TanStack Router throws a path matching error (the route doesn't match). To show a NotFound component instead, use the Option 1: Use
|
|
When import { createFileRoute, notFound } from '@tanstack/react-router'
import { z } from 'zod'
const ALLOWED_TERMS = ['privacy', 'service', 'marketing'] as const
const paramsSchema = z.object({ term: z.enum(ALLOWED_TERMS) })
export const Route = createFileRoute('/$term')({
params: {
parse: (raw) => {
const result = paramsSchema.safeParse(raw)
if (!result.success) throw notFound()
return result.data // term: 'privacy' | 'service' | 'marketing'
},
stringify: (params) => params,
},
notFoundComponent: NotFound, // optional; otherwise the nearest parent / root notFoundComponent handles it
component: RouteComponent,
})I tested this with On recent versions there's also an experimental option: return About the flicker: in a client-only setup, Docs: Not Found Errors |
Uh oh!
There was an error while loading. Please reload this page.
I'm using TanStack Start with Zod validation for route params, and I want to show a NotFound component (or throw a notFound error) when param validation fails.
Here's my setup:
What I want to achieve:
When a user navigates to /agreement/invalid-term (where "invalid-term" is not in the allowed enum), I want to:
What I've tried:
I attempted to use errorComponent with PathParamError check, but it doesn't work as expected - NotFound component is only briefly rendered, and then it changes to the default error component. I guess that the error is indeed a PathParamError instance initially, but it seems like the error boundary is re-rendering with a different error type afterward.
Questions:
All reactions