0
0
SvelteHow-ToBeginner · 3 min read

How to Create Dynamic Routes in SvelteKit Easily

In SvelteKit, create dynamic routes by naming files or folders with square brackets like [param]. This lets you capture URL parts as variables accessible in your page components via export let params.
📐

Syntax

Dynamic routes in SvelteKit use square brackets in filenames or folder names to capture URL parameters. For example, src/routes/[slug]/+page.svelte matches any URL segment and stores it as slug.

You can access these parameters inside your component using export let params.

svelte
src/routes/[id]/+page.svelte

<script>
  export let params;
</script>

<h1>Item ID: {params.id}</h1>
Output
If you visit /123, the page shows: Item ID: 123
💻

Example

This example shows a dynamic route that captures a username from the URL and displays it on the page.

svelte
src/routes/[username]/+page.svelte

<script>
  export let params;
</script>

<h2>Welcome, {params.username}!</h2>
Output
Visiting /alice shows: Welcome, alice!
⚠️

Common Pitfalls

  • Forgetting to use square brackets in the filename means the route is static, not dynamic.
  • Not exporting params in the script block will cause undefined errors.
  • Using nested dynamic routes requires matching folder structure with brackets.
svelte
/* Wrong: static route, won't capture parameter */
src/routes/id/+page.svelte

<script>
  export let params;
</script>

<p>ID: {params.id}</p>

/* Right: dynamic route capturing 'id' */
src/routes/[id]/+page.svelte

<script>
  export let params;
</script>

<p>ID: {params.id}</p>
📊

Quick Reference

Use these tips to create dynamic routes in SvelteKit:

  • Name files or folders with [param] to capture URL parts.
  • Access parameters via export let params in your component.
  • Nested dynamic routes use nested folders with brackets.
  • Use +page.svelte in latest SvelteKit versions for page components.

Key Takeaways

Create dynamic routes by naming files or folders with square brackets like [param].
Access URL parameters inside components using export let params.
Nested dynamic routes require matching nested folder structures with brackets.
Always use +page.svelte files in SvelteKit for routing components.
Forget static filenames if you want dynamic URL segments.