Skip to main content

Svelte.404

In SvelteKit, there are two main ways to handle 404 Not Found errors: triggering them programmatically in your code and customizing the UI that users see when an error occurs.

  1. Triggering a 404 Programmatically

If you are in a load function (e.g., in +page.server.ts or +page.ts) and can't find the requested data (like a story ID that doesn't exist), you should use the error helper from @sveltejs/kit.

// src/routes/(story)/story/[id]/+page.server.ts
import { error } from '@sveltejs/kit';
import type { PageServerLoad } from './$types';

export const load: PageServerLoad = async ({ params }) => {
const story = await getStory(params.id);

if (!story) {
// This stops execution and renders the nearest +error.svelte page
error(404, {
message: 'Story not found'
});
}

return { story };
};
  1. Creating a Custom 404 Page By default, SvelteKit shows a very basic error page. To create a beautiful, branded 404 page, create a +error.svelte file in your src/routes directory (or any sub-directory to limit its scope).

Here is a premium-looking template you can use for src/routes/+error.svelte:

<script lang="ts">
import { page } from '$app/state';
import { Home } from 'lucide-svelte';
</script>

<div class="min-h-screen flex flex-col items-center justify-center bg-base-100 px-4 text-center">
<div class="max-w-md">
<h1 class="text-9xl font-bold text-primary opacity-20">404</h1>

<div class="-mt-12">
<h2 class="text-3xl font-bold mb-4">Page Not Found</h2>
<p class="text-base-content/70 mb-8">
{page.error?.message || "Oops! The page you're looking for doesn't exist or has been moved."}
</p>

<div class="flex flex-col sm:flex-row gap-4 justify-center">
<a href="/" class="btn btn-primary btn-wide shadow-lg hover:scale-105 transition-transform">
<Home size={18} class="mr-2" />
Back to Home
</a>
<button on:click={() => history.back()} class="btn btn-ghost hover:bg-base-200">
Go Back
</button>
</div>
</div>
</div>

<!-- Subtle background decoration -->
<div class="fixed top-0 left-0 w-full h-full pointer-events-none -z-10 overflow-hidden opacity-10">
<div class="absolute top-[10%] left-[5%] w-64 h-64 bg-primary rounded-full blur-3xl"></div>
<div class="absolute bottom-[10%] right-[5%] w-96 h-96 bg-secondary rounded-full blur-3xl"></div>
</div>
</div>

<style>
/* Optional: Add custom animations or glassmorphism gradients here */
</style>

Key Tips:

  • Automatic 404s: SvelteKit automatically renders the +error.svelte page if a user visits a URL that doesn't match any route in your

src/routes folder.

  • Scope: A +error.svelte file handles all errors within its directory and any subdirectories. Placing it at src/routes/+error.svelte makes it the global fallback.

  • Accessing the Error: Use $page.error (or page.error in Svelte 5) to access the status code and message passed to the error() function.