Search code examples
navigationsveltesveltekitnavigator

How can I navigate pragmatically in sveltekit?


Using sveltekit, after authenticating a user, how can I redirect to another internal page (in this case, simply on '/')? I've already tried goto() and redirect(), but the first gives a usage error on the server (Cannot call goto(...) on the server, when I use it on the client side), while the second, just prints the error and doesn't redirect. To understand this, I would simply need something like nuxt's navigateTo().


Solution

  • I solved thanks to H.B.'s comment that linked this post to me: How to redirect to page in SvelteKit?.

    So I used:

    import { browser } from '$app/environment';
    // ...Your other imports
    
    if (browser) { // to prevent error window is not defined, because it's SSR
        window.location.href = '/redirectpage';
    }
    

    The problem now is that window.location reloads the whole page. So It's better use goto() that instructs the sveltekit router to do a client side navigation instead.

    goto('/redirectpage');
    

    This can also help with other client side things like writing localStorage.