How to Use Hooks in SvelteKit: Syntax and Examples
In SvelteKit,
hooks.server.js and hooks.client.js let you run code during server or client requests. You export functions like handle to intercept requests and responses, enabling tasks like authentication or logging.Syntax
SvelteKit hooks are special functions exported from hooks.server.js or hooks.client.js. The main hook is handle, which receives a request event and a function to resolve it. You can modify the request or response here.
Example parts:
handle({ event, resolve }): main function to intercept requests.event: contains request info like URL, cookies.resolve(event): calls the next step to get the response.- Return a
Responseobject to send back.
javascript
export async function handle({ event, resolve }) { // You can read or modify the request here const response = await resolve(event); // You can modify the response here return response; }
Example
This example shows a handle hook that adds a custom header to every response. It demonstrates how to intercept requests and modify responses globally.
javascript
export async function handle({ event, resolve }) { const response = await resolve(event); response.headers.set('X-Custom-Header', 'Hello from hook'); return response; }
Output
All responses include the HTTP header: X-Custom-Header: Hello from hook
Common Pitfalls
Common mistakes when using hooks include:
- Not returning the response from
handle, which breaks the request flow. - Forgetting to
awaittheresolve(event)call, causing unexpected behavior. - Modifying the request object directly instead of cloning or using event methods.
- Using hooks in the wrong file (
hooks.server.jsfor server-only code,hooks.client.jsfor client-only).
javascript
/* Wrong: missing await and no return */ export function handle({ event, resolve }) { resolve(event); } /* Right: await and return response */ export async function handle({ event, resolve }) { const response = await resolve(event); return response; }
Quick Reference
| Hook | Purpose | File | Notes |
|---|---|---|---|
| handle | Intercepts requests and responses | hooks.server.js or hooks.client.js | Must return a Response; async function |
| handleFetch | Modify fetch requests made by SvelteKit | hooks.server.js | Useful for adding headers to fetch calls |
| handleError | Custom error handling | hooks.server.js | Receives error and event, can log or modify error response |
| getSession | Provide session data to client | hooks.server.js | Returns session object accessible in load functions |
Key Takeaways
Use
handle in hooks.server.js to run code on every server request.Always
await the resolve(event) call and return its response.Modify requests or responses carefully without breaking the flow.
Use
hooks.client.js for client-side hooks and hooks.server.js for server-side.Common hooks include
handle, handleFetch, handleError, and getSession.