Svelte 55 ๐งก Dynamic Route Parameters, Rest Parameters, and Optional Parameters
SvelteKit uses a filesystem-based routing system where dynamic URL segments are defined by wrapping folder names in brackets. This pattern allows developers to build scalable applications that react to URL inputs without writing manual route-matching logic. Whether you are building a blog system with unique identifiers, a catch-all documentation site, or a site with optional internationalization prefixes, these primitives allow for granular control over how a request is parsed and handled.
When a URL segment is dynamic, SvelteKit extracts the value from the path and injects it into the params object during the server-side loading process. This enables the server to immediately fetch data based on the route and hydrate the page before it reaches the browser. This chapter details the mechanics of standard dynamic parameters, greedy rest parameters, and the specialized optional parameter syntax, providing the tools needed to design robust and flexible URL schemas.
Key point: Dynamic route parameters are defined by [name] for required segments, [[name]] for optional segments, and [...name] for greedy rest matches; these values are available in the load function and page store, allowing for server-side data fetching based on the URL.
Why exists
The Scalability Problem. Hardcoding every possible page (e.g., /posts/1, /posts/2) is impossible for content-heavy sites. Dynamic parameters exist to allow a single file to handle an infinite set of URLs, mapping the input to a database query automatically.
The URL Structure Problem. Static routes provide no context to the application code. By using parameters, the URL itself acts as a data contract, ensuring that the application logic knows exactly which resource the user is requesting without needing redundant client-side logic.
The Catch-all Problem. In many web applications, you need a catch-all route for legacy redirects, sub-path management, or complex nested structures. Rest parameters ([...rest]) exist to grab arbitrary paths, allowing the application to handle non-deterministic deep linking.
The Ambiguity Problem. Sometimes a part of the path might be missing, and the application should handle it gracefully (like an optional language code or category). Optional parameters exist to prevent the need for duplicate routes or hacky redirection logic to fill in missing segments.
The Type Safety Problem. Because SvelteKit passes these parameters into load functions, it can leverage TypeScript to enforce the shape of the URL. This ensures that the developer treats the dynamic segments as expected types rather than raw, unsafe strings.
a. Basic Dynamic Parameters
A dynamic parameter is defined by wrapping a folder name in single square brackets, such as src/routes/product/[id]/+page.svelte. When a user visits /product/123, SvelteKit extracts 123 as the id. This value is then passed into the params object of the load function, where it can be used to perform database or API lookups.
// src/routes/product/[id]/+page.server.ts
export async function load({ params }) {
const product = await db.fetchProduct(params.id);
return { product };
}
This approach allows for clean, semantic URLs. The load function executes before the component renders, ensuring that the necessary data is ready. If the data lookup fails, you can simply throw an error(404, 'Product not found'), and SvelteKit will display the nearest +error.svelte page automatically.
b. Rest Parameters
Rest parameters are defined using the spread syntax within brackets, like src/routes/docs/[...path]/+page.svelte. Unlike standard parameters, which match only one segment between slashes, rest parameters match everything that follows, including multiple slashes. This is known as a “greedy” match.
// src/routes/docs/[...path]/+page.server.ts
export async function load({ params }) {
const segments = params.path.split('/');
return { path: segments };
}
A request to /docs/installation/getting-started/quick-setup would result in params.path being equal to "installation/getting-started/quick-setup". This is highly useful for building nested documentation sites, file explorers, or any application where the depth of the URL is unknown at build time.
c. Optional Parameters
Optional parameters use double brackets: [[slug]]. Unlike standard parameters, which must be present for the route to match, an optional parameter allows the same page to handle both the base URL and the extended URL. This is frequently used for localized sites or filtering.
// src/routes/[[lang]]/blog/+page.server.ts
export async function load({ params }) {
const lang = params.lang ?? 'en';
return { content: await fetchBlog(lang) };
}
A user visiting /blog or /fr/blog will both trigger the same +page.svelte. The load function uses the nullish coalescing operator (??) to provide a fallback value for the missing segment. Note that optional parameters must be at the end of a path or correctly isolated to avoid matching conflicts with other routes.
Complete Example Session
// ============================================
// PART 1: DYNAMIC ID
// ============================================
// src/routes/users/[id]/+page.server.ts
export const load = ({ params }) => ({ id: params.id });
// ============================================
// PART 2: REST PATH
// ============================================
// src/routes/files/[...path]/+page.server.ts
export const load = ({ params }) => ({ path: params.path });
// ============================================
// PART 3: OPTIONAL PARAM
// ============================================
// src/routes/shop/[[category]]/+page.server.ts
export const load = ({ params }) => ({ cat: params.category || 'all' });
// ============================================
// PART 4: ACCESSING IN COMPONENT
// ============================================
// src/routes/users/[id]/+page.svelte
export let data;
<h1>User: {data.id}</h1>
// ============================================
// PART 5: THE PARAMS STORE
// ============================================
import { page } from '$app/stores';
// $page.params.id
// ============================================
// PART 6: PARAMS WITH TYPES
// ============================================
// src/routes/users/[id]/+page.server.ts
import type { PageServerLoad } from './$types';
export const load: PageServerLoad = ({ params }) => ({ ... });
// ============================================
// PART 7: CATCH-ALL ROUTE
// ============================================
// src/routes/[...catchall]/+error.svelte
// Handle 404s for everything else.
// ============================================
// PART 8: MULTIPLE PARAMS
// ============================================
// src/routes/shop/[cat]/[item]/+page.server.ts
export const load = ({ params }) => ({ cat: params.cat, item: params.item });
// ============================================
// PART 9: PARAM VALIDATION
// ============================================
if (isNaN(Number(params.id))) throw error(404);
// ============================================
// PART 10: REDIRECTING FROM PARAMS
// ============================================
if (!params.id) throw redirect(307, '/home');
These parts demonstrate how to handle dynamic values, nested paths, and optional segments, and how to integrate them into SvelteKitโs loading system.
Quick Reference
Bracket Syntax
| Pattern | Behavior | Use Case |
|---|---|---|
[id] | Required | Primary keys (DB) |
[...path] | Greedy/Rest | Deeply nested paths |
[[lang]] | Optional | Localization / Filters |
Param Access
| Source | Access Method |
|---|---|
| Load Function | params.name |
| Component | $page.params.name |
Best Practices
โ Do This:
// Validate parameters early
if (!/^\d+$/.test(params.id)) throw error(404); // โ
// Provide defaults for optional parameters
const lang = params.lang ?? 'en'; // โ
// Keep rest parameters isolated
// Place them at the end of a route tree // โ
// Use type-safe params from $types
import type { PageServerLoad } from './$types'; // โ
โ Don’t Do This:
// Don't trust user input directly
// Sanitize params before database queries // โ
// Don't use optional params for conflicting routes
// (e.g. [[slug]] alongside [id]) // โ
// Don't forget to handle the empty case for [[slug]]
// It will be undefined, not an empty string // โ
// Don't create overly greedy rest routes
// They might shadow other static routes // โ
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Overlap | Static route matches dynamic | Place static route higher |
| Undefined | Accessing missing optional | Use nullish coalescing |
| Trailing slash | Rest param captures it | Trim the string |
| Type mismatch | Params are always strings | Explicit cast to number |
Real-World Examples
1. Blog slug
src/routes/blog/[slug]/+page.server.ts
2. Deep docs path
src/routes/docs/[...path]/+page.server.ts
3. Optional locale
src/routes/[[lang]]/about/+page.server.ts
4. Multiple dynamic segments
src/routes/store/[category]/[product]/+page.server.ts
5. Validation logic
if (params.id.length < 3) throw error(400);
6. Redirecting invalid path
if (!isValid(params.slug)) throw redirect(301, '/');
7. Using in UI
{$page.params.slug}
8. Rest path splitting
const parts = params.path.split('/');
9. Optional fallback
const cat = params.category || 'general';
10. Typed params
export const load: PageServerLoad = ({ params }) => { ... }
Visual
URL Parameter Matching
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ /users/123 โ
โ Matched by: src/routes/users/[id]/ โ
โ Result: params.id = "123" โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Greedy Rest Matching
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ /docs/a/b/c โ
โ Matched by: src/routes/docs/[...path]/
โ Result: params.path = "a/b/c" โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Optional Parameter logic
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ /en/shop โโโบ [[lang]] = "en" โ
โ /shop โโโบ [[lang]] = undefined โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Summary
| Item | Value |
|---|---|
| Required Parameter | [name] |
| Rest Parameter | [...name] |
| Optional Parameter | [[name]] |
| Context | params object |
| Global Access | $page.params |
Key takeaways:
- Brackets define dynamic segments. Any directory name wrapped in
[]tells SvelteKit to extract that part of the URL path. paramsis the source of truth. Use this object insideloadfunctions to safely bridge the URL to backend logic.- Rest parameters are greedy. Using
[...name]allows you to capture entire URL paths, which is perfect for hierarchical systems like documentation. - Optional parameters handle flexibility. Double brackets
[[name]]provide a simple way to create routes that function with or without specific path segments. - Validate aggressively. Always treat dynamic parameters as untrusted user inputโsanitize and validate them before performing database operations or logic branching.
Remember: Dynamic routing is the mechanism that turns your file system into a powerful API. By leveraging required, greedy, and optional parameters, you can craft highly expressive URL structures that are both user-friendly and easy for your server-side logic to parse. Always remember that parameters are strings, so perform your type conversions early to keep your application logic clean and safe.
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!