Dynamic Routes
Use square brackets to declare a single-segment parameter:
src-api/users/[id].js
That route becomes:
/users/1/users/2/users/3
depending on what paths() returns.
Required paths()
Dynamic routes must export paths():
export async function paths() {
return ['1', '2', '3'];
}
For dynamic routes:
paths()must return an array of strings- each string is one concrete value for the parameter
If a dynamic route does not export paths():
- the route is skipped
- the build does not fail just because of that omission
Example
// src-api/users/[id].js
export async function paths() {
return ['1', '2', '3'];
}
export async function data({ params }) {
return {
id: params.id,
role: Number(params.id) % 2 === 0 ? 'editor' : 'viewer',
};
}
params for /users/2 will be:
{
id: '2';
}
Parent collection route with listIndex
Dynamic routes can also emit a parent collection route:
export const config = {
listIndex: true,
};
export async function paths() {
return ['1', '2'];
}
export async function data({ params }) {
return {
id: params.id,
name: `User ${params.id}`,
role: 'member',
};
}
This produces:
/users/1/users/2/users
If you want only selected fields in the parent route:
export const config = {
listIndex: {
enabled: true,
pick: ['id', 'name'],
},
};
Then /users contains only:
idname
from each item payload.
Route collisions
Be careful with parent collection routes.
If you already have a static route at /users, enabling listIndex for users/[id].js creates a collision.
That build should fail instead of silently overwriting one route with another.