---
url: /frontend/validation/query.md
description: >-
  Validate search params on a page route with the third defineRoute type
  argument - the query shape directly, with numeric and boolean coercion and the
  inline object rule.
---

The third type argument to a page's `defineRoute` **is** the URL search params shape.
It takes the query keys directly - there is no `{ query: ... }` wrapper on a page route.

```ts [pages/users/index.ts]
import { defineRoute } from "_/pages";

export default defineRoute<"users", [], {
  page?: number;
  sort?: "name" | "created";
  active?: boolean;
}>();
```

A request to `/users?page=abc` throws a `ValidationError` with `target: "query"`
before `page.tsx` renders. A request to `/users?page=2&sort=name` passes.

Compare with an API route, where the query target is nested under the handler:

```ts
// API route - the target object says which part of the request this is
GET<{ query: { page?: number } }>(async (ctx) => {
  const { page } = ctx.validated.query;
});
```

A page route has no target object because params already use the tuple and query is
the only other thing the router provides.

## Coercion

Query values arrive as strings, or arrays for repeated keys. KosmoJS coerces the
properties typed as `number` or `boolean` before validating:

| Declared | `"2"` | `"true"` | `"abc"` |
|---|---|---|---|
| `number` | `2` | fails | fails |
| `boolean` | fails | `true` | fails |
| `string` | `"2"` | `"true"` | `"abc"` |

Arrays of numbers and booleans are coerced element by element. A value that does not
match the expected wire form stays a string and fails cleanly.

## The object is open

Query objects accept keys you did not declare. Browsers, proxies and analytics add
parameters; they do not fail the page.

```ts
export default defineRoute<"search", [], {
  q?: string;
  page?: number;
}>();
```

`/search?q=router&page=2&utm_source=docs` passes; `q` and `page` are validated,
`utm_source` is ignored.

## Keep the object inline

The third type argument must be an inline type literal. An alias is rejected when the
route is parsed:

```ts
// ✅
export default defineRoute<"users", [], {
  page?: number;
}>();

// ❌ rejected
type Query = { page?: number };
export default defineRoute<"users", [], Query>();
```

The *values* may be aliases or imported types - it is the outer `{ ... }` that must
stay inline.

## Reading the values

Read validated query values with `useSearchParams()` from `_/use` in every framework.
It returns coerced numbers and booleans for the keys declared in the page's `index.ts`.

```tsx
import { useSearchParams } from "_/use";

const query = useSearchParams<"users">();
// read query.page during render
```

The framework's own search-param hook still returns raw router values:
`useSearchParams()` from `react-router` or `@solidjs/router`, and `useRoute().query` in Vue.
[Hooks ›](/frontend/hooks.md#usesearchparams)
