Skip to main content

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 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).

src/hooks.server
/** @type {import('@sveltejs/kit/hooks').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;
}
import type { Handle } from '@sveltejs/kit/hooks';

export const handle: Handle = async ({ event, resolve }) => {
	if (event.url.pathname.startsWith('/custom')) {
		return new Response('custom response');
	}

	const response = await resolve(event);
	return response;
};

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' | 'asset', path: string } | { type: 'font', path: string, filename: 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. For font files, input also has a filename property, the source file’s pathname relative to the project root, so that a filter can match on it instead of the hashed path.
src/hooks.server
/** @type {import('@sveltejs/kit/hooks').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;
}
import type { Handle } from '@sveltejs/kit/hooks';

export const handle: Handle = async ({ 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.

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.

src/hooks.server
/** @type {import('@sveltejs/kit/hooks').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;
}
import type { Handle } from '@sveltejs/kit/hooks';

export const handle: Handle = async ({ 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;
};

handleFetch

Can be added to src/hooks.server.js

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).

src/hooks.server
/** @type {import('@sveltejs/kit/hooks').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);
}
import type { HandleFetch } from '@sveltejs/kit/hooks';

export const handleFetch: HandleFetch = async ({ 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);
};

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:

src/hooks.server
/** @type {import('@sveltejs/kit/hooks').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);
}
import type { HandleFetch } from '@sveltejs/kit/hooks';
export const handleFetch: HandleFetch = async ({ event, request, fetch }) => {
	if (request.url.startsWith('https://api.my-domain.com/')) {
		request.headers.set('cookie', event.request.headers.get('cookie'));
	}

	return fetch(request);
};

handleError

Can be added to src/hooks.server.js and src/hooks.client.js

This function is called for every error thrown while loading, rendering, or responding to a request. 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

Alongside the event, the hook receives a kind discriminant that tells you where the error came from, and the error itself:

  • 'app' — the error came from your app via error(...)
    • error is the error body, which matches App.Error
    • defaults to the error body itself
  • 'framework' — the error came from SvelteKit, such as a 404, 405 or 413
    • error is { status, message }, where message is safe text like Not Found
    • defaults to that same { status, message }
  • 'validation' (server only) — the error came from validating a remote function argument against its Standard Schema
    • error is { status: 400, message: 'Bad Request' }, and issues contains the validation issues
    • defaults to the error object; the issues are not exposed unless you explicitly return them
    • to access validation-library-specific issue properties, parameterise HandleServerError with the issue type, for example HandleServerError<CustomIssue>
  • 'unknown' — we don’t know what went wrong; the error was thrown by your code, or code it calls
    • error is the thrown value, which may contain information unsafe to expose
    • defaults to { status: 500, message: 'Internal Error' }

The next section, Errors, explains the other categories in more detail. Redirects are not errors, and never reach the hook.

The hook returns an object matching App.Error, in which status and message are optional — return them only to override the defaults in the list above.

If you augment App.Error with additional required properties, the hook must return them.

To add more information to the page.error object in a type-safe way, augment the existing App.Error interface with your additional properties. The built-in status and message properties are already present and do not need to be redeclared. For example, you can add a tracking ID for users to quote when contacting support:

src/app.d
declare global {
	namespace App {
		interface Error {
			errorId: string;
		}
	}
}

export {};
src/hooks.server
import * as Sentry from '@sentry/sveltekit';

Sentry.init({/*...*/})
/** @type {import('@sveltejs/kit/hooks').HandleServerError} */export async function handleError({ kind, error, event }) {
	if (kind === 'app') {
		// you created this error with `error(...)`, so it already		// matches `App.Error` — pass it through unchanged		return error;
	}

	const errorId = crypto.randomUUID();

	if (kind === 'framework') {
		// a 404 (or similar) — `error.status` and `error.message` are safe to		// expose, so we keep them and just add our own property		return { ...error, errorId };
	}
	// example integration with https://sentry.io/	Sentry.captureException(error, {
		extra: { event, errorId }
	});
	// `status` and `message` are optional — we only override `message`,	// so the status stays at its default of 500	return {
		message: 'Whoops!',
		errorId
	};
}
import * as Sentry from '@sentry/sveltekit';
import type { HandleServerError } from '@sveltejs/kit/hooks';

Sentry.init({/*...*/})

