/

How to Access a URL Parameter in Sapper Outside of Script Module

How to Access a URL Parameter in Sapper Outside of Script Module

If you are creating a Svelte application using Sapper and have a dynamic page route such as /routes/[id].svelte, you may need to access the dynamic part of the URL (in this case, the id) outside of the preload() function in the <script context="module"> section of the component.

To achieve this, you can return the id from the preload() function and define it as a prop of the component using the export * syntax. Here’s an example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<script context="module">
export async function preload({ params }) {
const { id } = params;
return { id };
}
</script>

<script>
export let id;

if (typeof window !== 'undefined') {
alert(id);
}
</script>

By exporting the id from preload(), it becomes accessible as a prop within the component. Then, you can use it as required outside of the preload() function.

Tags: Sapper, Svelte, URL parameter, dynamic route