跳至主要內容

Hooks

「Hooks」是您宣告的全應用程式函數,SvelteKit 將在響應特定事件時呼叫這些函數,讓您可以精細地控制框架的行為。

有三個 Hooks 檔案,都是可選的

  • src/hooks.server.js — 您的應用程式的伺服器 Hooks
  • src/hooks.client.js — 您的應用程式的客戶端 Hooks
  • src/hooks.js — 您的應用程式在客戶端和伺服器上運行的 Hooks

這些模組中的程式碼將在應用程式啟動時運行,使其可用於初始化資料庫客戶端等等。

您可以使用 config.kit.files.hooks 配置這些檔案的位置。

伺服器 Hooks

以下 Hooks 可以添加到 src/hooks.server.js

handle

此函數在 SvelteKit 伺服器每次收到 請求 時執行 — 無論是在應用程式運行時還是 預先渲染 期間 — 並決定 回應。它接收一個代表請求的 event 物件和一個稱為 resolve 的函數,該函數會渲染路由並產生一個 Response。這允許您修改回應標頭或主體,或完全繞過 SvelteKit(例如,用於以程式方式實作路由)。

src/hooks.server
/** @type {import('@sveltejs/kit').Handle} */
export async function 
function handle({ event, resolve }: {
    event: any;
    resolve: any;
}): Promise<any>
@type{import('@sveltejs/kit').Handle}
handle
({ event: anyevent, resolve: anyresolve }) {
if (event: anyevent.url.pathname.startsWith('/custom')) { return new var Response: new (body?: BodyInit | null, init?: ResponseInit) => Response

This Fetch API interface represents the response to a request.

MDN Reference

Response
('custom response');
} const const response: anyresponse = await resolve: anyresolve(event: anyevent); return const response: anyresponse; }
import type { 
type Handle = (input: {
    event: RequestEvent;
    resolve(event: RequestEvent, opts?: ResolveOptions): MaybePromise<Response>;
}) => MaybePromise<...>

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

Handle
} from '@sveltejs/kit';
export const const handle: Handlehandle:
type Handle = (input: {
    event: RequestEvent;
    resolve(event: RequestEvent, opts?: ResolveOptions): MaybePromise<Response>;
}) => MaybePromise<...>

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

Handle
= async ({ event: RequestEvent<Partial<Record<string, string>>, string | null>event, resolve: (event: RequestEvent, opts?: ResolveOptions) => MaybePromise<Response>resolve }) => {
if (event: RequestEvent<Partial<Record<string, string>>, string | null>event.RequestEvent<Partial<Record<string, string>>, string | null>.url: URL

The requested URL.

url
.URL.pathname: stringpathname.String.startsWith(searchString: string, position?: number): boolean

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.

startsWith
('/custom')) {
return new var Response: new (body?: BodyInit | null, init?: ResponseInit) => Response

This Fetch API interface represents the response to a request.

MDN Reference

Response
('custom response');
} const const response: Responseresponse = await resolve: (event: RequestEvent, opts?: ResolveOptions) => MaybePromise<Response>resolve(event: RequestEvent<Partial<Record<string, string>>, string | null>event); return const response: Responseresponse; };

靜態資產(包括已經預先渲染的頁面)的請求 由 SvelteKit 處理。

如果未實作,則預設為 ({ event, resolve }) => resolve(event)

locals

要將自訂資料添加到請求中,該資料會傳遞給 +server.js 中的處理程式和伺服器 load 函數,請填寫 event.locals 物件,如下所示。

