28

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

chovy
  • 72,281
  • 52
  • 227
  • 295

3 Answers3

25

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

Thomas Hennes
  • 9,023
  • 3
  • 27
  • 36
  • 2
    Is there a way to get it from `$page`? – chovy Mar 07 '22 at 18:59
  • Yes you can, in similar fashion, see the code in the `Header` component in [this Stackblitz example](https://stackblitz.com/edit/sveltejs-kit-template-default-rmgmwd?file=src%2Flib%2Fheader%2FHeader.svelte&terminal=dev) I quickly put together. Which, incidentally, is the way you're attempting to do it in your own code, so you might want to check that your SvelteKit version is up-to-date. – Thomas Hennes Mar 07 '22 at 19:42
  • Yeah that’s what I thought. I have svelte 3.x – chovy Mar 07 '22 at 19:47
  • It's the SvelteKit version that matters here. Kit is where the routing, etc. is handled. – Thomas Hennes Mar 07 '22 at 20:08
  • ` "@sveltejs/kit": "next",` – chovy Mar 08 '22 at 01:55
20

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

KyleMit
  • 30,350
  • 66
  • 462
  • 664
Bitfinicon
  • 1,045
  • 1
  • 8
  • 22
  • 1
    Why do you destructure params? You are not using it. Plus, `$page.data` is used in a page **that need to access data from a child page or layout**: https://kit.svelte.dev/docs/load#using-url-data https://kit.svelte.dev/docs/load#$page-data – Big_Boulard Dec 15 '22 at 05:35
  • Actually, we are using it. That's why included. Good that it's reachable from server side – Bitfinicon Jan 10 '23 at 17:48
18

you can use

import { page } from '$app/stores'

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