How do get query string parameter in sveltekit?

Viewed 6235

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')

3 Answers

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).

you can use

import { page } from '$app/stores'

$page.url.searchParams.get('ref')

The above solutions won't work. This is the new way:

export async function load({ params, url }) {
    let lang = url.searchParams.get('lang');
    let q = url.searchParams.get('q');
    return { lang, q };
}

Then, please reach it as this:

import { page } from '$app/stores';
$page.data.q

Thanks to Richard this is much better than acknowledging export var lang in each page

Related