Programmatically navigate in your SvelteKit app with goto

Justin Ahinon
Last updated on
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).
Since SvelteKit is mostly plain JavaScript, you can still use native web APIs like 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.
Enter the goto
function
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 afterNavigate
, invalidateAll
and more.
Let's see the goto
function in action:
code loading...
This snippet will navigate to the /dashboard
page after the login
function is called.
Advanced usage
The 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:
code loading...
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.
Gotcha: goto
can only be called on the client
If you find yourself doing something like:
code loading...
you'll probably get an error that reads like this:
code loading...
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:
code loading...
Checkout the following blog posts about how to fix browser APIs related errors in SvelteKit: