Skip to content

Commit 0ebaeb4

Browse files
committed
feat(routes): support bracket patterns in typed routing APIs
1 parent 66b53d6 commit 0ebaeb4

26 files changed

Lines changed: 392 additions & 134 deletions

‎docs/guide/pages-routing/actions-and-forms.md‎

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -173,7 +173,7 @@ For dynamic routes, pass `params` in the options:
173173

174174
```ts
175175
// pages/users/[id].server.ts has an action
176-
const form = useForm('/users/:id', { name: '' }, { params: { id: '42' } });
176+
const form = useForm('/users/[id]', { name: '' }, { params: { id: '42' } });
177177
<Form form={form} method="put">{/* submits to /users/42 */}</Form>
178178
```
179179

@@ -209,7 +209,7 @@ Actions and forms keep the current scroll position when updating the page in pla
209209
Pass `preserveScroll: false` to reset scroll after an in-place update, or `true` to keep it even after a redirect:
210210

211211
```ts
212-
await action('/users/:id?update', {
212+
await action('/users/[id]?update', {
213213
params: { id: '42' },
214214
data: { name: 'Alice' },
215215
preserveScroll: false,
@@ -233,15 +233,15 @@ export const actions = {
233233
update: defineHandler.withValidator({
234234
body: updateUserSchema,
235235
})(async (c, { body }) => {
236-
const { id } = c.req.param() as PageParams<'/users/:id'>;
236+
const { id } = c.req.param() as PageParams<'/users/[id]'>;
237237
await db
238238
.update(users)
239239
.set(body)
240240
.where(eq(users.id, Number(id)));
241241
}),
242242

243243
delete: defineHandler(async (c) => {
244-
const { id } = c.req.param() as PageParams<'/users/:id'>;
244+
const { id } = c.req.param() as PageParams<'/users/[id]'>;
245245
await db.delete(users).where(eq(users.id, Number(id)));
246246
}),
247247
};
@@ -269,7 +269,7 @@ export const actions = {
269269
When a page exports named actions, append `?actionName` to the URL:
270270

271271
```ts
272-
const form = useForm('/users/:id?update', { name: '' }, { params: { id } });
272+
const form = useForm('/users/[id]?update', { name: '' }, { params: { id } });
273273
<Form form={form} method="put">{/* submits to /users/42?update */}</Form>
274274
```
275275

@@ -282,7 +282,7 @@ Use `action()` for a button or other mutation that does not need form state. It
282282
```ts
283283
import { action } from '@void/react'; // or "@void/vue", "@void/svelte", "@void/solid"
284284

