How to route programmatically in SvelteKit?

Answering my own question thanks to Theo from SvelteKit Discord:

Use $$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)
}

Leave a Comment