| | |

Svelte 66 ๐Ÿงก Server Event Hooks (hooks.server.js: handle, handleFetch, handleError)

โฑ๏ธ Estimated read: 7 min | |

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

HookPurpose
handleIntercepts requests/responses
handleFetchIntercepts server-side fetch
handleErrorGlobal error handler

Lifecycle Context

ObjectDefinition
event.localsShared server state
resolve()Executes route/page logic
event.cookiesAccess 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

PitfallWhy It HappensFix
Not returning resolveForgotten return statementAlways return resolve(event)
Blocking performanceExpensive logic in handleUse caching or memoization
Leaking secretsPrinting event to logsLog only specific properties
Missing headersOverwriting vs appendingUse 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

ItemValue
File Namehooks.server.js
Primary Hookhandle
Outgoing HookhandleFetch
Error HookhandleError
Context Objectevent.locals
ScopeServer-only

Key takeaways:

  • handle is your middleware. It gives you power over every request and response, ideal for session management and header injection.
  • event.locals is your state bus. Populate it in handle to pass information throughout the server-side lifecycle.
  • handleFetch proxies your calls. It allows you to append secure data (like session tokens) to internal API requests automatically.
  • handleError protects 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.

Was this helpful?


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!