How to route programmatically in SvelteKit?

I want to be able manage history of my SvelteKit app while simultaneously making sure the whole routing system of SvelteKit doesn't get affected in any way.

Something like:

function routeToPage(route: string) {
   router.push(`/${route}`) // equivalent of this function
}

Solution 1:

Answering my own question thanks to Theo from SvelteKit Discord:

Use https://kit.svelte.dev/docs#modules-$app-navigation.

import { goto } from '$app/navigation';

function routeToPage(route: string, replaceState: boolean) {
   goto(`/${route}`, { replaceState }) 
}

replaceState == true will replace the route instead of adding to the browser history. So, when you click back, you will not go back to the route you came from.

To go back use History API.

import { goto } from '$app/navigation';

function goBack(defaultRoute = '/home') {
  const ref = document.referrer;
  goto(ref.length > 0 ? ref : defaultRoute)
}

Solution 2:

You can programmatically navigate to a route in Svelte-Kit using the goto function. The most simple implementation would be something like this:

<script> 
  import { goto } from '$app/navigation';
  goto("/route")
</script>

But you can use more advanced options with it as well, which would be passed as a second argument with the target route.