0
0
SvelteHow-ToBeginner · 3 min read

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 Response object 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 await the resolve(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.js for server-only code, hooks.client.js for 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

HookPurposeFileNotes
handleIntercepts requests and responseshooks.server.js or hooks.client.jsMust return a Response; async function
handleFetchModify fetch requests made by SvelteKithooks.server.jsUseful for adding headers to fetch calls
handleErrorCustom error handlinghooks.server.jsReceives error and event, can log or modify error response
getSessionProvide session data to clienthooks.server.jsReturns 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.