0

Using sveltekit, after authenticating a user, how can I redirect to another internal page (in this case, simply on '/')? I've already tried goto() and redirect(), but the first gives a usage error on the server (Cannot call goto(...) on the server, when I use it on the client side), while the second, just prints the error and doesn't redirect. To understand this, I would simply need something like nuxt's navigateTo().

Teo7
  • 47
  • 5
  • Are you looking for [goto](https://kit.svelte.dev/docs/modules#$app-navigation-goto) from [$app/navigation](https://kit.svelte.dev/docs/modules#$app-navigation) – Nalin Ranjan Jul 16 '23 at 09:23
  • Show your code. See also [this question](https://stackoverflow.com/q/74805197/546730). – H.B. Jul 16 '23 at 16:57
  • Yes, I tried goto from $app/navigation. – Teo7 Jul 18 '23 at 16:41

2 Answers2

0

Using redirect would be the correct way to accomplish this. Are you sure you're not catching the thrown redirect?

huurseen
  • 1
  • 1
  • yes, maybe because I'm using it on client and not on server side.. But I need it on client. – Teo7 Jul 18 '23 at 16:42
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jul 23 '23 at 06:26
0

I solved thanks to H.B.'s comment that linked this post to me: How to redirect to page in SvelteKit?.

So I used:

import { browser } from '$app/environment';
// ...Your other imports

if (browser) { // to prevent error window is not defined, because it's SSR
    window.location.href = '/redirectpage';
}

The problem now is that window.location reloads the whole page. So It's better use goto() that instructs the sveltekit router to do a client side navigation instead.

goto('/redirectpage');

This can also help with other client side things like writing localStorage.

Teo7
  • 47
  • 5