/

How to Redirect to a URL in Sapper

How to Redirect to a URL in Sapper

When working on a Svelte+Sapper application, you may come across a situation where you need to redirect the user to a specific page when they visit the root domain instead of showing the home page. In this blog post, I will show you how to achieve this using Sapper.

To begin, open the src/routes/index.svelte file. Remove the existing content and replace it with the following code:

1
2
3
4
5
<script context="module">
export async function preload(page, session) {
return this.redirect(301, 'spreadsheet/1');
}
</script>

In the code above, we define a preload function with the context="module" attribute. This function is executed on the server during the preloading phase. Inside the function, we use the redirect method to perform the redirection. The 301 parameter indicates a permanent redirection, and the URL 'spreadsheet/1' specifies the destination page.

By implementing this code in index.svelte, when a user visits the root domain (/), they will be automatically redirected to the /spreadsheet/1 page.

Tags: Sapper, Svelte, URL redirection