Svelte 66 ๐งก Server Event Hooks (hooks.server.js: handle, handleFetch, handleError)
SvelteKit provides a robust mechanism to intercept the server-side lifecycle of every request through a file called hooks.server.js. This file acts as a middleware layer that sits between the incoming HTTP request and your application’s logic. By exporting specific functions from this file, you gain granular control over authentication, localization, response headers, and error reporting.
Hooks run exclusively on the server, meaning they have access to server-side APIs and node environment variables that are unavailable in the browser. This chapter explores the primary hooks provided by SvelteKit: handle, which manages the request/response cycle; handleFetch, which intercepts outgoing fetch calls from your server-side load functions; and handleError, which centralizes your global exception handling.
Key point: The hooks.server.js file is the entry point for global server logic, allowing you to modify events, inject custom headers, intercept network calls, and transform errors before they are returned to the client.
Why exists
The authentication problem. Many apps need to verify a user’s session cookie or JWT on every single route. handle exists to centralize this logic so it doesn’t need to be repeated in every +page.server.js file.
The response transformation problem. Sometimes you need to inject custom security headers like CSP or CORS, or perform transformations on the rendered HTML. The handle function gives you the final Response object before it hits the network.
The internal API fetch problem. When your server-side load functions call your own internal API, they might need custom headers or proxying logic. handleFetch intercepts these calls, allowing you to pass auth tokens from the incoming request to your internal API.
The error visibility problem. When a 500 error occurs, you often need to log it to a service like Sentry or LogRocket. handleError catches all unhandled exceptions, providing a unified place to report the error and return a sanitized message to the user.
The request enrichment problem. You may need to inject custom data into the event.locals object, which is passed throughout the entire request lifecycle. handle is the perfect place to calculate this data once and make it available globally.
a. The handle hook
The handle function is the most common hook. It receives the event object (containing the request and context) and a resolve function. You can modify the request, call resolve to continue the pipeline, and then modify the resulting response.
export async function handle({ event, resolve }) {
// Logic here runs before the route handler
event.locals.user = await getAuthUser(event.cookies);
const response = await resolve(event);
// Logic here runs after the route handler
response.headers.set('x-custom-header', 'SvelteKit-Hooks');
return response;
}
The resolve function executes the actual route rendering. By calling it, you pass the event object forward. Any changes you make to event.locals before calling resolve become available in your +page.server.js and +layout.server.js files, making it the primary way to inject data.
b. The handleFetch hook
The handleFetch hook intercepts fetch calls made inside load functions on the server. This is critical for authenticating requests between your SvelteKit server and your back-end microservices or APIs.
export async function handleFetch({ event, request, fetch }) {
if (request.url.startsWith('https://api.myapp.com/')) {
// Add auth headers from the incoming request to the internal API call
request.headers.set('Authorization', event.locals.token);
}
return fetch(request);
}
By intercepting the call, you can forward session information without having to manually pass it into every fetch call across your application. This effectively centralizes how your app talks to your data sources.
c. The handleError hook
The handleError hook runs whenever an error occurs during the execution of a load function, an action, or a page render. It allows you to transform the error into a response that is safe to send to the browser.
export function handleError({ error, event }) {
// Log to external logging service
console.error('Captured by hook:', error);
return {
message: 'An unexpected internal error occurred.',
code: 'INTERNAL_SERVER_ERROR'
};
}
In production, you rarely want to expose the full stack trace to the end user. handleError ensures you can log the details privately while displaying a helpful, generic message to the client.
Complete Example Session
// ============================================
// PART 1: AUTHENTICATION IN HANDLE
// ============================================
export async function handle({ event, resolve }) {
const session = event.cookies.get('session');
event.locals.user = session ? await verify(session) : null;
return await resolve(event);
}
// ============================================
// PART 2: MODIFYING RESPONSE
// ============================================
// Adding security headers after resolving
const response = await resolve(event);
response.headers.set('X-Frame-Options', 'DENY');
return response;
// ============================================
// PART 3: INTERCEPTING FETCH
// ============================================
export async function handleFetch({ event, request, fetch }) {
if (request.url.includes('/api/private')) {
request.headers.set('Auth', event.locals.user?.token);
}
return fetch(request);
}
// ============================================
// PART 4: CENTRALIZED ERROR LOGGING
// ============================================
export function handleError({ error, event }) {
// Report to Sentry or similar
reportToMonitoring(error, event.request.url);
return { message: 'Oops' };
}
These parts demonstrate the lifecycle: first authenticating the user via handle, modifying headers, proxying secure internal fetch calls via handleFetch, and finally ensuring errors are captured via handleError.
Quick Reference
Hooks
| Hook | Purpose |
|---|---|
handle | Intercepts requests/responses |
handleFetch | Intercepts server-side fetch |
handleError | Global error handler |
Lifecycle Context
| Object | Definition |
|---|---|
event.locals | Shared server state |
resolve() | Executes route/page logic |
event.cookies | Access cookies for auth |
Best Practices
โ Do This:
// Use locals to pass data to load functions
event.locals.user = user; // โ
// Always call resolve(event) in handle
return await resolve(event); // โ
// Sanitize errors in handleError
return { message: 'Safe message' }; // โ
โ Don’t Do This:
// Don't leak stack traces in production
throw error; // โ
// Don't block the request for too long
await longRunningExternalTask(); // โ
// Don't mutate the event object recklessly
event = {}; // โ
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
Not returning resolve | Forgotten return statement | Always return resolve(event) |
| Blocking performance | Expensive logic in handle | Use caching or memoization |
| Leaking secrets | Printing event to logs | Log only specific properties |
| Missing headers | Overwriting vs appending | Use headers.set() or append() |
Real-World Examples
1. JWT Verification
event.locals.user = jwt.verify(token, secret);
2. CORS Headers
response.headers.set('Access-Control-Allow-Origin', '*');
3. Internationalization
const lang = event.request.headers.get('accept-language');
event.locals.lang = lang;
4. Environment-based Security
if (process.env.NODE_ENV === 'production') { /* enforce SSL */ }
5. API Proxy Header
request.headers.set('X-User-ID', event.locals.user.id);
6. Custom Error Response
return { message: 'Auth required', status: 401 };
7. Cookie Deletion
event.cookies.delete('session', { path: '/' });
8. Request Logging
console.log(`Request: ${event.url.pathname}`);
9. Theme Injection
event.locals.theme = 'dark';
10. Rate Limiting Check
if (isRateLimited(event.clientAddress)) throw new Error('Too many');
Visual
The Request/Response Pipeline
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Incoming Request โ
โ โ โ
โ โผ โ
โ handle({ event, resolve }) โโโบ Modify Locals โ
โ โ โ
โ โผ โ
โ resolve(event) โโโบ Load Functions / Actions โ
โ โ โ
โ โผ โ
โ handle({ event, resolve }) โโโบ Modify Response โ
โ โ โ
โ โผ โ
โ Outgoing Response โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
The Fetch Interception
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Server-Side Load Function โ
โ fetch('/api/user') โ
โ โ โ
โ โผ โ
โ handleFetch({ event, request, fetch }) โ
โ โ โ
โ โผ โ
โ Inject Auth Headers โโโ Read event.locals โ
โ โ โ
โ โผ โ
โ Actual Network Request to API โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
The Error Flow
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Application Code (Throw Error) โ
โ โ โ
โ โผ โ
โ handleError({ error, event }) โ
โ โ โ
โ โผ โ
โ Report to Monitoring Service (Log) โ
โ โ โ
โ โผ โ
โ Return Cleaned Error Object to Client โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Summary
| Item | Value |
|---|---|
| File Name | hooks.server.js |
| Primary Hook | handle |
| Outgoing Hook | handleFetch |
| Error Hook | handleError |
| Context Object | event.locals |
| Scope | Server-only |
Key takeaways:
handleis your middleware. It gives you power over every request and response, ideal for session management and header injection.event.localsis your state bus. Populate it inhandleto pass information throughout the server-side lifecycle.handleFetchproxies your calls. It allows you to append secure data (like session tokens) to internal API requests automatically.handleErrorprotects your users. It provides a clean boundary where you can log sensitive server-side errors without exposing them in the browser.- Hooks only run on the server. They cannot access client-side browser APIs, making them the secure choice for handling secrets.
Remember: hooks.server.js is the most powerful customization point in a SvelteKit application. Because every single request passes through these functions, keep your logic lean, performant, and secure. Use event.locals to store data you calculated once, use handleFetch to keep your internal communication clean, and rely on handleError to maintain a professional, secure production environment.
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!