export const handleError: HandleServerError = async ({ kind, error, event }) => {
	if (kind === 'app') {
		// you created this error with `error(...)`, so it already		// matches `App.Error` — pass it through unchanged		return error;
	}

	const errorId = crypto.randomUUID();

	if (kind === 'framework') {
		// a 404 (or similar) — `error.status` and `error.message` are safe to		// expose, so we keep them and just add our own property		return { ...error, errorId };
	}
	// example integration with https://sentry.io/	Sentry.captureException(error, {
		extra: { event, errorId }
	});
	// `status` and `message` are optional — we only override `message`,	// so the status stays at its default of 500	return {
		message: 'Whoops!',
		errorId
	};
};
src/hooks.client
import * as Sentry from '@sentry/sveltekit';

Sentry.init({/*...*/})
/** @type {import('@sveltejs/kit/hooks').HandleClientError} */export async function handleError({ kind, error, event }) {
	if (kind === 'app') {
		return error;
	}

	const errorId = crypto.randomUUID();

	if (kind === 'framework') {
		return { ...error, errorId };
	}
	// example integration with https://sentry.io/	Sentry.captureException(error, {
		extra: { event, errorId }
	});

	return {
		message: 'Whoops!',
		errorId
	};
}
import * as Sentry from '@sentry/sveltekit';
import type { HandleClientError } from '@sveltejs/kit/hooks';

Sentry.init({/*...*/})

export const handleError: HandleClientError = async ({ kind, error, event }) => {
	if (kind === 'app') {
		return error;
	}

	const errorId = crypto.randomUUID();

	if (kind === 'framework') {
		return { ...error, errorId };
	}
	// example integration with https://sentry.io/	Sentry.captureException(error, {
		extra: { event, errorId }
	});

	return {
		message: 'Whoops!',
		errorId
	};
};

In src/hooks.client.js, the type of handleError is HandleClientError instead of HandleServerError, and event is a NavigationEvent rather than a RequestEvent.

Errors that were already transformed by the server-side hook are not passed to the client-side hook a second time.

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 handleError never 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.

src/hooks.server
import * as db from '#lib/server/database.js';
/** @type {import('@sveltejs/kit/hooks').ServerInit} */export async function init() {
	await db.connect();
}
import * as db from '#lib/server/database.js';
import type { ServerInit } from '@sveltejs/kit/hooks';

export const init: ServerInit = async () => {
	await db.connect();
};

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:

src/hooks

/** @type {Record<string, string>} */
const translated = {
	'/en/about': '/en/about',
	'/de/ueber-uns': '/de/about',
	'/fr/a-propos': '/fr/about',
};
/** @type {import('@sveltejs/kit/hooks').Reroute} */export function reroute({ url }) {
	if (url.pathname in translated) {
		return translated[url.pathname];
	}
}
import type { Reroute } from '@sveltejs/kit/hooks';
const translated: Record<string, string> = {
	'/en/about': '/en/about',
	'/de/ueber-uns': '/de/about',
	'/fr/a-propos': '/fr/about',
};

export const reroute: 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.

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.

src/hooks

/** @type {import('@sveltejs/kit/hooks').Reroute} */
export async function reroute({ url, fetch }) {
	// Ask a special endpoint within your app about the destination	if (url.pathname === '/api/reroute') return;

	const api = new URL('/api/reroute', url);
	api.searchParams.set('pathname', url.pathname);

	const result = await fetch(api).then(r => r.json());
	return result.pathname;
}
import type { Reroute } from '@sveltejs/kit/hooks';
export const reroute: Reroute = async ({ url, fetch }) => {
	// Ask a special endpoint within your app about the destination	if (url.pathname === '/api/reroute') return;

	const api = new URL('/api/reroute', url);
	api.searchParams.set('pathname', url.pathname);

	const result = await fetch(api).then(r => r.json());
	return result.pathname;
};

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:

src/hooks
import { Vector } from '#lib/math.js';
/** @type {import('@sveltejs/kit/hooks').Transport} */export const transport = {
	Vector: {
		encode: (value) => value instanceof Vector && [value.x, value.y],
		decode: ([x, y]) => new Vector(x, y)
	}
};
import { Vector } from '#lib/math.js';
import type { Transport } from '@sveltejs/kit/hooks';

export const transport: Transport = {
	Vector: {
		encode: (value) => value instanceof Vector && [value.x, value.y],
		decode: ([x, y]) => new Vector(x, y)
	}
};

Further reading

Edit this page on GitHub llms.txt

previous next