On a 404 error, I don't want to display a 404 page. Instead, I'd like to redirect back to the index page if the user is logged in or to the login page if the user is logged out. I'm already able to route the user to the login in page from the index page if not signed in, so I may just need to redirect to the index page and have it take care of the reroute to the login in page, although that seems inefficient to have to do two reroutes.
I'm able to accomplish it by re-writing the routes/_error.svelte
page to this...
<script>
import { onMount } from 'svelte';
onMount(() => {window.location.href = '/'});
</script>
But I'm not very confident it's the best way to accomplish what I want to do. It also redirects for all errors, and in a future project, I may want to show certain errors such as 404, but redirect on other errors like 500.
Does anyone have some insight on how this might be better accomplished using Sapper?
404s should not always be redirected. 404s should not be redirected globally to the home page. 404s should only be redirected to a category or parent page if that's the most relevant user experience available. It's okay to serve a 404 when the page doesn't exist anymore (crazy, I know).
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.
You should try goto
function.
import { goto } from '@sapper/app';
goto('your/path');
and if you want to do it in the onMount hook, it should be:
<script>
import { onMount } from 'svelte';
import { goto } from '@sapper/app';
onMount(() => goto('your/path'));
</script>
In your very specific case, if you want to do it on an error criteria on the _error.svelte
page, you should choose your path depending on error:
<script>
import { onMount } from 'svelte';
import { goto } from '@sapper/app';
onMount(() => goto(
error.status === 500
? 'path1'
: error.status === 404
? 'path2'
: 'path3'
));
</script>
original GitHub issue here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With