diff --git a/apps/svelte.dev/content/docs/kit/30-advanced/20-hooks.md b/apps/svelte.dev/content/docs/kit/30-advanced/20-hooks.md index 6decc1cbf4..9663d724fc 100644 --- a/apps/svelte.dev/content/docs/kit/30-advanced/20-hooks.md +++ b/apps/svelte.dev/content/docs/kit/30-advanced/20-hooks.md @@ -237,6 +237,25 @@ During development, if an error occurs because of a syntax error in your Svelte > [!NOTE] Make sure that `handleError` _never_ throws an error +### init + +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. + +```js +/// 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. + ## Universal hooks 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). diff --git a/apps/svelte.dev/content/docs/kit/98-reference/10-@sveltejs-kit.md b/apps/svelte.dev/content/docs/kit/98-reference/10-@sveltejs-kit.md index afbf2ca54e..556736df0c 100644 --- a/apps/svelte.dev/content/docs/kit/98-reference/10-@sveltejs-kit.md +++ b/apps/svelte.dev/content/docs/kit/98-reference/10-@sveltejs-kit.md @@ -851,6 +851,24 @@ Compress files in `directory` with gzip and brotli, where appropriate. Generates +## ClientInit + +
+ +Available since 2.10.0 + ++ +The [`init`](/docs/kit/hooks#Shared-hooks-init) will be invoked once the app starts in the browser + +
+ +Available since 2.10.0 + ++ +The [`init`](/docs/kit/hooks#Shared-hooks-init) will be invoked before the server responds to its first request + +