Redirecting pages in SvelteKit can be done using the load
functionality. This is a function that can be customized on a per-route basis and runs both during server-side rendering and in the client, and allows you to fetch and manipulate data before the page is rendered as per the SvelteKit Loading documentation.
The way to achieve a redirect in SvelteKit is to add a load
function to the route, that returns an HTTP 302
status code and as well as the target URL in the response body:
<script context="module">
export async function load() {
return {
status: 302,
redirect: "/directory/target-page"
}
}
</script>
The
load
function must be included as an ES module using<script context="module">
since the function runs before the page itself is rendered. The regular<script>
tag with Svelte imports and other component-specific code is included afterwards.
It’s worth noting that redirects can be done using platform-specific tooling, such as the _redirects
file when using Netlify as an example.
However, baking redirects into SvelteKit keeps the logic neatly within the src/routes
file system structure and avoids a declarative approach that would rely solely on the hosting provider.
#TIL
#TheMoreYouKnow