src/hooks.server
/** @type {import('@sveltejs/kit').Handle} */
export async function 
function handle(input: {
    event: RequestEvent;
    resolve(event: RequestEvent, opts?: ResolveOptions): MaybePromise<Response>;
}): MaybePromise<...>
@type{import('@sveltejs/kit').Handle}
handle
({ event: RequestEvent<Partial<Record<string, string>>, string | null>event, resolve: (event: RequestEvent, opts?: ResolveOptions) => MaybePromise<Response>resolve }) {
event: RequestEvent<Partial<Record<string, string>>, string | null>event.RequestEvent<Partial<Record<string, string>>, string | null>.locals: App.Locals

Contains custom data that was added to the request within the server handle hook.

locals
.App.Locals.user: Useruser = await const getUserInformation: (cookie: string | void) => Promise<User>getUserInformation(event: RequestEvent<Partial<Record<string, string>>, string | null>event.RequestEvent<Partial<Record<string, string>>, string | null>.cookies: Cookies

Get or set cookies related to the current request

cookies
.Cookies.get(name: string, opts?: CookieParseOptions): string | undefined

Gets a cookie that was previously set with cookies.set, or from the request headers.

@paramname the name of the cookie
@paramopts the options, passed directly to cookie.parse. See documentation here
get
('sessionid'));
const const response: Responseresponse = await resolve: (event: RequestEvent, opts?: ResolveOptions) => MaybePromise<Response>resolve(event: RequestEvent<Partial<Record<string, string>>, string | null>event); const response: Responseresponse.Response.headers: Headersheaders.Headers.set(name: string, value: string): voidset('x-custom-header', 'potato'); return const response: Responseresponse; }
import type { 
type Handle = (input: {
    event: RequestEvent;
    resolve(event: RequestEvent, opts?: ResolveOptions): MaybePromise<Response>;
}) => MaybePromise<...>

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

Handle
} from '@sveltejs/kit';
export const const handle: Handlehandle:
type Handle = (input: {
    event: RequestEvent;
    resolve(event: RequestEvent, opts?: ResolveOptions): MaybePromise<Response>;
}) => MaybePromise<...>

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

Handle
= async ({ event: RequestEvent<Partial<Record<string, string>>, string | null>event, resolve: (event: RequestEvent, opts?: ResolveOptions) => MaybePromise<Response>resolve }) => {
event: RequestEvent<Partial<Record<string, string>>, string | null>event.RequestEvent<Partial<Record<string, string>>, string | null>.locals: App.Locals

Contains custom data that was added to the request within the server handle hook.

locals
.App.Locals.user: Useruser = await const getUserInformation: (cookie: string | void) => Promise<User>getUserInformation(event: RequestEvent<Partial<Record<string, string>>, string | null>event.RequestEvent<Partial<Record<string, string>>, string | null>.cookies: Cookies

Get or set cookies related to the current request

cookies
.Cookies.get(name: string, opts?: CookieParseOptions): string | undefined

Gets a cookie that was previously set with cookies.set, or from the request headers.

@paramname the name of the cookie
@paramopts the options, passed directly to cookie.parse. See documentation here
get
('sessionid'));
const const response: Responseresponse = await resolve: (event: RequestEvent, opts?: ResolveOptions) => MaybePromise<Response>resolve(event: RequestEvent<Partial<Record<string, string>>, string | null>event); const response: Responseresponse.Response.headers: Headersheaders.Headers.set(name: string, value: string): voidset('x-custom-header', 'potato'); return const response: Responseresponse; };

您可以定義多個 handle 函數,並使用 sequence 輔助函數執行它們。

resolve 也支援第二個可選參數,讓您可以更精細地控制回應的渲染方式。該參數是一個物件,可以具有以下欄位

  • transformPageChunk(opts: { html: string, done: boolean }): MaybePromise<string | undefined> — 將自訂轉換套用於 HTML。如果 done 為 true,則它是最後一個區塊。不保證區塊是格式良好的 HTML(例如,它們可能包含元素的開始標籤,但不包含其結束標籤),但它們始終會以合理的邊界分割,例如 %sveltekit.head% 或版面配置/頁面元件。
  • filterSerializedResponseHeaders(name: string, value: string): boolean — 決定當 load 函數使用 fetch 載入資源時,應包含在序列化回應中的標頭。預設情況下,不會包含任何標頭。
  • preload(input: { type: 'js' | 'css' | 'font' | 'asset', path: string }): boolean — 決定應將哪些檔案添加到 <head> 標籤中以進行預載。該方法會以在建置時找到的每個檔案呼叫,同時建構程式碼區塊 — 因此,如果您例如在 +page.svelte 中有 import './styles.css,則在造訪該頁面時,將會使用該 CSS 檔案的解析路徑呼叫 preload。請注意,在開發模式下, 會呼叫 preload,因為它取決於在建置時發生的分析。預載可以透過更早下載資產來提高效能,但如果過多不必要的下載,也可能會造成損害。預設情況下,將會預載 jscss 檔案。目前完全不會預載 asset 檔案,但我們可能會在評估回饋後再添加此功能。
