Lesson 18 / 25
Error Pages and Redirects
error(), redirect() and +error.svelte.
Expected and unexpected errors
Call error(404, "Not found") from @sveltejs/kit in a load function, action or endpoint to produce an expected error; SvelteKit renders the nearest +error.svelte, which reads page.status and page.error.message. Any other exception is an unexpected error: the user sees a generic message and you can log details in the handleError hook. redirect(303, "/login") sends the user elsewhere; use 303 after a form POST and 307 or 308 to preserve the method. In SvelteKit 2 you call error() and redirect() directly; they throw internally, so do not wrap them in a try block that swallows them. A root src/error.html handles failures that prevent the root layout from rendering.
Guarding a route and rendering errors
A protected layout and an error page.
<!-- src/routes/account/+layout.server.ts
import { redirect } from '@sveltejs/kit';
import type { LayoutServerLoad } from './$types';
export const load: LayoutServerLoad = async ({ locals, url }) => {
if (!locals.user) {
redirect(303, `/login?next=${encodeURIComponent(url.pathname)}`);
}
return { user: locals.user };
};
-->
<!-- src/routes/+error.svelte -->
<script lang="ts">
import { page } from '$app/state';
</script>
<h1>{page.status}</h1>
<p>{page.error?.message}</p>
{#if page.status === 404}
<a href="/">Back to the home page</a>
{/if}A receptionist and a fire alarm
error(404) is a receptionist politely saying the person is not here; an unexpected exception is the fire alarm, where visitors get a calm generic message and staff get the details.
Quick check: In SvelteKit 2, how do you trigger a redirect from a server load?
- Call redirect(303, "/login") from @sveltejs/kit
- Return { redirect: "/login" }
- Set window.location in the load
- Throw new Error("redirect")
Answer
Call redirect(303, "/login") from @sveltejs/kit — redirect throws a special object for you.