title |
---|
Hooks |
'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 hookssrc/hooks.client.js
— your app's client hookssrc/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.
[!NOTE] You can configure the location of these files with
config.kit.files.hooks
.
The following hooks 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).
/// file: src/hooks.server.js
/** @type {import('@sveltejs/kit').Handle} */
export async function handle({ event, resolve }) {
if (event.url.pathname.startsWith('/custom')) {
return new Response('custom response');
}
const response = await resolve(event);
return response;
}
[!NOTE] Requests for static assets — which includes pages that were already prerendered — are not handled by SvelteKit.
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.
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.
/// file: src/hooks.server.js
// @filename: ambient.d.ts
type User = {
name: string;
}
declare namespace App {
interface Locals {
user: User;
}
}
const getUserInformation: (cookie: string | void) => Promise<User>;
// @filename: index.js
// ---cut---
/** @type {import('@sveltejs/kit').Handle} */
export async function handle({ event, resolve }) {
event.locals.user = await getUserInformation(event.cookies.get('sessionid'));
const response = await resolve(event);
// 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.
response.headers.set('x-custom-header', 'potato');
return response;
}
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. Ifdone
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 aload
function loads a resource withfetch
. By default, none will be included.preload(input: { type: 'js' | 'css' | 'font' | 'asset', path: string }): boolean
— determines what files should be added to the<head>
tag to preload it. The method is called with each file that was found at build time while constructing the code chunks — so if you for example haveimport './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 modepreload
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
andcss
files will be preloaded.asset
files are not preloaded at all currently, but we may add this later after evaluating feedback.
/// file: src/hooks.server.js
/** @type {import('@sveltejs/kit').Handle} */
export async function handle({ event, resolve }) {
const response = await resolve(event, {
transformPageChunk: ({ html }) => html.replace('old', 'new'),
filterSerializedResponseHeaders: (name) => name.startsWith('x-'),
preload: ({ type, path }) => type === 'js' || path.includes('/important/')
});
return response;
}
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.
This function allows you to modify (or replace) a fetch
request that happens inside a load
or action
function that runs on the server (or during pre-rendering).
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).
/// file: src/hooks.server.js
/** @type {import('@sveltejs/kit').HandleFetch} */
export async function handleFetch({ request, fetch }) {
if (request.url.startsWith('https://api.yourapp.com/')) {
// clone the original request, but change the URL
request = new Request(
request.url.replace('https://api.yourapp.com/', 'http://localhost:9999/'),
request
);
}
return fetch(request);
}
Credentials
For same-origin requests, SvelteKit's fetch
implementation will forward cookie
and authorization
headers 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.
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
:
/// file: src/hooks.server.js
// @errors: 2345
/** @type {import('@sveltejs/kit').HandleFetch} */
export async function handleFetch({ event, request, fetch }) {
if (request.url.startsWith('https://api.my-domain.com/')) {
request.headers.set('cookie', event.request.headers.get('cookie'));
}
return fetch(request);
}
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. In order to use this hook, you need to opt in to server-side route resolution, which means a server request is made before each navigation in order to invoke the server reroute
hook.
In contrast to the universal reroute
hook, it
- is allowed to be async (though you should take extra caution to not do long running operations here, as it will delay navigation)
- also receives headers and cookies (though you cannot modify them)
For example, you might have two variants of a page via src/routes/sale/variant-a/+page.svelte
and src/routes/sale/variant-b/+page.svelte
, which should be accessible as /sale
and want to use a cookie to determine what variant of the sales page to load. You could implement this with reroute
:
/// file: src/hooks.js
// @errors: 2345
// @errors: 2304
/** @type {import('@sveltejs/kit').Reroute} */
export function reroute({ url, cookies }) {
if (url.pathname === '/sale') {
const variant = cookies.get('sales-variant') ?? 'variant-a';
return `/sale/${variant}`;
}
}
Using reroute
will not change the contents of the browser's address bar, or the value of event.url
.
The following can be added to src/hooks.server.js
and src/hooks.client.js
:
If an unexpected error is thrown during loading or rendering, 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:
/// file: src/app.d.ts
declare global {
namespace App {
interface Error {
message: string;
errorId: string;
}
}
}
export {};
/// file: src/hooks.server.js
// @errors: 2322 2353
// @filename: ambient.d.ts
declare module '@sentry/sveltekit' {
export const init: (opts: any) => void;
export const captureException: (error: any, opts: any) => void;
}
// @filename: index.js
// ---cut---
import * as Sentry from '@sentry/sveltekit';
Sentry.init({/*...*/})
/** @type {import('@sveltejs/kit').HandleServerError} */
export async function handleError({ error, event, status, message }) {
const errorId = crypto.randomUUID();
// example integration with https://sentry.io/
Sentry.captureException(error, {
extra: { event, errorId, status }
});
return {
message: 'Whoops!',
errorId
};
}
/// file: src/hooks.client.js
// @errors: 2322 2353
// @filename: ambient.d.ts
declare module '@sentry/sveltekit' {
export const init: (opts: any) => void;
export const captureException: (error: any, opts: any) => void;
}
// @filename: index.js
// ---cut---
import * as Sentry from '@sentry/sveltekit';
Sentry.init({/*...*/})
/** @type {import('@sveltejs/kit').HandleClientError} */
export async function handleError({ error, event, status, message }) {
const errorId = crypto.randomUUID();
// example integration with https://sentry.io/
Sentry.captureException(error, {
extra: { event, errorId, status }
});
return {
message: 'Whoops!',
errorId
};
}
[!NOTE] In
src/hooks.client.js
, the type ofhandleError
isHandleClientError
instead ofHandleServerError
, andevent
is aNavigationEvent
rather than aRequestEvent
.
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.
[!NOTE] Make sure that
handleError
never throws an error
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.
[!NOTE] 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.
/// file: src/hooks.server.js
import * as db from '$lib/server/database';
/** @type {import('@sveltejs/kit').ServerInit} */
export async function init() {
await db.connect();
}
Note
In the browser, asynchronous work in init
will delay hydration, so be mindful of what you put in there.
The following can be added to src/hooks.js
. Universal hooks run on both server and client (not to be confused with shared hooks, which are environment-specific).
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.
In contrast to the server reroute
hook, it
- must be synchronous
- only receives the URL
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
:
/// file: src/hooks.js
// @errors: 2345
// @errors: 2304
/** @type {Record<string, string>} */
const translated = {
'/en/about': '/en/about',
'/de/ueber-uns': '/de/about',
'/fr/a-propos': '/fr/about',
};
/** @type {import('@sveltejs/kit').Reroute} */
export function reroute({ url }) {
if (url.pathname in translated) {
return translated[url.pathname];
}
}
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
.
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 false
for anything that isn't an instance of the type) and a corresponding decode
function:
/// file: src/hooks.js
import { Vector } from '$lib/math';
/** @type {import('@sveltejs/kit').Transport} */
export const transport = {
Vector: {
encode: (value) => value instanceof Vector && [value.x, value.y],
decode: ([x, y]) => new Vector(x, y)
}
};