'How do get query string parameter in sveltekit?

I'm trying to the /login?ref=/some/path parameter to redirect to after login:

    const ref = $page.url.searchParams.get('ref') || '/dashboard';

However I get this error:

TypeError: Cannot read properties of undefined (reading 'searchParams')



Solution 1:[1]

You can get the query string parameters from the url property of the object passed to the load function of a page:

<script context="module">
  export function load({ url }) {
    const ref = url.searchParams.get('ref') || '/dashboard';
    return {
      props: {
        ref
      }
    };
  }
</script>
<script>
  export let ref;

  // do stuff
</script>

More info on the load function, its input format and its reactivity here (SvelteKit docs).

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Thomas Hennes