How to redirect to page in SvelteKit?
Asked Answered
H

3

25

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.

Hamrick answered 14/12, 2022 at 23:17 Comment(0)
C
44

See the SvelteKit Redirect docs.

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

On the page one would use goto.

Cenesthesia answered 15/12, 2022 at 0:1 Comment(2)
Yes but what if I want to do it outside of the load function? Eg, in a +page.svelte fileCaceres
Note, for sveltekit 2.0 you can just use redirect(302, '/');, no need to throw anything anymore.Pedraza
O
18

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';
}
Olmos answered 20/3, 2023 at 2:4 Comment(0)
F
2

To do it on the server, you put it in +page.server.ts:

// src/routes/page-to-redirect/+page.server.ts

import { redirect } from '@sveltejs/kit';

export function load() {
    throw redirect(302, '/redirect-to-this-url');
}
Furthermore answered 25/11, 2023 at 21:23 Comment(1)
Note, for sveltekit 2.0 you can just use redirect(302, '/');, no need to throw anything anymore.Pedraza

© 2022 - 2024 — McMap. All rights reserved.