SvelteKit version: 1.22.3
After using SvelteKit for a while, you've probably came across a situation where you need to navigate to another page of your app (e.g. after a successful login).
window.location window.location to navigate .
However, this might not be what you're looking for, since this will trigger a full page reload, breaking the SPA experience you get with SvelteKit.
SvelteKit provides a
goto function that you can use to navigate programmatically in your app.
This function is part of the
$app/navigation module, that provides other helpful functions like
invalidateAll and more.
Let's see the
goto function in action:
This snippet will navigate to the
/dashboard page after the
login function is called.
goto function accepts an optional second argument, that can be used to pass additional options to the navigation.
Here is the full function definition for
goto , per SvelteKit documentation:
The option you will probably use the most is
invalidateAll , which will rerun all
load functions of the page you're navigating to.
Another one that you might find useful is
replaceState , which will replace the current
history entry rather than creating a new one with
pushState . This is useful when you want to navigate to a page, but don't want the user to be able to go back to the previous page.
goto can only be called on the client
If you find yourself doing something like:
you'll probably get an error that reads like this:
This is because `goto` can only be called on the client , since it uses some native browser APIs that are not available on the server .
In case you're not sure if you're on the client or the server, you can wrap your `goto` call in a `onMount() ` lifecycle function, which will only run on the client when the component is mounted:
Checkout the following blog posts about how to fix browser APIs related errors in SvelteKit: