Table of Contents
Get this article emailed to you .
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).
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
function that you can use to navigate programmatically in your app.
This function is part of the
module, that provides other helpful functions like
Let's see the
function in action:
This snippet will navigate to the
page after the
function is called.
function accepts an optional second argument, that can be used to pass additional options to the navigation.
Here is the full function definition for
, per SvelteKit documentation:
The option you will probably use the most is
, which will rerun all
functions of the page you're navigating to.
Another one that you might find useful is
, which will replace the current
entry rather than creating a new one with
. 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.
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: