0
0
SvelteHow-ToBeginner · 3 min read

How to Use Params in SvelteKit: Simple Guide

In SvelteKit, you use params to access dynamic parts of a route by defining filenames with brackets like [param]. Inside your page or layout, you get these params from the load function's argument to use them for fetching data or rendering dynamic content.
📐

Syntax

To use params in SvelteKit, create a route file with a dynamic segment using square brackets, like src/routes/[id]/+page.svelte. Then, in the +page.js or +page.ts file, use the load function to access params from the argument object.

The params object contains keys matching your dynamic segments and their values from the URL.

javascript
export function load({ params }) {
  const id = params.id;
  return { id };
}
💻

Example

This example shows a dynamic user profile page where the URL contains a user ID. The load function extracts the id param and passes it to the page component to display.

svelte
// src/routes/[id]/+page.js
export function load({ params }) {
  return { userId: params.id };
}

// src/routes/[id]/+page.svelte
<script>
  export let data;
</script>

<h1>User Profile</h1>
<p>User ID: {data.userId}</p>
Output
<h1>User Profile</h1> <p>User ID: 123</p> (when visiting /123)
⚠️

Common Pitfalls

  • Forgetting to use square brackets in the filename means params won't work.
  • Trying to access params directly in the component without using load will fail because params are only available in the load function.
  • Not returning the params data from load makes it unavailable in the component.
javascript
/* Wrong: No brackets in filename, so no params */
// src/routes/id/+page.js
export function load({ params }) {
  // params.id is undefined
  return { id: params.id };
}

/* Correct: Use brackets and return params */
// src/routes/[id]/+page.js
export function load({ params }) {
  return { id: params.id };
}
📊

Quick Reference

Summary tips for using params in SvelteKit:

  • Use [param] in route filenames for dynamic segments.
  • Access params inside load via { params }.
  • Return params data from load to use in your component.
  • Params are always strings from the URL.

Key Takeaways

Define dynamic route segments using square brackets in filenames like [param].
Access route params inside the load function via the params object.
Return params from load to pass them as props to your page component.
Params are strings representing the dynamic parts of the URL.
Always use load to get params; they are not directly available in the component script.