Route Parameters
Route Parameters are parts of the URLs that are extracted into parameters.
Imagine that you have a page with the following URLs where [skuId]
can be any of the thousands of products that you have in your database. It would be impractical to create a route for each product. Instead, we need to define a Route Parameter (a part of the URL) that will be used to extract the [skuId]
.
https://example.com/sku/[skuId]
- Will match:
https://example.com/sku/1234
- Will match:
https://example.com/sku/xyz-567
- Will match:
https://example.com/sku/[skuId]/details
- Will match:
https://example.com/sku/1234/details
- Will match:
src/
└── routes/
└── sku/
└── [skuId]/
├── index.tsx # https://example.com/sku/1234
└── details/
└── index.tsx # https://example.com/sku/1234/details
Retrieving the Route Parameter from the URL
Once we have [skuId]
in the URL, we need a way to retrieve it. This can be done by using useLocation()
API.
import { useLocation } from '@builder.io/qwik-city';
export default component$(() => {
const location = useLocation();
return (
<div>
<h1>SKU</h1>
<p>Pathname: {location.pathname}</p>
<p>Sku Id: {location.params.skuId}</p>
</div>
);
});
Catch All Routes
It is also possible to create a catch-all routes by adding a directory like [...slug]
. This works like the above described example but will also consider subsegments of the URI. It can also be applied on the routes
root level.
src/
└── routes/
└── sku/
└── [...slug]/
└── index.tsx
The above structure will match:
https://example.com/sku/1234
https://example.com/sku/1234/detail
https://example.com/sku/1234/detail/edit
- etc
It is possible to limit catch-all routes by adding a subdirectory say end-of-route
in [...slug]
directory.
src/
└── routes/
└── sku/
└── [...slug]/
├── index.tsx
└── end-of-route/
└──index.tsx
The above structure will match:
https://example.com/sku/1234/5678/end-of-route