Parametric routes
Parametric routes contain segments that change based on dynamic data.
Convention
A parametric route can be created by wrapping a folder with square brackets:
[segmentName]
.
Example
Let's imagine you want to create a route that gives the weather for a given city.
Bob is living in Toronto and will get the weather by calling the API /cities/toronto/weather
.
Jane is living in Paris and will get her weather by calling /cities/paris/weather
.
While being different, those 2 API calls should execute the same route.
> api
> cities
> [city]
> weather
+ route.get.ts
The parametric segment is automatically passed down to the route handler.
export default ({ city }) => {
return `weather in ${city} is moderate`
}
URL | params |
---|---|
/cities/toronto/weather | { city: 'toronto' } |
/cities/paris/weather | { city: 'paris' } |
Catch-all segment
Parametric segments can be extended to catch all subsequent segments by adding an ellipis inside the brackets [...segmentName]
.
> api
> hello
> [...names]
+ route.get.ts
URL | params |
---|---|
/hello/bob | { names: ['bob'] } |
/hello/bob/jane | { names: ['bob', 'jane'] } |
/hello/bob/jane/john | { names: ['bob', 'jane', 'john'] } |
Optional Catch-all params
Catch-all segments can be made optional (i.e parametric segment can be empty) by using double square brackets: [[...segmentName]]
.
> api
> hello
> [[...names]]
+ route.get.ts
URL | params |
---|---|
/hello | { names: [] } |
/hello/bob | { names: ['bob'] } |
/hello/bob/jane | { names: ['bob', 'jane'] } |
/hello/bob/jane/john | { names: ['bob', 'jane', 'john'] } |
Single parametric segment takes precedence over Catch-all segments that take precedence over optional Catch-all.