Theo
Theo

Reputation: 383

How to redirect to page in SvelteKit?

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:

<script context="module">
    export async function load() {
        return {
            status: 302,
            redirect: "/"
        };
    }
</script>
/** @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.

Upvotes: 27

Views: 73829

Answers (3)

Kevin Niam
Kevin Niam

Reputation: 221

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';
}

Upvotes: 21

brunnerh
brunnerh

Reputation: 185225

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.

Upvotes: 49

sirbots
sirbots

Reputation: 69

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');
}

Upvotes: 2

Related Questions