How to show 404 error page in SvelteKit after route is rendered

3 min read 05-10-2024
How to show 404 error page in SvelteKit after route is rendered


SvelteKit 404s: Not Found, But How to Display It?

You've built a sleek SvelteKit application, your routes are defined, and your components are rendering beautifully. But what happens when a user tries to navigate to a page that doesn't exist? The dreaded 404 error! While SvelteKit handles the basic routing, the challenge is to create a custom and informative 404 page that gracefully handles these situations.

The Problem: SvelteKit's Default 404 Handling

Let's imagine a scenario where you have a simple SvelteKit project with a route for '/about'. If a user visits '/about', they see your beautiful 'About Us' page. However, if they mistype and go to '/abut', SvelteKit doesn't automatically render a 404 page. Instead, it often displays a blank page or a generic error message.

// src/routes/+page.svelte
<script>
  import { onMount } from 'svelte';

  onMount(() => {
    console.log('About page loaded!');
  });
</script>

<h1>About Us</h1>

This behavior stems from the fact that SvelteKit prioritizes rendering the requested route. If the route exists (like '/about'), it renders it. If not (like '/abut'), it doesn't have a specific component to display, leading to the empty or generic error.

The Solution: Custom 404 Routing with SvelteKit

The key to achieving a robust 404 experience lies in leveraging SvelteKit's powerful routing capabilities. Here's how you can create a custom 404 page and ensure it's displayed for non-existent routes:

  1. Create your 404 component:

    • Create a new Svelte file named +page.svelte inside a new directory called 404 within your src/routes folder.
    • The +page.svelte naming convention ensures that this component is used to handle the 404 route.
    // src/routes/404/+page.svelte
    <h1>Page Not Found</h1>
    <p>The page you are looking for does not exist.</p>
    
  2. Handle 404 errors in your +layout.server.js:

    • Inside your src/routes/+layout.server.js file, you need to handle 404 errors and redirect to your custom 404 page.
    // src/routes/+layout.server.js
    import { json } from '@sveltejs/kit';
    
    export function GET({ params }) {
      // Your other layout logic...
    
      // Check if the route exists
      if (!params.route) {
        return json({ message: '404 Not Found' }, { status: 404 });
      }
    
      return { body: {} };
    } 
    
  3. Customize your 404 page:

    • You can add styling, error messages, or even functionality like a search bar to your 404 component to make it more informative and user-friendly.
    // src/routes/404/+page.svelte
    <h1>Oops! Page Not Found</h1>
    <p>We couldn't find the page you're looking for. Perhaps try searching?</p>
    <form method="GET" action="/">
      <input type="text" name="q" placeholder="Search..."/>
      <button type="submit">Search</button>
    </form>
    

Understanding the Code

  1. The +layout.server.js file:

    • This file acts as a "parent" component that wraps all other pages in your SvelteKit app.
    • The GET function handles incoming requests. In this example, it checks if the requested route is valid. If not, it sends a 404 status code and redirects to the custom 404 page.
  2. The +page.svelte in the 404 folder:

    • This component acts as a dedicated error page for SvelteKit.
    • You can customize the appearance and functionality of your 404 page within this component.

Going Further: Enhancing Your 404 Experience

  • Error logging: Integrate with a logging service to capture 404 errors for better debugging and understanding user behavior.
  • Search bar: Provide a search bar within your 404 page so users can find related content.
  • Custom error messages: Based on the route requested, you can display more specific error messages, like "The product you are looking for is no longer available."

Conclusion

Handling 404 errors gracefully in SvelteKit is essential for a smooth and professional user experience. By understanding the routing mechanisms and implementing a custom 404 page, you can ensure that users are always presented with clear and helpful information, even when they encounter non-existent routes.