src/hooks.server
/** @type {import('@sveltejs/kit').Handle} */
export async function 
function handle({ event, resolve }: {
    event: any;
    resolve: any;
}): Promise<any>
@type{import('@sveltejs/kit').Handle}
handle
({ event: anyevent, resolve: anyresolve }) {
const const response: anyresponse = await resolve: anyresolve(event: anyevent, {
transformPageChunk: ({ html }: {
    html: any;
}) => any
transformPageChunk
: ({ html: anyhtml }) => html: anyhtml.replace('old', 'new'),
filterSerializedResponseHeaders: (name: any) => anyfilterSerializedResponseHeaders: (name: anyname) => name: anyname.startsWith('x-'),
preload: ({ type, path }: {
    type: any;
    path: any;
}) => any
preload
: ({ type: anytype, path: anypath }) => type: anytype === 'js' || path: anypath.includes('/important/')
}); return const response: anyresponse; }
import type { 
type Handle = (input: {
    event: RequestEvent;
    resolve(event: RequestEvent, opts?: ResolveOptions): MaybePromise<Response>;
}) => MaybePromise<...>

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

Handle
} from '@sveltejs/kit';
export const const handle: Handlehandle:
type Handle = (input: {
    event: RequestEvent;
    resolve(event: RequestEvent, opts?: ResolveOptions): MaybePromise<Response>;
}) => MaybePromise<...>

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

