SvelteKit 10 🧡 Hooks — Intercepting requests with handle, handleFetch, handleError, reroute, and transport
SvelteKit hooks provide a global, architectural interception layer that allows you to observe, modify, and control the entire lifecycle of a request. By defining functions in hooks.server.ts and hooks.client.ts, you can inject authentication logic, perform global error logging, rewrite incoming URLs, and manage data serialization between the server and the browser. This power moves complex cross-cutting concerns out of individual routes and into a unified, predictable middleware structure.
This chapter details the primary hook functions available to SvelteKit developers. We will explore how handle acts as the primary gateway for server-side requests, how handleFetch and handleError provide observability and networking control, and how reroute and transport manage the complex mapping of URLs and data structures.
Key point: Hooks serve as the global control plane for your application; handle is the workhorse for request manipulation, handleFetch governs server-side network calls, handleError provides centralized observability, and reroute manages internal path logic, collectively enabling total orchestration of the request lifecycle.
Why exists
The authentication boilerplate problem. Without handle, every load function would require identical boilerplate to verify sessions and fetch user objects. Hooks centralize this logic, allowing you to attach locals to every request globally.
The network observability challenge. Server-side fetches often fail silently or lack the necessary authorization headers to talk to internal services. handleFetch allows you to intercept these outgoing requests, inject tokens, or log outgoing traffic patterns.
The inconsistent error reporting risk. Catching errors in hundreds of different routes is impossible to maintain. handleError provides a single point of entry for logging, allowing you to report crashes to external services like Sentry or Datadog consistently.
The routing complexity. Sometimes, you need to map unconventional URLs or localized paths (like /fr/accueil) to internal routes (/fr/home) without cluttering your filesystem. reroute provides a clean, programmatic way to handle URL resolution at the earliest possible stage.
The data serialization boundary. When complex JavaScript objects—like custom classes—move between server and client, they lose their prototype chain. transport allows you to register specialized handlers to reconstruct these objects, maintaining type integrity across the network gap.
a. The hooks.server.ts gateway: handle
The handle hook is the entry point for every request to your SvelteKit server. It receives an event object and a resolve function. By calling resolve(event), you allow the request to proceed to the internal SvelteKit router, but you can modify the event before it reaches the router, or modify the response after the router returns it.
// src/hooks.server.ts
export async function handle({ event, resolve }) {
// 1. Intercept request
event.locals.user = await getAuthUser(event.cookies.get('session'));
// 2. Proceed to route
const response = await resolve(event);
// 3. Modify response headers
response.headers.set('X-Custom-Header', 'SvelteKit');
return response;
}
The event.locals object is the standard way to pass data from your hooks to your load functions and Form Actions. By setting event.locals.user here, you make it available in every load function throughout the app, creating a clean, typed bridge for session data.
b. Network orchestration: handleFetch and handleError
handleFetch intercepts fetch calls made within your load functions and server actions. It is crucial for server-side API communication where you might need to append an Authorization header to every request without writing that logic inside your routes. handleError is your global safety net, intercepting any uncaught exception.
// src/hooks.server.ts
export async function handleFetch({ event, request, fetch }) {
if (request.url.startsWith('https://api.my-app.com')) {
request.headers.set('Authorization', `Bearer ${event.locals.token}`);
}
return fetch(request);
}
export function handleError({ error, event }) {
logToMonitoringSystem(error, event);
return { message: 'Whoops! Something went wrong.' };
}
While handle handles the incoming request from the user, handleFetch manages outgoing requests from the server to your backend or microservices. Together, they create a robust middleware layer that keeps your business logic free of infrastructure concerns.
c. Advanced mapping: reroute and transport
reroute is invoked before the server matches a URL to a route. It allows you to transform the url object, mapping different paths to the same internal route. transport is a sophisticated tool for defining how specific data types—like Date objects or custom User instances—should be serialized when they cross the server-client boundary.
// src/hooks.server.ts
export function reroute({ url }) {
if (url.pathname === '/login') return '/auth/login';
}
import { transport } from '@sveltejs/kit';
// Define how to handle specific data structures
transport.register('my-custom-class', {
encode: (value) => JSON.stringify(value),
decode: (value) => new MyClass(JSON.parse(value))
});
Using reroute keeps your filesystem clean, while transport ensures that your JavaScript objects survive the serialization process. These advanced hooks are typically used in large-scale applications where infrastructure requirements exceed standard file-system routing or simple JSON exchange.
Complete Example Session
// ============================================
// PART 1: AUTHENTICATION IN HANDLE
// ============================================
export async function handle({ event, resolve }) {
const session = event.cookies.get('s');
event.locals.user = session ? await db.find(session) : null;
return await resolve(event);
}
// ============================================
// PART 2: OUTGOING FETCH INTERCEPTOR
// ============================================
export async function handleFetch({ event, request, fetch }) {
request.headers.set('x-user-id', event.locals.user?.id || 'guest');
return fetch(request);
}
// ============================================
// PART 3: GLOBAL ERROR LOGGING
// ============================================
export function handleError({ error, event }) {
console.error(`Error at ${event.url.pathname}:`, error);
return { message: 'Unexpected server error' };
}
// ============================================
// PART 4: URL REROUTING
// ============================================
export function reroute({ url }) {
if (url.pathname.startsWith('/old-')) return url.pathname.replace('/old-', '/new-');
}
This sequence creates a hardened auth-gated middleware, automatically attaches user IDs to all internal fetches, logs errors, and provides automatic path-legacy support via rerouting.
Quick Reference
Server-side Hooks
| Hook | Purpose |
|---|---|
handle | Intercept incoming Request/Response |
handleFetch | Intercept server-side fetch |
handleError | Centralize error reporting |
reroute | Map URLs to internal routes |
Client-side Hooks
| Hook | Purpose |
|---|---|
handleError | Client-side error tracking |
Best Practices
✅ Do This:
// Always await resolve(event)
return await resolve(event); // ✅
// Namespace your local state
event.locals.user = ...; // ✅
// Only log relevant errors
if (event.isDataRequest) return; // ✅
// Use reroute for legacy cleanup
return '/new' + url.pathname; // ✅
❌ Don’t Do This:
// Don't modify the response without returning
resolve(event); // response is lost // ❌
// Don't block requests with heavy work in handle
await slowDatabaseCall(); // use caching instead // ❌
// Don't leak internals in handleError
return { message: error.stack }; // exposes secrets! // ❌
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Infinite Loop | handle resolving inside itself | Check if condition |
| Auth Failure | locals not populated correctly | Debug cookies.get |
| Serialization Loss | Complex objects passed via load | Use transport |
| Reroute Loop | Target path triggers reroute | Validate route target |
Real-World Examples
1. Session Injection
event.locals.user = await getUser(event);
2. Auth Header Proxy
request.headers.set('Authorization', token);
3. Log to Sentry
Sentry.captureException(error);
4. Legacy Redirect
if (url.pathname === '/home') return '/dashboard';
5. Cache Header Override
res.headers.set('Cache-Control', 'max-age=0');
6. Language Prefix Mapping
return url.pathname.replace('/fr', '');
7. Dark Mode Preference
event.locals.theme = event.cookies.get('theme');
8. Rate Limiting Logic
if (tooManyRequests(event)) throw error(429);
9. Custom Data Transport
transport.register('date', { ... });
10. Sanitizing Sensitive Data
response.headers.delete('X-Powered-By');
Visual
The Handle Pipeline
┌──────────────────────────────────────────────┐
│ INCOMING REQUEST │
│ │ │
│ [handle] ──► Inject Locals │
│ │ │
│ [resolve] ─► SvelteKit Router │
│ │ │
│ [response] ─► Modify Headers │
│ │ │
│ OUTGOING RESPONSE │
└──────────────────────────────────────────────┘
The Fetch Proxy
┌──────────────────────────────────────────────┐
│ LOAD FUNCTION (fetch) │
│ │ │
│ [handleFetch] ──► Add Auth Header │
│ │ │
│ INTERNAL API SERVICE │
└──────────────────────────────────────────────┘
Reroute Logic
┌──────────────────────────────────────────────┐
│ URL: /old-blog/post │
│ │ │
│ [reroute] ──► /blog/post │
│ │ │
│ ROUTER MATCHES: /blog/post │
└──────────────────────────────────────────────┘
Summary
| Item | Value |
|---|---|
handle | Interception gateway |
locals | Data bridge to load |
handleFetch | Network middleware |
handleError | Observability layer |
reroute | URL mapping |
transport | Serialization definition |
Key takeaways:
- Use
handlefor security. It is the most robust place to verify sessions and user permissions before any data is loaded. - Use
handleFetchfor API orchestration. It ensures that every server-side fetch is equipped with the necessary authentication, preventing duplication in your route code. - Centralize observability with
handleError. Don’t rely on per-route error handling; log globally to ensure you never miss a system failure. - Use
reroutesparingly. It is an advanced tool for routing cleanups or legacy support, not a replacement for good file-system structure. - Keep
handleperformant. Because every request hits this function, keep your logic lean and cache results where possible to prevent latency.
Remember: Hooks provide the surgical precision needed to manage the high-level flow of your SvelteKit application. By using handle to verify identity, handleFetch to orchestrate network traffic, and handleError to observe the system, you maintain a clean separation between your core business logic and the infrastructure required to host a production-grade application.
Stop using slow, ad-bloated tool sites! 🤮
🔎 Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)
⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free
🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!