Skip to content
Open
Show file tree
Hide file tree
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
52 changes: 51 additions & 1 deletion docs/guide/type-safety.md
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,7 @@ const url = routeUrl('/users/[id]', {
// /users/42?tab=activity#details
```

TypeScript checks the route and required parameter names. Patterns follow your filenames: `pages/users/[id].tsx`, `.vue`, or `.svelte` uses `/users/[id]`.
TypeScript checks the route, required parameter names, and the destination page's query schema. Patterns follow your filenames: `pages/users/[id].tsx`, `.vue`, or `.svelte` uses `/users/[id]`.

Parameters accept strings or numbers and are URL-encoded for you. Query values can be strings, numbers, booleans, or arrays. Arrays become repeated keys; `null` and `undefined` values are omitted.

Expand Down Expand Up @@ -241,6 +241,56 @@ import type { PageParams } from 'void/routes';
const { slug } = c.req.param() as PageParams<'/posts/[slug]'>;
```

### Page query

A loader can validate its query with `defineHandler.withValidator({ query })`. That schema types the page's links and its own reads.

```ts
// pages/admin/payments.server.ts
import { defineHandler } from 'void';
import { z } from 'zod';

const search = z.object({
status: z.enum(['paid', 'pending']),
page: z.coerce.number().default(1),
});

export const loader = defineHandler.withValidator({ query: search })(async (c, { query }) => {
return { payments: await listPayments(query) };
});
```

`routeUrl()` checks its `query` against that schema. A key outside it, a value outside it, or a missing required key is a type error:

```ts
import { routeUrl } from 'void/routes';

routeUrl('/admin/payments', { query: { status: 'paid' } });
routeUrl('/admin/payments', { query: { statsu: 'paid' } }); // Type error: no such key
routeUrl('/admin/payments', { query: { status: 'void' } }); // Type error: not in the schema
routeUrl('/admin/payments'); // Type error: `status` is required
```

`router.visit()` takes the same destination object and applies the same checks.

Read the values the loader validated with `useQuery()`. Pass the page pattern to type it.

```ts
import { useQuery } from '@void/react'; // @void/vue, @void/svelte, @void/solid

const query = useQuery<'/admin/payments'>();
// { status: 'paid' | 'pending'; page: number }

await router.visit({
pathname: '/admin/payments',
query: { ...query, status: 'pending', page: 1 },
});
```

The result is typed by the schema's output, so a coerced `page` is a number here even though the URL only carries text. Spreading it into a navigation changes one filter and keeps the rest.

A page without a query schema keeps accepting any `RouteQuery`, and `useQuery()` returns the request's query values as strings. Routes served by an HTTP handler are not checked, because one URL can serve several methods with different query schemas.

### Prerender paths

Annotate `getPrerenderPaths()` with `PageParams` to check that every path includes the page's required parameters:
Expand Down
4 changes: 4 additions & 0 deletions docs/reference/api/pages.md
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,7 @@ Imported from `"@void/vue"`.
| `Link` | Vue component for SPA navigation. Renders `<a>` for GET, `<button>` for non-GET methods. Props: `href`, `method`, `data`, `prefetch`, `cacheFor`, `preserveScroll`, `preserveState`, `replace`, `reloadDocument`, `viewTransition`, `activeMatch`, `onNavigate`. Adds `aria-current="page"` and `data-void-active` to the link to the current page ([active links](../../guide/pages-routing/overview.md#active-links)), and `data-void-pending` to links to a page while it loads ([pending links](../../guide/pages-routing/overview.md#pending-links)). |
| `useRouter()` | Returns the Void Router with current route state (`url`, `path`, `query`, `params`) and navigation methods: `visit`, `refresh`, awaitable `prefetch`, `flush`, `flushAll`. |
| `useParams()` | Returns dynamic route params for the page currently being rendered. Pass the page's pattern as the type argument, such as `useParams<'/users/[id]'>()`, to type them. |
| `useQuery()` | Returns the query of the page currently being rendered, as its loader's query schema validated it. Pass the page's pattern as the type argument, such as `useQuery<'/admin/payments'>()`, to type it. Pages without a query schema return the request's query string values. | |
| `useNavigation()` | Returns pending navigation state: `{ state, location, method }`, where `state` is `"idle"`, `"loading"`, or `"submitting"` and `location` is the pending destination. |
| `useForm(url, defaults, options?)` | Typed reactive form helper bound to a page action URL. Returns `{ data, post, put, patch, delete, pending, errors, error, hasChanges, wasSuccessful, recentlySuccessful, reset, setError, clearErrors, clearError }`. |
| `useIslandForm(defaults)` | Form helper for island components. Same form state as `useForm()`, plus `submit(url, method)`. `post(url)`, `put(url)`, `patch(url)`, and `delete(url)` take the action URL and submit with `fetch()`. With [`routing.typedRoutes`](../config.md#routing-typedroutes), the URL is a [`RouteUrl`](./types.md#route-types). |
Expand Down Expand Up @@ -159,6 +160,7 @@ Imported from `"@void/react"`.
| `Link` | React component for SPA navigation. Renders `<a>` for GET, `<button>` for non-GET methods. Props: `href`, `method`, `data`, `prefetch`, `cacheFor`, `preserveScroll`, `preserveState`, `replace`, `reloadDocument`, `viewTransition`, `activeMatch`, `onNavigate`. Adds `aria-current="page"` and `data-void-active` to the link to the current page ([active links](../../guide/pages-routing/overview.md#active-links)), and `data-void-pending` to links to a page while it loads ([pending links](../../guide/pages-routing/overview.md#pending-links)). |
| `useRouter()` | Returns the Void Router with current route state (`url`, `path`, `query`, `params`) and navigation methods: `visit`, `refresh`, awaitable `prefetch`, `flush`, `flushAll`. React navigations are scheduled as transitions. |
| `useParams()` | Returns dynamic route params for the page currently being rendered. Pass the page's pattern as the type argument, such as `useParams<'/users/[id]'>()`, to type them. |
| `useQuery()` | Returns the query of the page currently being rendered, as its loader's query schema validated it. Pass the page's pattern as the type argument, such as `useQuery<'/admin/payments'>()`, to type it. Pages without a query schema return the request's query string values. | |
| `useNavigation()` | Returns pending navigation state: `{ state, location, method }`, where `state` is `"idle"`, `"loading"`, or `"submitting"` and `location` is the pending destination. |
| `useForm(url, defaults, options?)` | Form helper hook. Returns `{ data, setData, post, put, patch, delete, pending, errors, error, hasChanges, wasSuccessful, recentlySuccessful, reset, setError, clearErrors, clearError }`. |
| `useIslandForm(defaults)` | Form helper hook for island components. Same form state as `useForm()`. `post(url)`, `put(url)`, `patch(url)`, and `delete(url)` take the action URL and submit with `fetch()`. With [`routing.typedRoutes`](../config.md#routing-typedroutes), the URL is a [`RouteUrl`](./types.md#route-types). |
Expand Down Expand Up @@ -251,6 +253,7 @@ Imported from `"@void/svelte"`.
| `useShared()` | Returns shared data. Middleware sets it with `c.set("shared", {...})`; a loader or action can update it. See [Shared data](../../guide/pages-routing/layouts.md#shared-data). |
| `useRouter()` | Returns the Void Router with current route state (`url`, `path`, `query`, `params`) and navigation methods: `visit`, `refresh`, awaitable `prefetch`, `flush`, `flushAll`. |
| `useParams()` | Returns dynamic route params for the page currently being rendered. Pass the page's pattern as the type argument, such as `useParams<'/users/[id]'>()`, to type them. |
| `useQuery()` | Returns the query of the page currently being rendered, as its loader's query schema validated it. Pass the page's pattern as the type argument, such as `useQuery<'/admin/payments'>()`, to type it. Pages without a query schema return the request's query string values. | |
| `useNavigation()` | Returns pending navigation state: `{ state, location, method }`, where `state` is `"idle"`, `"loading"`, or `"submitting"` and `location` is the pending destination. |

Svelte `Link` GET `data` is merged into the rendered `href` query string. Primitive values are serialized with `String(value)`, arrays become repeated keys, `null` and `undefined` are omitted, and nested objects throw. `prefetch` and `reloadDocument` are GET-only and throw for mutation links.
Expand Down Expand Up @@ -305,6 +308,7 @@ Imported from `"@void/solid"`.
| `useShared()` | Returns shared data. Middleware sets it with `c.set("shared", {...})`; a loader or action can update it. See [Shared data](../../guide/pages-routing/layouts.md#shared-data). |
| `useRouter()` | Returns the Void Router with current route state (`url`, `path`, `query`, `params`) and navigation methods: `visit`, `refresh`, awaitable `prefetch`, `flush`, `flushAll`. |
| `useParams()` | Returns dynamic route params for the page currently being rendered. Pass the page's pattern as the type argument, such as `useParams<'/users/[id]'>()`, to type them. |
| `useQuery()` | Returns the query of the page currently being rendered, as its loader's query schema validated it. Pass the page's pattern as the type argument, such as `useQuery<'/admin/payments'>()`, to type it. Pages without a query schema return the request's query string values. | |
| `useNavigation()` | Returns pending navigation state: `{ state, location, method }`, where `state` is `"idle"`, `"loading"`, or `"submitting"` and `location` is the pending destination. |

Solid `Link` GET `data` is merged into the rendered `href` query string. Primitive values are serialized with `String(value)`, arrays become repeated keys, `null` and `undefined` are omitted, and nested objects throw. `prefetch` and `reloadDocument` are GET-only and throw for mutation links.
Expand Down
Loading