This page looks best with JavaScript enabled

How to redirect to a URL in Sapper

 ·  ☕ 1 min read  ·  👽 john hashim

If your working on a Svelte+Sapper application and you run in asituation where you need to redirect to different homepage, with URL /home1/1,/home2/1 when the user visited the root domain /, instead of showing the default home page opened src/routes/index.svelte, comment out or removed everything in that file, and add this code:

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

or redirect your user to login pages if not login user..

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
<script context="module">
	export async function preload(page, session) {
		const { user } = session;

		if (!user) {
			return this.redirect(302, 'login');
		}

		return { user };
	}
</script>
Share on

john hashim
WRITTEN BY
john hashim
Web Developer