285-
const result = await action('/users/:id?delete', {
285+
const result = await action('/users/[id]?delete', {
286286
params: { id: '42' },
287287
method: 'DELETE',
288288
});

‎docs/guide/pages-routing/head.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ export interface Props {
2020
}
2121

2222
export const loader = defineHandler<Props>(async (c) => {
23-
const { slug } = c.req.param() as PageParams<'/posts/:slug'>;
23+
const { slug } = c.req.param() as PageParams<'/posts/[slug]'>;
2424
const post = await getPost(slug);
2525
return { post };
2626
});

‎docs/guide/pages-routing/overview.md‎

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -164,7 +164,7 @@ import { Link } from "@void/react";
164164
import { routeUrl } from 'void/routes';
165165

166166
<Link href="/users">Users</Link>
167-
<Link href={routeUrl('/users/:id', { params: { id } })}>View</Link>
167+
<Link href={routeUrl('/users/[id]', { params: { id } })}>View</Link>
168168
```
169169

170170
```vue [Vue]
@@ -175,7 +175,7 @@ import { routeUrl } from 'void/routes';
175175
176176
<template>
177177
<Link href="/users">Users</Link>
178-
<Link :href="routeUrl('/users/:id', { params: { id } })">View</Link>
178+
<Link :href="routeUrl('/users/[id]', { params: { id } })">View</Link>
179179
</template>
180180
```
181181

@@ -186,15 +186,15 @@ import { routeUrl } from 'void/routes';
186186
</script>
187187
188188
<Link href="/users">Users</Link>
189-
<Link href={routeUrl('/users/:id', { params: { id } })}>View</Link>
189+
<Link href={routeUrl('/users/[id]', { params: { id } })}>View</Link>
190190
```
191191

192192
```tsx [Solid]
193193
import { Link } from "@void/solid";
194194
import { routeUrl } from 'void/routes';
195195

196196
<Link href="/users">Users</Link>
197-
<Link href={routeUrl('/users/:id', { params: { id } })}>View</Link>
197+
<Link href={routeUrl('/users/[id]', { params: { id } })}>View</Link>
198198
```
199199

200200
:::
@@ -313,7 +313,7 @@ import type { RouteDestination } from 'void/routes';
313313

314314
const router = useRouter();
315315
const profile = {
316-
pathname: '/users/:id',
316+
pathname: '/users/[id]',
317317
params: { id: 42 },
318318
query: { tab: 'activity' },
319319
} satisfies RouteDestination;
@@ -338,7 +338,7 @@ For dynamic route params, use `useParams()` from the same adapter package. Pass
338338
import { useParams } from '@void/react';
339339

340340
export default function PostPage() {
341-
const { id } = useParams<'/posts/:id'>(); // { id: string }
341+
const { id } = useParams<'/posts/[id]'>(); // { id: string }
342342
return <h1>Post {id}</h1>;
343343
}
344344
```
@@ -348,7 +348,7 @@ export default function PostPage() {
348348
<script setup lang="ts">
349349
import { useParams } from '@void/vue';
350350
351-
const params = useParams<'/posts/:id'>(); // { id: string }
351+
const params = useParams<'/posts/[id]'>(); // { id: string }
352352
</script>
353353
354354
<template>
@@ -361,7 +361,7 @@ const params = useParams<'/posts/:id'>(); // { id: string }
361361
<script lang="ts">
362362
import { useParams } from '@void/svelte';
363363
364-
const params = useParams<'/posts/:id'>(); // { id: string }
364+
const params = useParams<'/posts/[id]'>(); // { id: string }
365365
</script>
366366
367367
<h1>Post {params.id}</h1>
@@ -372,7 +372,7 @@ const params = useParams<'/posts/:id'>(); // { id: string }
372372
import { useParams } from '@void/solid';
373373

374374
export default function PostPage() {
375-
const params = useParams<'/posts/:id'>(); // { id: string }
375+
const params = useParams<'/posts/[id]'>(); // { id: string }
376376
return <h1>Post {params.id}</h1>;
377377
}
378378
```

‎docs/guide/ssg.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ Dynamic pages with `getPrerenderPaths()` are prerendered for the returned param
3434
// pages/blog/[slug].server.ts
3535
import type { PageParams } from 'void/routes';
3636

37-
export async function getPrerenderPaths(): Promise<PageParams<'/blog/:slug'>[]> {
37+
export async function getPrerenderPaths(): Promise<PageParams<'/blog/[slug]'>[]> {
3838
return [{ slug: 'hello-world' }, { slug: 'getting-started' }];
3939
}
4040
```

‎docs/guide/type-safety.md‎

Lines changed: 35 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -127,21 +127,21 @@ form.errors.foo; // ✗ TypeScript error
127127
[Named actions](./pages-routing/actions-and-forms#named-actions) work the same way. The `?actionName` suffix selects the right types for that action:
128128

129129
```ts
130-
const updateForm = useForm('/users/:id?update', { name: '' }, { params: { id } });
131-
const deleteForm = useForm('/users/:id?delete', { id: '' }, { params: { id } });
130+
const updateForm = useForm('/users/[id]?update', { name: '' }, { params: { id } });
131+
const deleteForm = useForm('/users/[id]?delete', { id: '' }, { params: { id } });
132132
// Each form's data and errors are typed from their respective validators
133133
```
134134

135135
The `action()` helper gets the same type checking. See [Actions & Forms](./pages-routing/actions-and-forms) for the full API.
136136

137137
## Typed URLs and Navigation
138138

139-
Use `routeUrl()` from `void/routes` to build URLs from your app's page, HTTP, and WebSocket route patterns. For a page at `pages/users/[id].tsx`, `.vue`, or `.svelte`, the pattern is `/users/:id`:
139+
Use `routeUrl()` from `void/routes` to build URLs from your app's page, HTTP, and WebSocket route patterns. For a page at `pages/users/[id].tsx`, `.vue`, or `.svelte`, the pattern is `/users/[id]`:
140140

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

144-
const url = routeUrl('/users/:id', {
144+
const url = routeUrl('/users/[id]', {
145145
params: { id: 42 },
146146
query: { tab: 'activity' },
147147
hash: 'details',
@@ -151,13 +151,15 @@ const url = routeUrl('/users/:id', {
151151

152152
Your editor autocompletes route patterns and parameter names. TypeScript checks that the route exists and all required parameters are supplied. Parameter values accept strings or numbers; Void encodes them for the URL. Query keys are chosen by your app, and values can be strings, numbers, booleans, or arrays of those values. Arrays become repeated query parameters; `null` and `undefined` values are omitted.
153153

154+
Use bracket patterns with `routeUrl()`, typed `fetch()`, WebSocket `connect()`, page actions, and `useParams()`.
155+
154156
Pass the returned string to `Link`, a plain `<a>`, or `c.redirect()`. For programmatic navigation and `c.rewrite()`, you can pass a destination object directly:
155157

156158
```ts
157159
import type { RouteDestination } from 'void/routes';
158160

159161
const profile = {
160-
pathname: '/users/:id',
162+
pathname: '/users/[id]',
161163
params: { id: 42 },
162164
query: { tab: 'activity' },
163165
hash: 'details',
@@ -166,56 +168,63 @@ const profile = {
166168

167169
Destination objects use the same parameter checking and URL encoding as `routeUrl()`. See [Pages Routing](./pages-routing/overview.md#typed-navigation) for links and router methods, and [Rewrites](../reference/api/rewrites.md#c-rewrite-destination) for server navigation.
168170

169-
For a catch-all page such as `pages/files/[...path].tsx`, `.vue`, or `.svelte`, use `/files/:path{.+}` and pass the full path as one value:
171+
For a catch-all page such as `pages/files/[...path].tsx`, `.vue`, or `.svelte`, use `/files/[...path]` and pass the full path as one value:
172+
173+
```ts
174+
routeUrl('/files/[...path]', { params: { path: 'docs/get started' } });
175+
// /files/docs/get%20started
176+
```
177+
178+
For an unnamed catch-all (`[...]`), pass its value under the `'*'` key:
170179

171180
```ts
172-
routeUrl('/files/:path{.+}', { params: { path: 'docs/get started' } });
181+
routeUrl('/files/[...]', { params: { '*': 'docs/get started' } });
173182
// /files/docs/get%20started
174183
```
175184

176185
### Page params
177186

178-
Pass a page's URL pattern as the type argument of `useParams()` to type the params it reads. For a page at `pages/users/[id].tsx`, `.vue`, or `.svelte`, the pattern is `/users/:id`:
187+
Pass a page's URL pattern as the type argument of `useParams()` to type the params it reads. For a page at `pages/users/[id].tsx`, `.vue`, or `.svelte`, the pattern is `/users/[id]`:
179188

180189
::: code-group
181190

182191
```tsx [React]
183192
import { useParams } from '@void/react';
184193

185-
const { id } = useParams<'/users/:id'>(); // id: string
186-
useParams<'/users/:id'>().idd; // Type error: no such param
187-
useParams<'/userz/:id'>(); // Type error: no page matches
194+
const { id } = useParams<'/users/[id]'>(); // id: string
195+
useParams<'/users/[id]'>().idd; // Type error: no such param
196+
useParams<'/userz/[id]'>(); // Type error: no page matches
188197
```
189198

190199
```vue [Vue]
191200
<script setup lang="ts">
192201
import { useParams } from '@void/vue';
193202
194-
const params = useParams<'/users/:id'>();
203+
const params = useParams<'/users/[id]'>();
195204
params.id; // string
196205
params.idd; // Type error: no such param
197-
useParams<'/userz/:id'>(); // Type error: no page matches
206+
useParams<'/userz/[id]'>(); // Type error: no page matches
198207
</script>
199208
```
200209

201210
```svelte [Svelte]
202211
<script lang="ts">
203212
import { useParams } from '@void/svelte';
204213
205-
const params = useParams<'/users/:id'>();
214+
const params = useParams<'/users/[id]'>();
206215
params.id; // string
207216
params.idd; // Type error: no such param
208-
useParams<'/userz/:id'>(); // Type error: no page matches
217+
useParams<'/userz/[id]'>(); // Type error: no page matches
209218
</script>
210219
```
211220

212221
```tsx [Solid]
213222
import { useParams } from '@void/solid';
214223

215-
const params = useParams<'/users/:id'>();
224+
const params = useParams<'/users/[id]'>();
216225
params.id; // string
217226
params.idd; // Type error: no such param
218-
useParams<'/userz/:id'>(); // Type error: no page matches
227+
useParams<'/userz/[id]'>(); // Type error: no page matches
219228
```
220229

221230
:::
@@ -229,7 +238,7 @@ On the server, `c.req.param('slug')` accepts any name. Read the params object th
229238
```ts
230239
import type { PageParams } from 'void/routes';
231240

232-
const { slug } = c.req.param() as PageParams<'/posts/:slug'>;
241+
const { slug } = c.req.param() as PageParams<'/posts/[slug]'>;
233242
```
234243

235244
### Prerender paths
@@ -240,7 +249,7 @@ On a dynamic page, annotate `getPrerenderPaths()` with `PageParams` for that pag
240249
// pages/blog/[slug].server.ts
241250
import type { PageParams } from 'void/routes';
242251

243-
export async function getPrerenderPaths(): Promise<PageParams<'/blog/:slug'>[]> {
252+
export async function getPrerenderPaths(): Promise<PageParams<'/blog/[slug]'>[]> {
244253
return [{ slug: 'hello-world' }];
245254
}
246255
```
@@ -282,7 +291,7 @@ import { routeUrl } from 'void/routes';
282291

283292
<Link href="/about">About</Link>
284293
<Link href={`/users/${user.id}?tab=activity`}>Profile</Link>
285-
<Link href={routeUrl('/users/:id', { params: { id } })}>Profile</Link>
294+
<Link href={routeUrl('/users/[id]', { params: { id } })}>Profile</Link>
286295
<Link href="/abuot">About</Link> // Type error: no route matches
287296
```
288297

@@ -295,7 +304,7 @@ import { routeUrl } from 'void/routes';
295304
<template>
296305
<Link href="/about">About</Link>
297306
<Link :href="`/users/${user.id}?tab=activity`">Profile</Link>
298-
<Link :href="routeUrl('/users/:id', { params: { id } })">Profile</Link>
307+
<Link :href="routeUrl('/users/[id]', { params: { id } })">Profile</Link>
299308
<!-- Type error: no route matches -->
300309
<Link href="/abuot">About</Link>
301310
</template>
@@ -309,7 +318,7 @@ import { routeUrl } from 'void/routes';
309318
310319
<Link href="/about">About</Link>
311320
<Link href={`/users/${user.id}?tab=activity`}>Profile</Link>
312-
<Link href={routeUrl('/users/:id', { params: { id } })}>Profile</Link>
321+
<Link href={routeUrl('/users/[id]', { params: { id } })}>Profile</Link>
313322
<!-- Type error: no route matches -->
314323
<Link href="/abuot">About</Link>
315324
```
@@ -320,13 +329,13 @@ import { routeUrl } from 'void/routes';
320329

321330
<Link href="/about">About</Link>
322331
<Link href={`/users/${user.id}?tab=activity`}>Profile</Link>
323-
<Link href={routeUrl('/users/:id', { params: { id } })}>Profile</Link>
332+
<Link href={routeUrl('/users/[id]', { params: { id } })}>Profile</Link>
324333
<Link href="/abuot">About</Link> // Type error: no route matches
325334
```
326335

327336
:::
328337

329-
Links can also point to the current page (`?page=2`, `#comments`) and to `http://`, `https://`, `mailto:`, and `tel:` URLs. Relative paths such as `../settings` are rejected; use the absolute path. A fixed part with spaces or non-ASCII characters can be written as is (`/café menu`) or percent-encoded in uppercase, as `routeUrl()` returns it (`/caf%C3%A9%20menu`). A dynamic segment matches any text, including none, so `/users/:id` also accepts `/users/` and `/users/42/edit`. With a root dynamic page such as `pages/[slug].tsx`, `.vue`, or `.svelte`, a protocol-relative URL like `//example.com` passes too.
338+
Links can also point to the current page (`?page=2`, `#comments`) and to `http://`, `https://`, `mailto:`, and `tel:` URLs. Relative paths such as `../settings` are rejected; use the absolute path. A fixed part with spaces or non-ASCII characters can be written as is (`/café menu`) or percent-encoded in uppercase, as `routeUrl()` returns it (`/caf%C3%A9%20menu`). A dynamic segment matches any text, including none, so `/users/[id]` also accepts `/users/` and `/users/42/edit`. With a root dynamic page such as `pages/[slug].tsx`, `.vue`, or `.svelte`, a protocol-relative URL like `//example.com` passes too.
330339

331340
The [SSE](./sse.md#client) and [live stream](./live.md#subscribe-from-the-browser) clients, `connectEventStream()` and `connectLiveStream()`, take one of your routes or an `http://` or `https://` URL for a stream on another origin. They reject same-page, `mailto:`, `tel:`, and `ws://` URLs. Cast a stream URL that TypeScript can't check with `as RouteUrl`; the cast turns off the check for that URL.
332341

@@ -339,8 +348,8 @@ declare const id: string;
339348
declare const dynamic: string;
340349

341350
c.redirect('/about');
342-
c.redirect(routeUrl('/users/:id', { params: { id } }));
343-
c.redirect({ pathname: '/users/:id', params: { id } });
351+
c.redirect(routeUrl('/users/[id]', { params: { id } }));
352+
c.redirect({ pathname: '/users/[id]', params: { id } });
344353
c.redirect('https://example.com/login');
345354
c.redirect(new URL('https://example.com/login'));
346355
c.redirect(dynamic as Href);

‎docs/guide/typed-fetch.md‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -21,11 +21,13 @@ await fetch('/api/users', {
2121
});
2222

2323
// Dynamic params interpolated from the route pattern
24-
const user = await fetch('/api/users/:id', {
24+
const user = await fetch('/api/users/[id]', {
2525
params: { id: '42' },
2626
});
2727
```
2828

29+
Route patterns use the same brackets as your filenames.
30+
2931
## What Gets Type-Checked
3032

3133
The client constrains every part of the request:
@@ -64,7 +66,7 @@ Non-2xx responses throw a `FetchError`:
6466
import { fetch, FetchError } from 'void/client';
6567

6668
try {
67-
await fetch('/api/users/:id', { params: { id: '999' } });
69+
await fetch('/api/users/[id]', { params: { id: '999' } });
6870
} catch (e) {
6971
if (e instanceof FetchError) {
7072
console.log(e.status); // 404
@@ -81,7 +83,7 @@ try {
8183
| `method` | `string` | HTTP method. Defaults to `"GET"`. |
8284
| `body` | `object` | Request body (auto-serialized as JSON). |
8385
| `query` | `Record<string, string>` | Query string parameters. |
84-
| `params` | `Record<string, string>` | URL path parameters (`:id` segments). |
86+
| `params` | `Record<string, string>` | URL path parameters (`[id]` segments). |
8587
| `headers` | `HeadersInit` | Additional request headers. |
8688
| `signal` | `AbortSignal` | Abort signal. |
8789
| `baseURL` | `string` | Base URL prepended to the path. Useful for external calls. |

0 commit comments

Comments
 (0)