Skip to content

docs: validation path params #3938

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

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions docs/router/framework/react/guide/path-params.md
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,36 @@ function Component() {

Notice that the function style is useful when you need to persist params that are already in the URL for other routes. This is because the function style will receive the current params as an argument, allowing you to modify them as needed and return the final params object.

## Validate Path Params

You can ensure your route parameters are correctly formatted. This helps prevent invalid inputs and improves type safety.

<ul>
<li>Why Validate Path Params?</li>
<ul>
<li>Prevents invalid route parameters before they reach your component</li>
<li>Ensures correct data types, reducing runtime errors</li>
<li>Improves maintainability, especially when working with APIs that expect specific formats</li>
</ul>
</li>
</ul>

Here's an example using the Zod library (but feel free to use any validation library you want) to both validate and type the search params in a single step:

```tsx
export const Route = createFileRoute('/posts/$postId')({
component: PostComponent,
params: z.object({
postId: z.string().uuid(), // Ensures postId is a valid UUID
}),
})

function PostComponent() {
const { postId } = Route.useParams()
return <div>Viewing post with ID: {postId}</div>
}
```

## Allowed Characters

By default, path params are escaped with `encodeURIComponent`. If you want to allow other valid URI characters (e.g. `@` or `+`), you can specify that in your [RouterOptions](../api/router/RouterOptionsType.md#pathparamsallowedcharacters-property)
Expand Down