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.
CodePudding user response:
Please see the docs.
You have to throw a redirect
:
import { redirect } from '@sveltejs/kit';
export function load() {
// ...
throw redirect(302, '/');
}