0
0
Svelteframework~5 mins

Hooks (handle, handleError, handleFetch) in Svelte

Choose your learning style9 modes available
Introduction

Hooks let you run code at key moments in your app's life. They help you manage requests, errors, and responses easily.

You want to add a loading spinner or log every request your app makes.
You need to catch and show friendly messages when something goes wrong.
You want to modify data coming from the server before your app uses it.
You want to add headers or tokens to every fetch request automatically.
Syntax
Svelte
export const handle = async ({ event, resolve }) => {
  // your code here
  const response = await resolve(event);
  return response;
};

export const handleError = ({ error, event }) => {
  // your code here
};

export const handleFetch = async ({ request, fetch }) => {
  // your code here
  const response = await fetch(request);
  return response;
};

handle runs on every request and response cycle.

handleError runs when an error happens during a request.

Examples
This logs the URL of every request your app receives.
Svelte
export const handle = async ({ event, resolve }) => {
  console.log('Request URL:', event.url.href);
  const response = await resolve(event);
  return response;
};
This logs error messages to the console when something goes wrong.
Svelte
export const handleError = ({ error, event }) => {
  console.error('Error caught:', error.message);
};
This adds a custom header to every fetch request your app makes.
Svelte
export const handleFetch = async ({ request, fetch }) => {
  const modifiedRequest = new Request(request, {
    headers: { ...Object.fromEntries(request.headers), 'X-Custom-Header': 'MyValue' }
  });
  const response = await fetch(modifiedRequest);
  return response;
};
Sample Program

This example shows all three hooks working together. It logs requests, fetches, and errors with clear messages.

Svelte
export const handle = async ({ event, resolve }) => {
  console.log(`Handling request for: ${event.url.pathname}`);
  const response = await resolve(event);
  return response;
};

export const handleError = ({ error, event }) => {
  console.error(`Error on ${event.url.pathname}: ${error.message}`);
};

export const handleFetch = async ({ request, fetch }) => {
  console.log(`Fetching: ${request.url}`);
  const response = await fetch(request);
  return response;
};
OutputSuccess
Important Notes

Hooks run on the server side in SvelteKit, so you can safely handle secrets here.

Always return the response from handle and handleFetch to keep the app working.

Use handleError to log or show user-friendly error messages.

Summary

Hooks let you run code during requests, errors, and fetches.

handle manages requests and responses.

handleError catches and handles errors.

handleFetch lets you change fetch requests and responses.