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:
src/hooks.server.js
)These hooks run on the server side and are useful for handling server-specific logic.
handle
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
fetch
requests made during server-side load
functions.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
export function handleServerError({ error, event }) {
console.error('Server error:', error);
return {
message: 'An unexpected error occurred',
status: 500
};
}
init
export async function init() {
await db.connect(); // Initialize database connection
}
src/hooks.client.js
)These hooks run on the client side and are useful for handling client-specific logic.
handleClientError
export function handleClientError({ error, event }) {
console.error('Client error:', error);
return {
message: 'Something went wrong on the client',
status: 500
};
}
src/hooks.js
)These hooks run on both the client and server, making them ideal for shared logic.
reroute
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)export function handleError({ error, event }) {
console.error('Error:', error);
return {
message: 'An error occurred',
status: 500
};
}
handle
to check authentication before allowing access to routes.handleServerError
and handleClientError
for consistent error handling.reroute
for language-specific or dynamic routing.init
for setting up global resources like database connections.handleFetch
to modify fetch requests, such as adding headers.src/hooks.server.js
for server-only logic and src/hooks.client.js
for client-only logic.src/hooks.js
for logic that should run in both environments.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.