10

I have a page with content rendered from a SvelteKit store. If the store is invalid, a user needs do be redirected to the homepage. Unfortunately, I can't find a way to redirect a user even without checking any conditions, so let's focus on a simpler question: how to always redirect from somepage to homepage?

I have tried the following, none of this works for me:

  • Using <script context="module"> before script tag on the page as follows:
<script context="module">
    export async function load() {
        return {
            status: 302,
            redirect: "/"
        };
    }
</script>
  • Using PageLoad in +page.js file:
/** @type {import('./$types').PageLoad} */
export function load() {
    return {
        status: 302,
        redirect: '/'
    };
}

When I use the code mentioned above, the website works as if nothing was changed, I get no errors, but the redirection does not happen. If I get to the page unexpectedly (type it's address in the search bar, the store is not ready), I get redirected to the error page, because an error happens (which I want to prevent by homepage redirection). If I get to the page expectedly (the store is fine), the page gets rendered normally, no redirect happens.

Theo
  • 103
  • 1
  • 1
  • 6

2 Answers2

23

See the SvelteKit Redirect docs.

You have to throw a redirect:

import { redirect } from '@sveltejs/kit';
 
export function load() {
  // ...
  throw redirect(302, '/');
}

On the page one would use goto.

H.B.
  • 166,899
  • 29
  • 327
  • 400
9

Based on the documentation page you would use goto(theurl). Example:

import { goto } from '$app/navigation';
// ...Your other imports

goto('/redirectpage');

Or if you prefer using native approach, then in file .svelte you would do this,

If you are not using SSR then this:

window.location.href = '/redirectpage';

Or if you are using SSR then this:

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';
}
Kevin Niam
  • 91
  • 1
  • 2