Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Sapper, how can I redirect to the index page on a 404 error?

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?

like image 744
Steven Bell Avatar asked Oct 22 '19 01:10

Steven Bell


People also ask

Should you redirect to a 404 page?

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).

How do I redirect in SvelteKit?

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.


1 Answers

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

like image 94
Rodrigo Medina Avatar answered Oct 23 '22 20:10

Rodrigo Medina