Handle
= async ({ event: RequestEvent<Partial<Record<string, string>>, string | null>event, resolve: (event: RequestEvent, opts?: ResolveOptions) => MaybePromise<Response>resolve }) => {
const const response: Responseresponse = await resolve: (event: RequestEvent, opts?: ResolveOptions) => MaybePromise<Response>resolve(event: RequestEvent<Partial<Record<string, string>>, string | null>event, {
ResolveOptions.transformPageChunk?(input: {
    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.

@paraminput the html chunk and the info if this is the last chunk
transformPageChunk
: ({ html: stringhtml }) => html: stringhtml.String.replace(searchValue: string | RegExp, replaceValue: string): string (+3 overloads)

Replaces text in a string, using a regular expression or search string.

@paramsearchValue A string or regular expression to search for.
@paramreplaceValue 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.
replace
('old', 'new'),
ResolveOptions.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.

@paramname header name
@paramvalue header value
filterSerializedResponseHeaders
: (name: stringname) => name: stringname.String.startsWith(searchString: string, position?: number): boolean

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.

startsWith
('x-'),
ResolveOptions.preload?(input: {
    type: "font" | "css" | "js" | "asset";
    path: string;
}): boolean

Determines what should be added to the &#x3C;head> tag to preload it. By default, js and css files will be preloaded.

@paraminput the type of the file and its path
preload
: ({ type: "font" | "css" | "js" | "asset"type, path: stringpath }) => type: "font" | "css" | "js" | "asset"type === 'js' || path: stringpath.String.includes(searchString: string, position?: number): boolean

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.

@paramsearchString search string
@paramposition If position is undefined, 0 is assumed, so as to search all of the String.
includes
('/important/')
}); return const response: Responseresponse; };

請注意,resolve(...) 永遠不會擲回錯誤,它將始終以適當的狀態碼傳回 Promise<Response>。如果 handle 期間在其他地方擲回錯誤,則會將其視為致命錯誤,SvelteKit 將會根據 Accept 標頭,以錯誤的 JSON 表示形式或備用錯誤頁面(可透過 src/error.html 自訂)進行回應。您可以在 這裡閱讀更多關於錯誤處理的資訊。

handleFetch

此函數允許您修改(或替換)在伺服器(或在預先渲染期間)運行的 loadaction 函數內部發生的 fetch 請求。

例如,當使用者執行客戶端導覽到對應頁面時,您的 load 函數可能會向公用 URL(例如 https://api.yourapp.com)發出請求,但在 SSR 期間,直接點擊 API 可能更有意義(繞過其與公共網際網路之間的所有 Proxy 和負載平衡器)。

src/hooks.server
/** @type {import('@sveltejs/kit').HandleFetch} */
export async function 
function handleFetch({ request, fetch }: {
    request: any;
    fetch: any;
}): Promise<any>
@type{import('@sveltejs/kit').HandleFetch}
handleFetch
({ request: anyrequest, fetch: anyfetch }) {
if (request: anyrequest.url.startsWith('https://api.yourapp.com/')) { // clone the original request, but change the URL request: anyrequest = new var Request: new (input: RequestInfo | URL, init?: RequestInit) => Request

This Fetch API interface represents a resource request.

MDN Reference

Request
(
request: anyrequest.url.replace('https://api.yourapp.com/', 'https://127.0.0.1:9999/'), request: anyrequest ); } return fetch: anyfetch(request: anyrequest); }
import type { 
type HandleFetch = (input: {
    event: RequestEvent;
    request: Request;
    fetch: typeof fetch;
}) => MaybePromise<Response>

The handleFetch hook allows you to modify (or replace) a fetch request that happens inside a load function that runs on the server (or during pre-rendering)

HandleFetch
} from '@sveltejs/kit';
export const const handleFetch: HandleFetchhandleFetch:
type HandleFetch = (input: {
    event: RequestEvent;
    request: Request;
    fetch: typeof fetch;
}) => MaybePromise<Response>

The handleFetch hook allows you to modify (or replace) a fetch request that happens inside a load function that runs on the server (or during pre-rendering)

HandleFetch
= async ({ request: Requestrequest,
fetch: {
    (input: RequestInfo | URL, init?: RequestInit): Promise<Response>;
    (input: string | URL | globalThis.Request, init?: RequestInit): Promise<Response>;
}
fetch
}) => {
if (request: Requestrequest.Request.url: string

Returns the URL of request as a string.

MDN Reference

url
.String.startsWith(searchString: string, position?: number): boolean

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.

startsWith
('https://api.yourapp.com/')) {
// clone the original request, but change the URL request: Requestrequest = new var Request: new (input: RequestInfo | URL, init?: RequestInit) => Request

This Fetch API interface represents a resource request.

MDN Reference

Request
(
request: Requestrequest.Request.url: string

Returns the URL of request as a string.

MDN Reference

url
.String.replace(searchValue: string | RegExp, replaceValue: string): string (+3 overloads)

Replaces text in a string, using a regular expression or search string.

@paramsearchValue A string or regular expression to search for.
@paramreplaceValue 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.
replace
('https://api.yourapp.com/', 'https://127.0.0.1:9999/'),
request: Requestrequest ); } return fetch: (input: string | URL | globalThis.Request, init?: RequestInit) => Promise<Response> (+1 overload)fetch(request: Requestrequest); };

憑證

對於同源請求,SvelteKit 的 fetch 實作將會轉發 cookieauthorization 標頭,除非 credentials 選項設定為 "omit"

對於跨域請求,如果請求 URL 屬於應用程式的子網域,則會包含 cookie — 例如,如果您的應用程式位於 my-domain.com 上,而您的 API 位於 api.my-domain.com 上,則請求中將包含 Cookie。

如果您的應用程式和 API 位於同級子網域上 — 例如 www.my-domain.comapi.my-domain.com — 則屬於通用父網域(例如 my-domain.com)的 Cookie 將 會被包含,因為 SvelteKit 無法知道 Cookie 所屬的網域。在這些情況下,您需要使用 handleFetch 手動包含 Cookie

src/hooks.server
/** @type {import('@sveltejs/kit').HandleFetch} */
export async function 
function handleFetch({ event, request, fetch }: {
    event: any;
    request: any;
    fetch: any;
}): Promise<any>
@type{import('@sveltejs/kit').HandleFetch}
handleFetch
({ event: anyevent, request: anyrequest, fetch: anyfetch }) {
if (request: anyrequest.url.startsWith('https://api.my-domain.com/')) { request: anyrequest.headers.set('cookie', event: anyevent.request.headers.get('cookie')); } return fetch: anyfetch(request: anyrequest); }
import type { 
type HandleFetch = (input: {
    event: RequestEvent;
    request: Request;
    fetch: typeof fetch;
}) => MaybePromise<Response>

The handleFetch hook allows you to modify (or replace) a fetch request that happens inside a load function that runs on the server (or during pre-rendering)

HandleFetch
} from '@sveltejs/kit';
export const const handleFetch: HandleFetchhandleFetch:
type HandleFetch = (input: {
    event: RequestEvent;
    request: Request;
    fetch: typeof fetch;
}) => MaybePromise<Response>

The handleFetch hook allows you to modify (or replace) a fetch request that happens inside a load function that runs on the server (or during pre-rendering)

HandleFetch
= async ({ event: RequestEvent<Partial<Record<string, string>>, string | null>event, request: Requestrequest,
fetch: {
    (input: RequestInfo | URL, init?: RequestInit): Promise<Response>;
    (input: string | URL | globalThis.Request, init?: RequestInit): Promise<Response>;
}
fetch
}) => {
if (request: Requestrequest.Request.url: string

Returns the URL of request as a string.

MDN Reference

url
.String.startsWith(searchString: string, position?: number): boolean

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.

startsWith
('https://api.my-domain.com/')) {
request: Requestrequest.Request.headers: Headers

Returns a Headers object consisting of the headers associated with request. Note that headers added in the network layer by the user agent will not be accounted for in this object, e.g., the “Host” header.

MDN Reference

headers
.Headers.set(name: string, value: string): voidset('cookie', event: RequestEvent<Partial<Record<string, string>>, string | null>event.RequestEvent<Partial<Record<string, string>>, string | null>.request: Request

The original request object

request
.Request.headers: Headers

Returns a Headers object consisting of the headers associated with request. Note that headers added in the network layer by the user agent will not be accounted for in this object, e.g., the “Host” header.

MDN Reference

headers
.Headers.get(name: string): string | nullget('cookie'));
} return fetch: (input: string | URL | globalThis.Request, init?: RequestInit) => Promise<Response> (+1 overload)fetch(request: Requestrequest); };

共用 Hooks

以下內容可以添加到 src/hooks.server.js src/hooks.client.js

handleError

如果在載入或渲染期間擲回非預期錯誤,則會使用 erroreventstatus 程式碼和 message 呼叫此函數。這允許執行兩件事

  • 您可以記錄錯誤
  • 您可以產生對使用者安全的錯誤自訂表示,省略敏感詳細資料,例如訊息和堆疊追蹤。傳回值(預設為 { message })會變成 $page.error 的值。

對於從您的程式碼(或您的程式碼呼叫的程式庫程式碼)擲回的錯誤,狀態碼將為 500,訊息將為「內部錯誤」。雖然 error.message 可能包含不應向使用者公開的敏感資訊,但 message 是安全的(儘管對一般使用者而言沒有意義)。

若要以類型安全的方式將更多資訊添加到 $page.error 物件中,您可以透過宣告 App.Error 介面(必須包含 message: string,以保證合理的備用行為)來自訂預期的形狀。這允許您例如附加一個追蹤 ID,供使用者在與您的技術支援人員通信時引用

src/app.d
declare global {
	namespace App {
		interface interface App.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.

Error
{
App.Error.message: stringmessage: string; App.Error.errorId: stringerrorId: string; } } } export {};
src/hooks.server
import * as module "@sentry/sveltekit"Sentry from '@sentry/sveltekit';

module "@sentry/sveltekit"Sentry.const init: (opts: any) => voidinit({/*...*/})

/** @type {import('@sveltejs/kit').HandleServerError} */
export async function 
function handleError(input: {
    error: unknown;
    event: RequestEvent;
    status: number;
    message: string;
}): MaybePromise<void | App.Error>
@type{import('@sveltejs/kit').HandleServerError}
handleError
({ error: unknownerror, event: RequestEvent<Partial<Record<string, string>>, string | null>event, status: numberstatus, message: stringmessage }) {
const const errorId: `${string}-${string}-${string}-${string}-${string}`errorId = var crypto: Cryptocrypto.Crypto.randomUUID(): `${string}-${string}-${string}-${string}-${string}`

Available only in secure contexts.

MDN Reference

randomUUID
();
// example integration with https://sentry.io/ module "@sentry/sveltekit"Sentry.const captureException: (error: any, opts: any) => voidcaptureException(error: unknownerror, {
extra: {
    event: RequestEvent<Partial<Record<string, string>>, string | null>;
    errorId: `${string}-${string}-${string}-${string}-${string}`;
    status: number;
}
extra
: { event: RequestEvent<Partial<Record<string, string>>, string | null>event, errorId: `${string}-${string}-${string}-${string}-${string}`errorId, status: numberstatus }
}); return { App.Error.message: stringmessage: 'Whoops!', errorId: `${string}-${string}-${string}-${string}-${string}`errorId }; }
import * as module "@sentry/sveltekit"Sentry from '@sentry/sveltekit';
import type { 
type HandleServerError = (input: {
    error: unknown;
    event: RequestEvent;
    status: number;
    message: string;
}) => MaybePromise<void | App.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.

HandleServerError
} from '@sveltejs/kit';
module "@sentry/sveltekit"Sentry.const init: (opts: any) => voidinit({/*...*/}) export const const handleError: HandleServerErrorhandleError:
type HandleServerError = (input: {
    error: unknown;
    event: RequestEvent;
    status: number;
    message: string;
}) => MaybePromise<void | App.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.

HandleServerError
= async ({ error: unknownerror, event: RequestEvent<Partial<Record<string, string>>, string | null>event, status: numberstatus, message: stringmessage }) => {
const const errorId: `${string}-${string}-${string}-${string}-${string}`errorId = var crypto: Cryptocrypto.Crypto.randomUUID(): `${string}-${string}-${string}-${string}-${string}`

Available only in secure contexts.

MDN Reference

randomUUID
();
// example integration with https://sentry.io/ module "@sentry/sveltekit"Sentry.const captureException: (error: any, opts: any) => voidcaptureException(error: unknownerror, {
extra: {
    event: RequestEvent<Partial<Record<string, string>>, string | null>;
    errorId: `${string}-${string}-${string}-${string}-${string}`;
    status: number;
}
extra
: { event: RequestEvent<Partial<Record<string, string>>, string | null>event, errorId: `${string}-${string}-${string}-${string}-${string}`errorId, status: numberstatus }
}); return { App.Error.message: stringmessage: 'Whoops!', errorId: `${string}-${string}-${string}-${string}-${string}`errorId }; };
src/hooks.client
import * as module "@sentry/sveltekit"Sentry from '@sentry/sveltekit';

