Search code examples
sveltesvelte-3sveltekit

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

  • 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