Redirect from script tag
This is the simplest redirect you can do in sveltekit. The redirect happens after the component is loaded.
<script>
import { goto } from '$app/navigation';
goto("/some-route")
//user will be redirected to /some-route
</script>
Redirect from load function
This is the most common way to redirect users. The redirect happens before the component is loaded.
<script context="module">
export const load = async() => {
return {
status: 302,
redirect: "/some-route"
};
}
</script>
Redirect from endpoint
We usually redirect users in an Endpoint after an action. So i have shown a post method here.
User sends some data to the endpoint and after validation of that data we redirect users to an appropriate page.
An example would be when a user logs in, we redirect them to the dashboard.
export const post = async () => {
return {
status: 302,
headers: {
location: "/some-route",
},
};
};
Redirect from handle function in hooks file
Hooks file gives us God level control over all requests. So it should be used with caution.
In this case I’m redirecting users from homepage to /some-route
. So no one can access the homepage.
export const handle = async ({ event, resolve }) => {
if (event.url.pathname === "/") {
return Response.redirect("http://localhost:3000/some-route", 302);
// redirects user to /some-route on condition
}
return await resolve(event);
};
You have to be cautious when using redirects in hooks. You might end up in a loop or error saying too many redirects.