module "@sentry/sveltekit"Sentry.const init: (opts: any) => voidinit({/*...*/})

/** @type {import('@sveltejs/kit').HandleClientError} */
export async function 
function handleError(input: {
    error: unknown;
    event: NavigationEvent;
    status: number;
    message: string;
}): MaybePromise<void | App.Error>
@type{import('@sveltejs/kit').HandleClientError}
handleError
({ error: unknownerror, event: NavigationEvent<Partial<Record<string, string>>, string | null>event, status: numberstatus, message: stringmessage }) {
const const errorId: `${string}-${string}-${string}-${string}-${string}`errorId = var crypto: Cryptocrypto.Crypto.randomUUID(): `${string}-${string}-${string}-${string}-${string}`

Available only in secure contexts.

MDN Reference

randomUUID
();
// example integration with https://sentry.io/ module "@sentry/sveltekit"Sentry.const captureException: (error: any, opts: any) => voidcaptureException(error: unknownerror, {
extra: {
    event: NavigationEvent<Partial<Record<string, string>>, string | null>;
    errorId: `${string}-${string}-${string}-${string}-${string}`;
    status: number;
}
extra
: { event: NavigationEvent<Partial<Record<string, string>>, string | null>event, errorId: `${string}-${string}-${string}-${string}-${string}`errorId, status: numberstatus }
}); return { App.Error.message: stringmessage: 'Whoops!', errorId: `${string}-${string}-${string}-${string}-${string}`errorId }; }
import * as module "@sentry/sveltekit"Sentry from '@sentry/sveltekit';
import type { 
type HandleClientError = (input: {
    error: unknown;
    event: NavigationEvent;
    status: number;
    message: string;
}) => MaybePromise<void | App.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.

HandleClientError
} from '@sveltejs/kit';
module "@sentry/sveltekit"Sentry.const init: (opts: any) => voidinit({/*...*/}) export const const handleError: HandleClientErrorhandleError:
type HandleClientError = (input: {
    error: unknown;
    event: NavigationEvent;
    status: number;
    message: string;
}) => MaybePromise<void | App.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.

