How to redirect to a URL in Sapper
By Flavio Copes
Learn how to redirect to another URL in Sapper by calling this.redirect with a 301 status inside the preload function of your Svelte route module.
Sapper is deprecated in favor of SvelteKit and receives no security or bug fixes. Do not use this code in a new project.
In Sapper you redirect to another URL by calling this.redirect() inside the preload() function of a route, passing an HTTP status code and the destination.
I was working on a Svelte+Sapper application when I had the need to redirect to a page, with URL /spreadsheet/1, when the user visited the root domain /, instead of showing the home page.
So I opened src/routes/index.svelte, removed everything in that file, and I added this code:
<script context="module">
export async function preload(page, session) {
return this.redirect(301, 'spreadsheet/1')
}
</script>
What is preload()?
preload() is a special function Sapper looks for in route components. It runs before the component renders, so it’s the right place to fetch data, or in this case, to decide the page shouldn’t render at all.
It must live in a <script context="module"> block. A module script runs once when the module loads, before any component instance exists, and that’s the only place Sapper can call preload() from.
The function receives two arguments. page gives you the current path, params and query string. session holds server-provided session data. We don’t need either here, but you could use page.query to redirect conditionally.
What does this.redirect() do?
Sapper binds preload() to an object with a few helper methods, and redirect() is one of them. It takes a status code and the target URL, and aborts rendering the current route.
The nice part is that it works on both sides of a Sapper app. On the first request, preload() runs on the server and the visitor gets a real HTTP redirect with the status code you passed. On client-side navigation, Sapper handles it in the browser and swaps the route without a full page load.
Since we’re using a regular function (not an arrow function), this points to that helper object. An arrow function here would break, because it wouldn’t get its own this.
Choosing 301 vs 302
I used 301 because I wanted the redirect to be permanent: that app has no real home page.
Be careful with 301 during development, though. Browsers cache permanent redirects aggressively, so if you later change your mind, your own browser may keep redirecting you even after you removed the code. While testing, use 302 (a temporary redirect), and switch to 301 only when you’re sure.
Want me to talk about your product? You can sponsor this site.