Overview
There are three hooks files, all optional:src/hooks.server.js
Server-only hooks
src/hooks.client.js
Client-only hooks
src/hooks.js
Universal hooks (both)
Server hooks
The following hooks can be added tosrc/hooks.server.js:
handle
This function runs every time the SvelteKit server receives a request and determines the response. It receives anevent object and a resolve function that renders the route.
Requests for static assets and prerendered pages are not handled by SvelteKit.
Advanced resolve options
Theresolve function accepts a second parameter with the following options:
function
Applies custom transforms to HTML chunks. Useful for search-and-replace operations.
function
Determines which headers are included in serialized responses when a
load function uses fetch.function
Determines which files are added to the
<head> tag for preloading.Complete example with all options
Complete example with all options
handleFetch
Modify or replacefetch requests that run on the server during SSR or prerendering.
handleValidationError
Called when a remote function receives an argument that doesn’t match its schema.Shared hooks
These hooks work in bothsrc/hooks.server.js and src/hooks.client.js:
handleError
Called when an unexpected error is thrown during loading or rendering.1
Log the error
Send errors to a reporting service like Sentry
2
Generate safe representation
Return a sanitized error object that’s safe to show users
3
Add custom properties
Include tracking IDs or other custom fields
Make sure that
handleError never throws an error itself.init
Runs once when the server starts or the app initializes in the browser.Universal hooks
These hooks run on both server and client (insrc/hooks.js):
reroute
Runs beforehandle and changes how URLs are translated into routes.
Using
reroute will not change the browser’s address bar or the value of event.url.transport
Allows custom types to be serialized across the server/client boundary.Sequencing multiple hooks
You can use thesequence helper to run multiple handle functions:
Learn more
Follow the interactive tutorial on hooks