HandleClientError
= async ({ error: unknownerror, event: NavigationEvent<Partial<Record<string, string>>, string | null>event, status: numberstatus, message: stringmessage }) => {
const const errorId: `${string}-${string}-${string}-${string}-${string}`errorId = var crypto: Cryptocrypto.Crypto.randomUUID(): `${string}-${string}-${string}-${string}-${string}`

Available only in secure contexts.

MDN Reference

randomUUID
();
// example integration with https://sentry.io/ module "@sentry/sveltekit"Sentry.const captureException: (error: any, opts: any) => voidcaptureException(error: unknownerror, {
extra: {
    event: NavigationEvent<Partial<Record<string, string>>, string | null>;
    errorId: `${string}-${string}-${string}-${string}-${string}`;
    status: number;
}
extra
: { event: NavigationEvent<Partial<Record<string, string>>, string | null>event, errorId: `${string}-${string}-${string}-${string}-${string}`errorId, status: numberstatus }
}); return { App.Error.message: stringmessage: 'Whoops!', errorId: `${string}-${string}-${string}-${string}-${string}`errorId }; };

src/hooks.client.js 中,handleError 的類型為 HandleClientError,而不是 HandleServerError,且 eventNavigationEvent 而不是 RequestEvent

對於 預期 的錯誤(使用從 @sveltejs/kit 匯入的 error 函數擲回的錯誤),不會呼叫此函數。

