‘Hooks’ are app-wide functions you declare that SvelteKit will call in response to specific events, giving you fine-grained control over the framework’s behaviour.
There are three hooks files, all optional:
src/hooks.server.js — your app’s server hooks
src/hooks.client.js — your app’s client hooks
src/hooks.js — your app’s hooks that run on both the client and server
Code in these modules will run when the application starts up, making them useful for initializing database clients and so on.
handle
Can be added to src/hooks.server.js
This function runs every time the SvelteKit server receives a request — whether that happens while the app is running, or during prerendering — and determines the response. It receives an event object representing the request and a function called resolve, which renders the route and generates a Response. This allows you to modify response headers or bodies, or bypass SvelteKit entirely (for implementing routes programmatically, for example).
In the context of a remote function request initiated by the client, this relates to the page the remote function
was called from, not the URL of the endpoint SvelteKit creates for the remote function. Never use this to determine
whether or not a user is authorized to access certain data, as these values are part of the request which could be manipulated.
.pathname(property)URL.pathname:string
The pathname property of the URL interface represents a location in a hierarchical structure. It is a string constructed from a list of path segments, each of which is prefixed by a / character.
Returns true if the sequence of elements of searchString converted to a String is the
same as the corresponding elements of this object (converted to a String) starting at
position. Otherwise returns false.
The handle hook runs every time the SvelteKit server receives a request and
determines the response.
It receives an event object representing the request and a function called resolve, which renders the route and generates a Response.
This allows you to modify response headers or bodies, or bypass SvelteKit entirely (for implementing routes programmatically, for example).
The handle hook runs every time the SvelteKit server receives a request and
determines the response.
It receives an event object representing the request and a function called resolve, which renders the route and generates a Response.
This allows you to modify response headers or bodies, or bypass SvelteKit entirely (for implementing routes programmatically, for example).
In the context of a remote function request initiated by the client, this relates to the page the remote function
was called from, not the URL of the endpoint SvelteKit creates for the remote function. Never use this to determine
whether or not a user is authorized to access certain data, as these values are part of the request which could be manipulated.
.pathname(property)URL.pathname:string
The pathname property of the URL interface represents a location in a hierarchical structure. It is a string constructed from a list of path segments, each of which is prefixed by a / character.
Returns true if the sequence of elements of searchString converted to a String is the
same as the corresponding elements of this object (converted to a String) starting at
position. Otherwise returns false.
Requests for static assets — which includes pages that were already prerendered — are not handled by SvelteKit.
If the handle hook runs as part of a remote function request initiated by the client, route, params and url relate to the page the remote function was called from, not the URL of the endpoint SvelteKit creates for the remote function. Never use them to determine whether or not a user is authorized to access certain data, as these values are part of the request which could be manipulated. Queries are also not re-run when the user navigates (unless the argument to the query changes as a result of navigation), and so you should be mindful of how you use these values.
If unimplemented, defaults to ({ event, resolve }) => resolve(event).
During prerendering, SvelteKit crawls your pages for links and renders each route it finds. Rendering the route invokes the handle function (and all other route dependencies, like load). If you need to exclude some code from running during this phase, check that the app is not building beforehand.
You can define multiple handle functions and execute them with the sequence helper function.
resolve also supports a second, optional parameter that gives you more control over how the response will be rendered. That parameter is an object that can have the following fields:
transformPageChunk(opts: { html: string, done: boolean }): MaybePromise<string | undefined> — applies custom transforms to HTML. If done is true, it’s the final chunk. Chunks are not guaranteed to be well-formed HTML (they could include an element’s opening tag but not its closing tag, for example) but they will always be split at sensible boundaries such as %sveltekit.head% or layout/page components.
filterSerializedResponseHeaders(name: string, value: string): boolean — determines which headers should be included in serialized responses when a load function loads a resource with fetch. By default, none will be included.
preload(input: { type: 'js' | 'css' | 'font' | 'asset', path: string }): boolean — determines which files should be preloaded. Files are preloaded via <link> tags added to the <head> tag; if output.linkHeaderPreload is enabled, dynamically rendered pages use the Link response header instead. The method is called with each file that was found at build time while constructing the code chunks — so if you for example have import './styles.css in your +page.svelte, preload will be called with the resolved path to that CSS file when visiting that page. Note that in dev mode preload is not called, since it depends on analysis that happens at build time. Preloading can improve performance by downloading assets sooner, but it can also hurt if too much is downloaded unnecessarily. By default, js and css files will be preloaded. asset files are not preloaded at all currently, but we may add this later after evaluating feedback.
Applies custom transforms to HTML. If done is true, it's the final chunk. Chunks are not guaranteed to be well-formed HTML
(they could include an element's opening tag but not its closing tag, for example)
but they will always be split at sensible boundaries such as %sveltekit.head% or layout/page components.
input
the html chunk and the info if this is the last chunk
Replaces text in a string, using a regular expression or search string.
searchValue
A string or regular expression to search for.
replaceValue
A string containing the text to replace. When the {@linkcode searchValue} is a RegExp, all matches are replaced if the g flag is set (or only those matches at the beginning, if the y flag is also present). Otherwise, only the first match of {@linkcode searchValue} is replaced.
Determines which headers should be included in serialized responses when a load function loads a resource with fetch.
By default, none will be included.
Returns true if the sequence of elements of searchString converted to a String is the
same as the corresponding elements of this object (converted to a String) starting at
position. Otherwise returns false.
Returns true if searchString appears as a substring of the result of converting this
object to a String, at one or more positions that are
greater than or equal to position; otherwise, returns false.
searchString
search string
position
If position is undefined, 0 is assumed, so as to search all of the String.
The handle hook runs every time the SvelteKit server receives a request and
determines the response.
It receives an event object representing the request and a function called resolve, which renders the route and generates a Response.
This allows you to modify response headers or bodies, or bypass SvelteKit entirely (for implementing routes programmatically, for example).
The handle hook runs every time the SvelteKit server receives a request and
determines the response.
It receives an event object representing the request and a function called resolve, which renders the route and generates a Response.
This allows you to modify response headers or bodies, or bypass SvelteKit entirely (for implementing routes programmatically, for example).
Applies custom transforms to HTML. If done is true, it's the final chunk. Chunks are not guaranteed to be well-formed HTML
(they could include an element's opening tag but not its closing tag, for example)
but they will always be split at sensible boundaries such as %sveltekit.head% or layout/page components.
input
the html chunk and the info if this is the last chunk
Replaces text in a string, using a regular expression or search string.
searchValue
A string or regular expression to search for.
replaceValue
A string containing the text to replace. When the {@linkcode searchValue} is a RegExp, all matches are replaced if the g flag is set (or only those matches at the beginning, if the y flag is also present). Otherwise, only the first match of {@linkcode searchValue} is replaced.
Determines which headers should be included in serialized responses when a load function loads a resource with fetch.
By default, none will be included.
Returns true if the sequence of elements of searchString converted to a String is the
same as the corresponding elements of this object (converted to a String) starting at
position. Otherwise returns false.
Returns true if searchString appears as a substring of the result of converting this
object to a String, at one or more positions that are
greater than or equal to position; otherwise, returns false.
searchString
search string
position
If position is undefined, 0 is assumed, so as to search all of the String.
Note that resolve(...) will never throw an error, it will always return a Promise<Response> with the appropriate status code. If an error is thrown elsewhere during handle, it is treated as fatal, and SvelteKit will respond with a JSON representation of the error or a fallback error page — which can be customised via src/error.html — depending on the Accept header. You can read more about error handling here.
locals
To add custom data to the request, which is passed to handlers in +server.js and server load functions, populate the event.locals object, as shown below.
Gets a cookie that was previously set with cookies.set, or from the request headers.
name
the name of the cookie
opts
the options, passed directly to cookie.parse. See documentation here
('sessionid'));constresponseconstresponse:Response=awaitresolve(parameter)resolve:(event:RequestEvent,opts?:ResolveOptions)=>MaybePromise<Response>(event(parameter)event:RequestEvent<Record<string,string>,string|null>); // Note that modifying response headers isn't always safe. // Response objects can have immutable headers // (e.g. Response.redirect() returned from an endpoint). // Modifying immutable headers throws a TypeError. // In that case, clone the response or avoid creating a // response object with immutable headers.responseconstresponse:Response.headers(property)Response.headers:Headers
The headers read-only property of the Response interface contains the Headers object associated with the response.
The set() method of the Headers interface sets a new value for an existing header inside a Headers object, or adds the header if it does not already exist.
The handle hook runs every time the SvelteKit server receives a request and
determines the response.
It receives an event object representing the request and a function called resolve, which renders the route and generates a Response.
This allows you to modify response headers or bodies, or bypass SvelteKit entirely (for implementing routes programmatically, for example).
The handle hook runs every time the SvelteKit server receives a request and
determines the response.
It receives an event object representing the request and a function called resolve, which renders the route and generates a Response.
This allows you to modify response headers or bodies, or bypass SvelteKit entirely (for implementing routes programmatically, for example).
Gets a cookie that was previously set with cookies.set, or from the request headers.
name
the name of the cookie
opts
the options, passed directly to cookie.parse. See documentation here
('sessionid'));constresponseconstresponse:Response=awaitresolve(parameter)resolve:(event:RequestEvent,opts?:ResolveOptions)=>MaybePromise<Response>(event(parameter)event:RequestEvent<Record<string,string>,string|null>); // Note that modifying response headers isn't always safe. // Response objects can have immutable headers // (e.g. Response.redirect() returned from an endpoint). // Modifying immutable headers throws a TypeError. // In that case, clone the response or avoid creating a // response object with immutable headers.responseconstresponse:Response.headers(property)Response.headers:Headers
The headers read-only property of the Response interface contains the Headers object associated with the response.
The set() method of the Headers interface sets a new value for an existing header inside a Headers object, or adds the header if it does not already exist.
This function allows you to modify (or replace) the result of an event.fetch call that runs on the server (or during prerendering) inside an endpoint, load, action, handle, handleError or reroute.
For example, your load function might make a request to a public URL like https://api.yourapp.com when the user performs a client-side navigation to the respective page, but during SSR it might make sense to hit the API directly (bypassing whatever proxies and load balancers sit between it and the public internet).
Returns true if the sequence of elements of searchString converted to a String is the
same as the corresponding elements of this object (converted to a String) starting at
position. Otherwise returns false.
('https://api.yourapp.com/')){ // clone the original request, but change the URLrequest(parameter)request:Request=newRequestvarRequest:new(input:RequestInfo|URL,init?:RequestInit)=>Request
The Request interface of the Fetch API represents a resource request.
Replaces text in a string, using a regular expression or search string.
searchValue
A string or regular expression to search for.
replaceValue
A string containing the text to replace. When the {@linkcode searchValue} is a RegExp, all matches are replaced if the g flag is set (or only those matches at the beginning, if the y flag is also present). Otherwise, only the first match of {@linkcode searchValue} is replaced.
The handleFetch hook allows you to modify (or replace) the result of an event.fetch call that runs on the server (or during prerendering) inside an endpoint, load, action, handle, handleError or reroute.
The handleFetch hook allows you to modify (or replace) the result of an event.fetch call that runs on the server (or during prerendering) inside an endpoint, load, action, handle, handleError or reroute.
Returns true if the sequence of elements of searchString converted to a String is the
same as the corresponding elements of this object (converted to a String) starting at
position. Otherwise returns false.
('https://api.yourapp.com/')){ // clone the original request, but change the URLrequest(parameter)request:Request=newRequestvarRequest:new(input:RequestInfo|URL,init?:RequestInit)=>Request
The Request interface of the Fetch API represents a resource request.
Replaces text in a string, using a regular expression or search string.
searchValue
A string or regular expression to search for.
replaceValue
A string containing the text to replace. When the {@linkcode searchValue} is a RegExp, all matches are replaced if the g flag is set (or only those matches at the beginning, if the y flag is also present). Otherwise, only the first match of {@linkcode searchValue} is replaced.
Requests made with event.fetch follow the browser’s credentials model — for same-origin requests, cookie and authorization headers are forwarded unless the credentials option is set to "omit". For cross-origin requests, cookie will be included if the request URL belongs to a subdomain of the app — for example if your app is on my-domain.com, and your API is on api.my-domain.com, cookies will be included in the request.
There is one caveat: if your app and your API are on sibling subdomains — www.my-domain.com and api.my-domain.com for example — then a cookie belonging to a common parent domain like my-domain.com will not be included, because SvelteKit has no way to know which domain the cookie belongs to. In these cases you will need to manually include the cookie using handleFetch:
Returns true if the sequence of elements of searchString converted to a String is the
same as the corresponding elements of this object (converted to a String) starting at
position. Otherwise returns false.
The set() method of the Headers interface sets a new value for an existing header inside a Headers object, or adds the header if it does not already exist.
The get() method of the Headers interface returns a byte string of all the values of a header within a Headers object with a given name. If the requested header doesn't exist in the Headers object, it returns null.
The handleFetch hook allows you to modify (or replace) the result of an event.fetch call that runs on the server (or during prerendering) inside an endpoint, load, action, handle, handleError or reroute.
The handleFetch hook allows you to modify (or replace) the result of an event.fetch call that runs on the server (or during prerendering) inside an endpoint, load, action, handle, handleError or reroute.
Returns true if the sequence of elements of searchString converted to a String is the
same as the corresponding elements of this object (converted to a String) starting at
position. Otherwise returns false.
The set() method of the Headers interface sets a new value for an existing header inside a Headers object, or adds the header if it does not already exist.
The get() method of the Headers interface returns a byte string of all the values of a header within a Headers object with a given name. If the requested header doesn't exist in the Headers object, it returns null.
This hook is called when a remote function is called with an argument that does not match the provided Standard Schema. It must return an object matching the shape of App.Error.
Say you have a remote function that expects a string as its argument ...
...but it is called with something that doesn’t match the schema — such as a number (e.g. await getTodos(1)) — then validation will fail, the server will respond with a 400 status code, and the function will throw with the message ‘Bad Request’.
To customise this message and add additional properties to the error object, implement handleValidationError:
Be thoughtful about what information you expose here, as the most likely reason for validation to fail is that someone is sending malicious requests to your server.
handleError
Can be added to src/hooks.server.js and src/hooks.client.js
If an unexpected error is thrown during loading, rendering, or from an endpoint, this function will be called with the error, event, status code and message. This allows for two things:
you can log the error
you can generate a custom representation of the error that is safe to show to users, omitting sensitive details like messages and stack traces. The returned value, which defaults to { message }, becomes the value of page.error.
For errors thrown from your code (or library code called by your code) the status will be 500 and the message will be “Internal Error”. While error.message may contain sensitive information that should not be exposed to users, message is safe (albeit meaningless to the average user).
To add more information to the page.error object in a type-safe way, you can customize the expected shape by declaring an App.Error interface (which must include message: string, to guarantee sensible fallback behavior). This allows you to — for example — append a tracking ID for users to quote in correspondence with your technical support staff:
It's possible to tell SvelteKit how to type objects inside your app by declaring the App namespace. By default, a new project will have a file called src/app.d.ts containing the following:
The export {} line exists because without it, the file would be treated as an ambient module which prevents you from adding import declarations.
If you need to add ambient declare module declarations, do so in a separate file like src/ambient.d.ts.
By populating these interfaces, you will gain type safety when using event.locals, event.platform, and data from load functions.
{interfaceErrorinterfaceApp.Error
Defines the common shape of expected and unexpected errors. Expected errors are thrown using the error function. Unexpected errors are handled by the handleError hooks which should return this shape.
The randomUUID() method of the Crypto interface is used to generate a v4 UUID using a cryptographically secure random number generator.
Available only in secure contexts.
(); // example integration with https://sentry.io/Sentry(alias)module"@sentry/sveltekit"importSentry.captureExceptionconstcaptureException:(error:any,opts:any)=>void(error(parameter)error:unknown,{extra(property)extra:{event:RequestEvent<Record<string,string>,string|null>;errorId:`${string}-${string}-${string}-${string}-${string}`;status:number;}:{event(property)event:RequestEvent<Record<string,string>,string|null>,errorId(property)errorId:`${string}-${string}-${string}-${string}-${string}`,status(property)status:number}});return{message(property)App.Error.message:string:'Whoops!',errorId(property)errorId:`${string}-${string}-${string}-${string}-${string}`};}
The server-side handleError hook runs when an unexpected error is thrown while responding to a request.
If an unexpected error is thrown during loading or rendering, this function will be called with the error and the event.
Make sure that this function never throws an error.
The server-side handleError hook runs when an unexpected error is thrown while responding to a request.
If an unexpected error is thrown during loading or rendering, this function will be called with the error and the event.
Make sure that this function never throws an error.
The randomUUID() method of the Crypto interface is used to generate a v4 UUID using a cryptographically secure random number generator.
Available only in secure contexts.
(); // example integration with https://sentry.io/Sentry(alias)module"@sentry/sveltekit"importSentry.captureExceptionconstcaptureException:(error:any,opts:any)=>void(error(parameter)error:unknown,{extra(property)extra:{event:RequestEvent<Record<string,string>,string|null>;errorId:`${string}-${string}-${string}-${string}-${string}`;status:number;}:{event(property)event:RequestEvent<Record<string,string>,string|null>,errorId(property)errorId:`${string}-${string}-${string}-${string}-${string}`,status(property)status:number}});return{message(property)App.Error.message:string:'Whoops!',errorId(property)errorId:`${string}-${string}-${string}-${string}-${string}`};};
The randomUUID() method of the Crypto interface is used to generate a v4 UUID using a cryptographically secure random number generator.
Available only in secure contexts.
(); // example integration with https://sentry.io/Sentry(alias)module"@sentry/sveltekit"importSentry.captureExceptionconstcaptureException:(error:any,opts:any)=>void(error(parameter)error:unknown,{extra(property)extra:{event:NavigationEvent<Record<string,string>,string|null>;errorId:`${string}-${string}-${string}-${string}-${string}`;status:number;}:{event(property)event:NavigationEvent<Record<string,string>,string|null>,errorId(property)errorId:`${string}-${string}-${string}-${string}-${string}`,status(property)status:number}});return{message(property)App.Error.message:string:'Whoops!',errorId(property)errorId:`${string}-${string}-${string}-${string}-${string}`};}
The client-side handleError hook runs when an unexpected error is thrown while navigating.
If an unexpected error is thrown during loading or the following render, this function will be called with the error and the event.
Make sure that this function never throws an error.
The client-side handleError hook runs when an unexpected error is thrown while navigating.
If an unexpected error is thrown during loading or the following render, this function will be called with the error and the event.
Make sure that this function never throws an error.
The randomUUID() method of the Crypto interface is used to generate a v4 UUID using a cryptographically secure random number generator.
Available only in secure contexts.
(); // example integration with https://sentry.io/Sentry(alias)module"@sentry/sveltekit"importSentry.captureExceptionconstcaptureException:(error:any,opts:any)=>void(error(parameter)error:unknown,{extra(property)extra:{event:NavigationEvent<Record<string,string>,string|null>;errorId:`${string}-${string}-${string}-${string}-${string}`;status:number;}:{event(property)event:NavigationEvent<Record<string,string>,string|null>,errorId(property)errorId:`${string}-${string}-${string}-${string}-${string}`,status(property)status:number}});return{message(property)App.Error.message:string:'Whoops!',errorId(property)errorId:`${string}-${string}-${string}-${string}-${string}`};};
In src/hooks.client.js, the type of handleError is HandleClientError instead of HandleServerError, and event is a NavigationEvent rather than a RequestEvent.
This function is not called for expected errors (those thrown with the error function imported from @sveltejs/kit).
During development, if an error occurs because of a syntax error in your Svelte code, the passed in error has a frame property appended highlighting the location of the error.
Make sure that handleErrornever throws an error
init
Can be added to src/hooks.server.js and src/hooks.client.js
This function runs once, when the server is created or the app starts in the browser, and is a useful place to do asynchronous work such as initializing a database connection.
If your environment supports top-level await, the init function is really no different from writing your initialisation logic at the top level of the module, but some environments — most notably, Safari — don’t.
In the browser, asynchronous work in init will delay hydration, so be mindful of what you put in there.
reroute
Can be added to src/hooks.js; it runs on both server and client
This function runs before handle and allows you to change how URLs are translated into routes. The returned pathname (which defaults to url.pathname) is used to select the route and its parameters.
For example, you might have a src/routes/[[lang]]/about/+page.svelte page, which should be accessible as /en/about or /de/ueber-uns or /fr/a-propos. You could implement this with reroute:
The pathname property of the URL interface represents a location in a hierarchical structure. It is a string constructed from a list of path segments, each of which is prefixed by a / character.
The pathname property of the URL interface represents a location in a hierarchical structure. It is a string constructed from a list of path segments, each of which is prefixed by a / character.
The pathname property of the URL interface represents a location in a hierarchical structure. It is a string constructed from a list of path segments, each of which is prefixed by a / character.
The pathname property of the URL interface represents a location in a hierarchical structure. It is a string constructed from a list of path segments, each of which is prefixed by a / character.
The lang parameter will be correctly derived from the returned pathname.
Using reroute will not change the contents of the browser’s address bar, or the value of event.url.
Since version 2.18, the reroute hook can be asynchronous, allowing it to (for example) fetch data from your backend to decide where to reroute to. Use this carefully and make sure it’s fast, as it will delay navigation otherwise. If you need to fetch data, use the fetch provided as an argument. It has the same benefits as the fetch provided to load functions, with the caveat that params and id are unavailable to handleFetch because the route is not yet known.
({url(parameter)url:URL,fetch(parameter)fetch:{(input:RequestInfo|URL,init?:RequestInit):Promise<Response>;(input:string|URL|Request,init?:RequestInit):Promise<Response>;}}){ // Ask a special endpoint within your app about the destinationif(url(parameter)url:URL.pathname(property)URL.pathname:string
The pathname property of the URL interface represents a location in a hierarchical structure. It is a string constructed from a list of path segments, each of which is prefixed by a / character.
The URL interface is used to parse, construct, normalize, and encode URLs. It works by providing properties which allow you to easily read and modify the components of a URL.
The searchParams read-only property of the URL interface returns a URLSearchParams object allowing access to the GET decoded query arguments contained in the URL.
The set() method of the URLSearchParams interface sets the value associated with a given search parameter to the given value. If there were several matching values, this method deletes the others. If the search parameter doesn't exist, this method creates it.
The pathname property of the URL interface represents a location in a hierarchical structure. It is a string constructed from a list of path segments, each of which is prefixed by a / character.
The reroute hook allows you to modify the URL before it is used to determine which route to render.
2.3.0
reference=async({url(parameter)url:URL,fetch(parameter)fetch:{(input:RequestInfo|URL,init?:RequestInit):Promise<Response>;(input:string|URL|Request,init?:RequestInit):Promise<Response>;}})=>{ // Ask a special endpoint within your app about the destinationif(url(parameter)url:URL.pathname(property)URL.pathname:string
The pathname property of the URL interface represents a location in a hierarchical structure. It is a string constructed from a list of path segments, each of which is prefixed by a / character.
The URL interface is used to parse, construct, normalize, and encode URLs. It works by providing properties which allow you to easily read and modify the components of a URL.
The searchParams read-only property of the URL interface returns a URLSearchParams object allowing access to the GET decoded query arguments contained in the URL.
The set() method of the URLSearchParams interface sets the value associated with a given search parameter to the given value. If there were several matching values, this method deletes the others. If the search parameter doesn't exist, this method creates it.
The pathname property of the URL interface represents a location in a hierarchical structure. It is a string constructed from a list of path segments, each of which is prefixed by a / character.
reroute is considered a pure, idempotent function. As such, it must always return the same output for the same input and not have side effects. Under these assumptions, SvelteKit caches the result of reroute on the client so it is only called once per unique URL.
transport
Can be added to src/hooks.js; it runs on both server and client
This is a collection of transporters, which allow you to pass custom types — returned from load and form actions — across the server/client boundary. Each transporter contains an encode function, which encodes values on the server (or returns a falsy value for anything that isn’t an instance of the type) and a corresponding decode function:
The transport hook allows you to transport custom types across the server/client boundary.
Each transporter has a pair of encode and decode functions. On the server, encode determines whether a value is an instance of the custom type and, if so, returns a non-falsy encoding of the value which can be an object or an array (or false otherwise).
In the browser, decode turns the encoding back into an instance of the custom type.
The transport hook allows you to transport custom types across the server/client boundary.
Each transporter has a pair of encode and decode functions. On the server, encode determines whether a value is an instance of the custom type and, if so, returns a non-falsy encoding of the value which can be an object or an array (or false otherwise).
In the browser, decode turns the encoding back into an instance of the custom type.