3

SvelteKit 1.0 has been out for a very short amount of time as per this writing, and I've encountered something that is nowhere in the new documentation. How can I route programmatically in SvelteKit 1.0? Before SvelteKit 1.0 there was a solution to do this, like it's written in this stackoverflow question. There was a goto function that did this (and now this function is out of the framework). You would've pass a route like "/homepage" and the function would route your app to the homepage page. How can I do this in SvelteKit 1.0? I have found nothing until now.

  • [`goto` still exists](https://kit.svelte.dev/docs/modules#$app-navigation-goto). Are you trying to do a server side redirect? – Tholle Dec 26 '22 at 12:29
  • Actually, I just realized that i have the default setting on my page, so I guess SSR is enabled. Yea, in this case, I am trying to do a server side redirect. – Timotei Oros Dec 26 '22 at 13:03
  • Nice. If you try to use `goto` in the top-level of your script tag it will be run on the server as well, which will not work as expected. You could put the logic in a `+page.server.js` file instead and use the built-in [`redirect` helper](https://kit.svelte.dev/docs/load#redirects). – Tholle Dec 26 '22 at 13:11

1 Answers1

3

goto still exists, but it is only usable in the browser (in an onMount callback, in an event handler, ...).

If you try to use it in the top-level of your page script tag it will be run on the server as well, which will not work as you might expect. You could e.g. create a +page.server.js file and use the built-in redirect helper to do a server-side redirect instead.

Tholle
  • 108,070
  • 19
  • 198
  • 189