SvelteKit 03 🧡 Dynamic Routes & Param Matchers — Building [slug], […rest], [[opt]], and src/params/ matchers
Dynamic routing is essential for modern web applications that serve database-driven content. Instead of creating thousands of static files, SvelteKit allows you to define route patterns using square brackets, which capture segments of the URL as variables. These variables are passed into your load functions, allowing you to fetch content from your database or CMS dynamically based on the path provided by the user.
Beyond basic dynamic segments, SvelteKit provides advanced tools to handle complex URL patterns, including catch-all routes and optional parameters. Furthermore, the framework introduces “Param Matchers,” which allow you to constrain specific segments to ensure they match valid formats (like integers or UUIDs) before the server even executes your load logic. This chapter explores how to structure these dynamic paths to build robust, type-safe, and SEO-friendly applications.
Key point: Dynamic routes are defined using brackets in the folder name, such as [slug] for dynamic segments, [...rest] for catch-all paths, and [[opt]] for optional segments; SvelteKit uses src/params/ matchers to validate these segments before the application logic runs, ensuring invalid routes are handled immediately.
Why exists
The Content-Scalability problem. Without dynamic routes, every blog post or user profile would require a physical folder on your disk. Dynamic segments allow you to serve infinite content using a single file.
The URL-Structure problem. SEO-friendly URLs are vital. Dynamic routes allow developers to construct clean, hierarchical URL structures (e.g., /shop/[category]/[product]) that search engines can easily index.
The Catch-All necessity. Some applications require complex hierarchical structures where the depth of the URL is unknown. The rest parameter [...rest] allows the application to handle arbitrary nesting.
The Data-Integrity problem. When a URL contains a dynamic ID, passing an invalid ID to a database can cause errors. Param matchers exist to validate URL segments at the routing layer, preventing unnecessary processing for invalid requests.
The Optional-Path requirement. Sometimes a parameter is desirable but not required (e.g., /blog/[page] vs /blog). Optional parameters [[opt]] solve this by allowing a single route to serve multiple path depths.
a. Basic Dynamic Segments and Catch-Alls
The most common dynamic route is [slug]. When a user visits /blog/my-first-post, SvelteKit matches the folder blog/[slug] and makes the value my-first-post available in your load function via the params object.
// src/routes/blog/[slug]/+page.server.ts
export function load({ params }) {
// params.slug is "my-first-post"
return { post: fetchPost(params.slug) };
}
For routes where the structure is deep or variable, you use [...rest]. This is often used for documentation sites or file browsers, where you need to know everything that comes after a specific base path. Everything captured by [...rest] is returned as a single slash-separated string.
b. Optional Parameters and Route Priority
Optional parameters use double brackets: [[opt]]. This allows a route to match both the base path and the path with the parameter. For example, a route named /search/[[query]] will match both /search and /search/apples.
Optional parameters are particularly useful for search interfaces, category filters, or optional user IDs. It is important to remember that SvelteKit resolves routes from top to bottom; if you have a static route with the same name as a dynamic route, the static route will always take precedence.
// src/routes/search/[[query]]/+page.server.ts
export function load({ params }) {
const query = params.query ?? 'default'; // Handle empty case
return { results: search(query) };
}
The double-bracket syntax ensures that your logic can gracefully handle the scenario where the parameter is missing, removing the need for separate redirect logic.
c. Constraining with Param Matchers
Matchers inside src/params/ are files that export a match function. This function returns true if the URL segment is valid for that specific route, or false otherwise. If the matcher returns false, SvelteKit will ignore the route and treat it as a 404 or move to the next matching route.
// src/params/integer.ts
export function match(param) {
return /^\d+$/.test(param); // Only matches numeric strings
}
To apply this to a route, rename your folder to [id=integer]. Now, if a user visits /post/abc, the route will not match, preventing your load function from even being called. This is a powerful way to guard your database queries against malformed ID inputs.
Complete Example Session
// ============================================
// PART 1: DEFINING A MATCHER
// ============================================
// src/params/uuid.ts
export function match(param) {
return /^[0-9a-f]{8}-.../.test(param);
}
// ============================================
// PART 2: APPLYING THE MATCHER
// ============================================
// Folder: src/routes/users/[id=uuid]/+page.server.ts
export function load({ params }) {
return { user: getUser(params.id) };
}
// ============================================
// PART 3: OPTIONAL PARAMETER
// ============================================
// Folder: src/routes/posts/[[page]]/+page.server.ts
export function load({ params }) {
const page = params.page || 1;
return { posts: getPosts(page) };
}
// ============================================
// PART 4: CATCH-ALL
// ============================================
// Folder: src/routes/docs/[...path]/+page.server.ts
export function load({ params }) {
return { content: getDoc(params.path) };
}
This sequence demonstrates the full spectrum of dynamic routing: validating IDs via matchers, handling optional pages, and capturing deep paths with rest parameters.
Quick Reference
Route Syntax
| Syntax | Description | Example |
|---|---|---|
[slug] | Mandatory parameter | /post/[slug] |
[...rest] | Catch-all (unlimited depth) | /files/[...path] |
[[opt]] | Optional parameter | /page/[[num]] |
[id=int] | Typed parameter (via matcher) | /user/[id=int] |
Matcher File Path
src/params/[name].ts must export match(param: string): boolean.
Best Practices
✅ Do This:
// Use matchers for validation
[id=integer] // ✅
// Handle missing optional params
params.page ?? 1 // ✅
// Use descriptive names for segments
[category]/[product] // ✅
// Group related dynamic routes
/shop/[category]/[product] // ✅
❌ Don’t Do This:
// Use invalid characters in slug
[slug_with_spaces] // ❌
// Use a catch-all route at the top level
// (It will hijack every request) // ❌
// Perform validation in the load function
// (Do it in the matcher) // ❌
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Route conflict | Static route matches dynamic | Put static route first |
| Matcher failure | Incorrect regex/logic | Test matcher in isolation |
| 404 confusion | Optional param missing | Ensure params.x ?? val used |
| Rest overlap | Catch-all too broad | Use specific matchers |
Real-World Examples
1. Blog slug
src/routes/blog/[slug]/+page.svelte
2. E-commerce category
src/routes/shop/[category]/+page.svelte
3. Optional page
src/routes/posts/[[page]]/+page.svelte
4. Docs catch-all
src/routes/docs/[...path]/+page.svelte
5. User integer ID
src/routes/user/[id=integer]/+page.svelte
6. UUID match
src/routes/api/session/[id=uuid]/+server.ts
7. Profile slug
src/routes/p/[slug]/+page.svelte
8. Search results
src/routes/search/[[query]]/+page.svelte
9. Language catch-all
src/routes/[lang]/[...path]/+page.svelte
10. Dashboard reset
src/routes/dashboard/[...rest]/+layout@.svelte
Visual
Route Resolution Priority
┌──────────────────────────────────────────────┐
│ Request: /post/123 │
│ │
│ 1. Check static: /post/123/ │
│ 2. Check dynamic: /post/[id=int]/ │
│ 3. Check catch-all: /post/[...rest]/ │
└──────────────────────────────────────────────┘
Param Matcher Lifecycle
┌──────────────────────────────────────────────┐
│ URL Segment ──► Matcher (True/False) │
│ │ │
│ ┌──────────────────┴──────────────────┐ │
│ True False
│ │ │
│ Run Load Function 404 / Skip
└──────────────────────────────────────────────┘
Catch-All Routing
┌──────────────────────────────────────────────┐
│ /docs/intro/installation/setup │
│ ┌───────────────────────────┐ │
│ │ Folder: [...path] │ │
│ │ params.path = │ │
│ │ "intro/installation/setup"│ │
└──────────────────────────────────────────────┘
Summary
| Item | Value |
|---|---|
| Mandatory | [slug] |
| Catch-all | [...rest] |
| Optional | [[opt]] |
| Validations | src/params/ matchers |
| Resolution | Top-to-bottom |
Key takeaways:
- Use square brackets. They are the declarative way to tell SvelteKit that a URL segment is dynamic.
- Matchers are your first line of defense. Don’t wait for your database query to fail; use
src/params/to filter bad requests out before they reach yourloadfunction. - Think about priority. Always place your most specific static routes at the top of your folder hierarchy and your broad catch-all routes at the bottom.
- Handle the missing state. With optional parameters
[[opt]], always provide a default value (e.g.,params.page ?? 1) to ensure your application behaves correctly when the parameter is absent. - Catch-all is powerful but dangerous. Use
[...rest]only when you truly need to support deep nesting, as it is difficult to intercept with other routes once defined.
Remember: Dynamic routing is a balance between flexibility and precision. By using specific segment types, optional brackets, and rigorous param matchers, you create a robust entry point for your application that protects your backend from garbage input while providing clean, meaningful URLs for your users.
Stop using slow, ad-bloated tool sites! 🤮
🔎 Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)
⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free
🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!