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:

<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