在開發期間,如果因 Svelte 程式碼中的語法錯誤而發生錯誤,則傳入的錯誤會附加一個 frame 屬性,以突出顯示錯誤的位置。

請確保 handleError 永遠 不會擲回錯誤

通用 Hooks

以下內容可以添加到 src/hooks.js。通用 Hooks 在伺服器和客戶端上運行(不要與特定於環境的共用 Hooks 混淆)。

reroute

此函數在 handle 之前運行,讓您可以變更 URL 轉換為路由的方式。傳回的路徑名稱(預設為 url.pathname)用於選取路由及其參數。

例如,您可能有一個 src/routes/[[lang]]/about/+page.svelte 頁面,該頁面應可作為 /en/about/de/ueber-uns/fr/a-propos 存取。您可以使用 reroute 來實作此功能

src/hooks

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

The reroute hook allows you to modify the URL before it is used to determine which route to render.

@since2.3.0
Reroute
} from '@sveltejs/kit';
const const translated: Record<string, string>translated: type Record<K extends keyof any, T> = { [P in K]: T; }

Construct a type with a set of properties K of type T

Record
<string, string> = {
'/en/about': '/en/about', '/de/ueber-uns': '/de/about', '/fr/a-propos': '/fr/about', }; export const const reroute: Reroutereroute:
type Reroute = (event: {
    url: URL;
}) => void | string

The reroute hook allows you to modify the URL before it is used to determine which route to render.

@since2.3.0
Reroute
= ({ url: URLurl }) => {
if (url: URLurl.URL.pathname: stringpathname in const translated: Record<string, string>translated) { return const translated: Record<string, string>translated[url: URLurl.URL.pathname: stringpathname]; } };

lang 參數將會正確地從傳回的路徑名稱中衍生。

使用 reroute不會 變更瀏覽器網址列的內容或 event.url 的值。

延伸閱讀

在 GitHub 上編輯此頁面

上一個 下一個