Svelte Search

About

What are all possible usages for hooks?

Hooks in SvelteKit are powerful tools that allow you to intercept and modify the framework's behavior at specific points in the application lifecycle. Let's break down the different types of hooks and their usages:

1. Server Hooks (src/hooks.server.js)

These hooks run on the server side and are useful for handling server-specific logic.

handle

  • Purpose: Intercept and modify incoming HTTP requests before they reach your routes.
  • Use Case: Authentication, logging, or modifying request/response headers.
  • Example:
    export async function handle({ event, resolve }) {
      // Example: Add a custom header to all responses
      const response = await resolve(event);
      response.headers.set('X-Custom-Header', 'Hello from handle hook');
      return response;
    }
    

handleFetch

  • Purpose: Modify or replace fetch requests made during server-side load functions.
  • Use Case: Adding authentication tokens to fetch requests or logging fetch calls.
  • Example:
    export async function handleFetch({ event, request, fetch }) {
      // Example: Add an auth token to all fetch requests
      request.headers.set('Authorization', `Bearer ${event.locals.token}`);
      return fetch(request);
    }
    

handleServerError

  • Purpose: Handle errors that occur during server-side rendering or data loading.
  • Use Case: Custom error logging or returning a custom error page.
  • Example:
    export function handleServerError({ error, event }) {
      console.error('Server error:', error);
      return {
        message: 'An unexpected error occurred',
        status: 500
      };
    }
    

init

  • Purpose: Run initialization code when the server starts.
  • Use Case: Setting up database connections or other global server-side resources.
  • Example:
    export async function init() {
      await db.connect(); // Initialize database connection
    }
    

2. Client Hooks (src/hooks.client.js)

These hooks run on the client side and are useful for handling client-specific logic.

handleClientError

  • Purpose: Handle errors that occur during client-side navigation or rendering.
  • Use Case: Displaying custom error messages or logging client-side errors.
  • Example:
    export function handleClientError({ error, event }) {
      console.error('Client error:', error);
      return {
        message: 'Something went wrong on the client',
        status: 500
      };
    }
    

3. Universal Hooks (src/hooks.js)

These hooks run on both the client and server, making them ideal for shared logic.

reroute

  • Purpose: Modify the URL pathname before it is used to select a route.
  • Use Case: Implementing custom routing logic, such as language-specific routes.
  • Example:
    const translated = {
      '/en/about': '/en/about',
      '/de/ueber-uns': '/de/about',
      '/fr/a-propos': '/fr/about',
    };
    
    export function reroute({ url }) {
      if (url.pathname in translated) {
        return translated[url.pathname]; // Translate the URL
      }
    }
    

handleError (Shared)

  • Purpose: Handle errors that occur on both the client and server.
  • Use Case: Centralized error handling for consistent behavior across environments.
  • Example:
    export function handleError({ error, event }) {
      console.error('Error:', error);
      return {
        message: 'An error occurred',
        status: 500
      };
    }
    

When to Use Hooks

  • Authentication: Use handle to check authentication before allowing access to routes.
  • Error Handling: Use handleServerError and handleClientError for consistent error handling.
  • Custom Routing: Use reroute for language-specific or dynamic routing.
  • Initialization: Use init for setting up global resources like database connections.
  • Request Modification: Use handleFetch to modify fetch requests, such as adding headers.

Key Considerations

  • Environment-Specific Logic: Use src/hooks.server.js for server-only logic and src/hooks.client.js for client-only logic.
  • Shared Logic: Use src/hooks.js for logic that should run in both environments.
  • Error Handling: Ensure that error-handling hooks (handleError, handleServerError, handleClientError) never throw errors themselves.

By understanding these hooks and their use cases, you can fine-tune your SvelteKit application's behavior and handle complex scenarios with ease.