Svelte and SvelteKit course ยท Module 14: Hooks, API and Deployment
Heimdall's Watch - Hooks
In this lesson4
Welcome to Heimdall's outpost! He guards the Bifrost and sees everything. Hooks in SvelteKit are the guardians of your application - they see every request!
hooks.server.js
// src/hooks.server.js
export async function handle({ event, resolve }) {
// Before processing the request
console.log('Request:', event.url.pathname);
// Add data to locals
const session = await getSession(event.cookies.get('session'));
event.locals.user = session?.user;
// Process the request
const response = await resolve(event);
// After processing
console.log('Response status:', response.status);
return response;
}Authentication middleware
// hooks.server.js
import { redirect } from '@sveltejs/kit';
export async function handle({ event, resolve }) {
const session = event.cookies.get('session');
if (session) {
const user = await getUserFromSession(session);
event.locals.user = user;
}
// Protect routes
if (event.url.pathname.startsWith('/dashboard') && !event.locals.user) {
redirect(303, '/login');
}
return resolve(event);
}Just like in load functions, redirect() in the handle hook throws by itself, and SvelteKit turns it into a redirect response.
Several guards: sequence
When a hook does many things, split it into smaller functions and join them with the sequence helper. They run one after another, like the guard posts on the Bifrost bridge:
// hooks.server.js
import { sequence } from '@sveltejs/kit/hooks';
async function auth({ event, resolve }) {
event.locals.user = await getUserFromSession(event.cookies.get('session'));
return resolve(event);
}
async function logger({ event, resolve }) {
console.log('Request:', event.url.pathname);
return resolve(event);
}
export const handle = sequence(auth, logger);handleError
// hooks.server.js
export function handleError({ kind, error, event }) {
// kind: 'app', 'framework', 'validation' or 'unknown'
if (kind !== 'unknown') {
return error; // errors from error() pass through unchanged
}
console.error('Error:', error);
// Send to Sentry, LogRocket, etc.
Sentry.captureException(error);
return {
message: 'An error occurred'
};
}In SvelteKit 3 handleError receives every error, and the kind field tells you where it came from. You log unexpected errors (unknown) and turn them into a safe message, so the user never sees server details.
Heimdall sees everything - your hooks do too!
Code for this lesson: App.svelte
<script>
// Heimdall Guard - Hooks
// hooks.server.js - guardian of every request
let requests = $state([]);
let isAuthenticated = $state(false);
let user = $state(null);
let nextId = 1;
// Simulating handle hook
function simulateRequest(path) {
const timestamp = new Date().toLocaleTimeString();
const log = {
id: nextId++,
time: timestamp,
path,
user: isAuthenticated ? user?.name : 'anonymous'
};
requests = [log, ...requests].slice(0, 5);
// Simulating protected route
if (path.startsWith('/dashboard') && !isAuthenticated) {
return { redirect: '/login', status: 303 };
}
return { ok: true };
}
function login() {
isAuthenticated = true;
user = { name: 'Ragnar', role: 'jarl' };
}
function logout() {
isAuthenticated = false;
user = null;
}
</script>
<main class="heimdall">
<h1>Heimdall Guard - Hooks</h1>
<p class="subtitle">hooks.server.js - sees every request</p>
<section class="code">
<h2>hooks.server.js</h2>
<pre>
import {"{"} redirect {"}"} from '@sveltejs/kit';
export async function handle({"{"} event, resolve {"}"}) {"{"}
// 1. Before processing
console.log('Request:', event.url.pathname);
// 2. Add data to locals
const session = event.cookies.get('session');
event.locals.user = await getUser(session);
// 3. Protect routes
if (event.url.pathname.startsWith('/dashboard')) {"{"}
if (!event.locals.user) {"{"}
redirect(303, '/login');
{"}"}
{"}"}
// 4. Process request
const response = await resolve(event);
// 5. After processing
console.log('Status:', response.status);
return response;
{"}"}
</pre>
</section>
<section class="auth">
<h2>User status</h2>
{#if isAuthenticated}
<p>Logged in as: <strong>{user.name}</strong></p>
<button onclick={logout}>Log out</button>
{:else}
<p>Not logged in</p>
<button onclick={login}>Log in as Ragnar</button>
{/if}
</section>
<section class="test">
<h2>Test routes</h2>
<div class="paths">
<button onclick={() => simulateRequest('/')}>/ (Home)</button>
<button onclick={() => simulateRequest('/warriors')}>/warriors</button>
<button onclick={() => simulateRequest('/dashboard')}>/dashboard</button>
</div>
</section>
<section class="logs">
<h2>Request logs</h2>
{#each requests as req (req.id)}
<div class="log">
<span class="time">{req.time}</span>
<span class="path">{req.path}</span>
<span class="user">{req.user}</span>
</div>
{:else}
<p class="empty">No requests</p>
{/each}
</section>
</main>
<style>
.heimdall {
font-family: 'Georgia', serif;
max-width: 600px;
margin: 0 auto;
padding: 2rem;
background: linear-gradient(135deg, #0a1628 0%, #1a2d4e 100%);
color: #b8d4f7;
min-height: 100vh;
}
h1 {
color: #ffd700;
text-align: center;
}
.subtitle {
text-align: center;
color: #6a8ab9;
}
section {
background: rgba(74, 144, 217, 0.1);
border: 1px solid #4a90d9;
border-radius: 8px;
padding: 1rem;
margin: 1rem 0;
}
h2 {
color: #4a90d9;
font-size: 1rem;
margin-top: 0;
}
pre {
background: rgba(0,0,0,0.5);
padding: 1rem;
border-radius: 4px;
font-size: 0.75rem;
overflow-x: auto;
}
strong {
color: #ffd700;
}
button {
padding: 0.5rem 1rem;
background: #1e3a5f;
color: #b8d4f7;
border: 1px solid #4a90d9;
border-radius: 4px;
cursor: pointer;
margin-right: 0.5rem;
}
.paths {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
}
.log {
display: flex;
gap: 1rem;
padding: 0.5rem;
background: rgba(0,0,0,0.3);
border-radius: 4px;
margin-bottom: 0.25rem;
font-size: 0.9rem;
}
.time {
color: #6a8ab9;
font-family: monospace;
}
.path {
color: #ffd700;
flex: 1;
}
.user {
color: #90ee90;
}
.empty {
color: #6a8ab9;
font-style: italic;
}
</style>Docs entries used in this lesson
Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. In which file do we define server hooks?
2. What does the handle() function do in hooks.server.js?