A helper function for sequencing multiple handle calls in a middleware-like manner.
The behavior for the handle options is as follows:
transformPageChunk is applied in reverse order and merged
preload is applied in forward order, the first option "wins" and no preload options after it are called
filterSerializedResponseHeaders behaves the same as preload
src/hooks.server
import{sequence}from'@sveltejs/kit/hooks';/// type: import('@sveltejs/kit/hooks').Handleasyncfunctionfirst({event,resolve}){console.log('first pre-processing');constresult=awaitresolve(event,{transformPageChunk:({html})=>{// transforms are applied in reverse orderconsole.log('first transform');returnhtml;},preload:()=>{// this one wins as it's the first defined in the chainconsole.log('first preload');returntrue;}});console.log('first post-processing');returnresult;}/// type: import('@sveltejs/kit/hooks').Handleasyncfunctionsecond({event,resolve}){console.log('second pre-processing');constresult=awaitresolve(event,{transformPageChunk:({html})=>{console.log('second transform');returnhtml;},preload:()=>{console.log('second preload');returntrue;},filterSerializedResponseHeaders:()=>{// this one wins as it's the first defined in the chainconsole.log('second filterSerializedResponseHeaders');returntrue;}});console.log('second post-processing');returnresult;}exportconsthandle=sequence(first,second);
The example above would print:
first pre-processing
first preload
second pre-processing
second filterSerializedResponseHeaders
second transform
first transform
second post-processing
first post-processing
Calling resolve invokes the next handler in the sequence (or SvelteKit itself, if it is the last one). To pass data between handlers, use event.locals.
handlers
The chain of handle functions
}from'@sveltejs/kit/hooks';
sequence
Une fonction utilitaire pour séquencer plusieurs appels handle à la manière d’un middleware.
Le comportement des options de handle est le suivant :
transformPageChunk est appliquée en ordre inversé et fusionné
preload est appliquée en ordre normal, la première option “gagne” et aucune option preload
n’est appelée après elle
filterSerializedResponseHeaders se comporte comme preload
A helper function for sequencing multiple handle calls in a middleware-like manner.
The behavior for the handle options is as follows:
transformPageChunk is applied in reverse order and merged
preload is applied in forward order, the first option "wins" and no preload options after it are called
filterSerializedResponseHeaders behaves the same as preload
src/hooks.server
import{sequence}from'@sveltejs/kit/hooks';/// type: import('@sveltejs/kit/hooks').Handleasyncfunctionfirst({event,resolve}){console.log('first pre-processing');constresult=awaitresolve(event,{transformPageChunk:({html})=>{// transforms are applied in reverse orderconsole.log('first transform');returnhtml;},preload:()=>{// this one wins as it's the first defined in the chainconsole.log('first preload');returntrue;}});console.log('first post-processing');returnresult;}/// type: import('@sveltejs/kit/hooks').Handleasyncfunctionsecond({event,resolve}){console.log('second pre-processing');constresult=awaitresolve(event,{transformPageChunk:({html})=>{console.log('second transform');returnhtml;},preload:()=>{console.log('second preload');returntrue;},filterSerializedResponseHeaders:()=>{// this one wins as it's the first defined in the chainconsole.log('second filterSerializedResponseHeaders');returntrue;}});console.log('second post-processing');returnresult;}exportconsthandle=sequence(first,second);
The example above would print:
first pre-processing
first preload
second pre-processing
second filterSerializedResponseHeaders
second transform
first transform
second post-processing
first post-processing
Calling resolve invokes the next handler in the sequence (or SvelteKit itself, if it is the last one). To pass data between handlers, use event.locals.
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
:({html(parameter)html:string})=>{ // les transformations sont appliquées en ordre inverse
consolevarconsole:Console.log(method)Console.log(...data:any[]):void
The console.log() static method outputs a message to the console.
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.
By default, js and css files will be preloaded.
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. js and
css files are bundled and have no single source file name.
input
the type of the file and its path
:()=>{ // c'est ce `preload` qui gagne car c'est le premier défini dans la chaîne
consolevarconsole:Console.log(method)Console.log(...data:any[]):void
The console.log() static method outputs a message to the console.
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
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.
By default, js and css files will be preloaded.
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. js and
css files are bundled and have no single source file name.
Determines which headers should be included in serialized responses when a load function loads a resource with fetch.
By default, none will be included.
name
header name
value
header value
:()=>{ // ce `filterSerializedResponseHeaders` gagne car c'est le premier défini dans la chaîne
consolevarconsole:Console.log(method)Console.log(...data:any[]):void
The console.log() static method outputs a message to the console.
A helper function for sequencing multiple handle calls in a middleware-like manner.
The behavior for the handle options is as follows:
transformPageChunk is applied in reverse order and merged
preload is applied in forward order, the first option "wins" and no preload options after it are called
filterSerializedResponseHeaders behaves the same as preload
src/hooks.server
import{sequence}from'@sveltejs/kit/hooks';/// type: import('@sveltejs/kit/hooks').Handleasyncfunctionfirst({event,resolve}){console.log('first pre-processing');constresult=awaitresolve(event,{transformPageChunk:({html})=>{// transforms are applied in reverse orderconsole.log('first transform');returnhtml;},preload:()=>{// this one wins as it's the first defined in the chainconsole.log('first preload');returntrue;}});console.log('first post-processing');returnresult;}/// type: import('@sveltejs/kit/hooks').Handleasyncfunctionsecond({event,resolve}){console.log('second pre-processing');constresult=awaitresolve(event,{transformPageChunk:({html})=>{console.log('second transform');returnhtml;},preload:()=>{console.log('second preload');returntrue;},filterSerializedResponseHeaders:()=>{// this one wins as it's the first defined in the chainconsole.log('second filterSerializedResponseHeaders');returntrue;}});console.log('second post-processing');returnresult;}exportconsthandle=sequence(first,second);
The example above would print:
first pre-processing
first preload
second pre-processing
second filterSerializedResponseHeaders
second transform
first transform
second post-processing
first post-processing
Calling resolve invokes the next handler in the sequence (or SvelteKit itself, if it is the last one). To pass data between handlers, use event.locals.
A helper function for sequencing multiple handle calls in a middleware-like manner.
The behavior for the handle options is as follows:
transformPageChunk is applied in reverse order and merged
preload is applied in forward order, the first option "wins" and no preload options after it are called
filterSerializedResponseHeaders behaves the same as preload
src/hooks.server
import{sequence}from'@sveltejs/kit/hooks';/// type: import('@sveltejs/kit/hooks').Handleasyncfunctionfirst({event,resolve}){console.log('first pre-processing');constresult=awaitresolve(event,{transformPageChunk:({html})=>{// transforms are applied in reverse orderconsole.log('first transform');returnhtml;},preload:()=>{// this one wins as it's the first defined in the chainconsole.log('first preload');returntrue;}});console.log('first post-processing');returnresult;}/// type: import('@sveltejs/kit/hooks').Handleasyncfunctionsecond({event,resolve}){console.log('second pre-processing');constresult=awaitresolve(event,{transformPageChunk:({html})=>{console.log('second transform');returnhtml;},preload:()=>{console.log('second preload');returntrue;},filterSerializedResponseHeaders:()=>{// this one wins as it's the first defined in the chainconsole.log('second filterSerializedResponseHeaders');returntrue;}});console.log('second post-processing');returnresult;}exportconsthandle=sequence(first,second);
The example above would print:
first pre-processing
first preload
second pre-processing
second filterSerializedResponseHeaders
second transform
first transform
second post-processing
first post-processing
Calling resolve invokes the next handler in the sequence (or SvelteKit itself, if it is the last one). To pass data between handlers, use event.locals.
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
:({html(parameter)html:string})=>{ // les transformations sont appliquées en ordre inverse
consolevarconsole:Console.log(method)Console.log(...data:any[]):void
The console.log() static method outputs a message to the console.
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.
By default, js and css files will be preloaded.
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. js and
css files are bundled and have no single source file name.
input
the type of the file and its path
:()=>{ // c'est ce `preload` qui gagne car c'est le premier défini dans la chaîne
consolevarconsole:Console.log(method)Console.log(...data:any[]):void
The console.log() static method outputs a message to the console.
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
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.
By default, js and css files will be preloaded.
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. js and
css files are bundled and have no single source file name.
Determines which headers should be included in serialized responses when a load function loads a resource with fetch.
By default, none will be included.
name
header name
value
header value
:()=>{ // ce `filterSerializedResponseHeaders` gagne car c'est le premier défini dans la chaîne
consolevarconsole:Console.log(method)Console.log(...data:any[]):void
The console.log() static method outputs a message to the console.
A helper function for sequencing multiple handle calls in a middleware-like manner.
The behavior for the handle options is as follows:
transformPageChunk is applied in reverse order and merged
preload is applied in forward order, the first option "wins" and no preload options after it are called
filterSerializedResponseHeaders behaves the same as preload
src/hooks.server
import{sequence}from'@sveltejs/kit/hooks';/// type: import('@sveltejs/kit/hooks').Handleasyncfunctionfirst({event,resolve}){console.log('first pre-processing');constresult=awaitresolve(event,{transformPageChunk:({html})=>{// transforms are applied in reverse orderconsole.log('first transform');returnhtml;},preload:()=>{// this one wins as it's the first defined in the chainconsole.log('first preload');returntrue;}});console.log('first post-processing');returnresult;}/// type: import('@sveltejs/kit/hooks').Handleasyncfunctionsecond({event,resolve}){console.log('second pre-processing');constresult=awaitresolve(event,{transformPageChunk:({html})=>{console.log('second transform');returnhtml;},preload:()=>{console.log('second preload');returntrue;},filterSerializedResponseHeaders:()=>{// this one wins as it's the first defined in the chainconsole.log('second filterSerializedResponseHeaders');returntrue;}});console.log('second post-processing');returnresult;}exportconsthandle=sequence(first,second);
The example above would print:
first pre-processing
first preload
second pre-processing
second filterSerializedResponseHeaders
second transform
first transform
second post-processing
first post-processing
Calling resolve invokes the next handler in the sequence (or SvelteKit itself, if it is the last one). To pass data between handlers, use event.locals.
first pre-processing
first preload
second pre-processing
second filterSerializedResponseHeaders
second transform
first transform
second post-processing
first post-processing
Exécuter resolve invoque le prochain gestionnaire de la séquence (ou SvelteKit lui-même, s’il
s’agit du dernier). Pour fournir des données entre chaque gestionnaire, utilisez event.locals.
L’erreur passée aux hooks handleError.
Utilisez le discriminant kind pour distinguer les erreurs venant de votre application (jetées avec
l’utilitaire error), les erreurs générées par SvelteKit lui-même
(comme les 404s), les erreurs de validation, et les erreurs inconnues (jetées par votre code, ou par
du code que votre code exécute).
typeCaughtError<IssueextendsStandardSchemaV1.Issue=StandardSchemaV1.Issue>=|{[KindinkeyofCaughtErrorMap]:{/** Identifie la catégorie et l'origine de l'erreur */kind:Kind;/** L'erreur attrapée. Son type dépend de `kind` */error:CaughtErrorMap[Kind];/** Seulement présente pour les erreurs de validation */issues?:undefined;/** Seulement présente pour les erreurs de validation */remote?:undefined;};}[keyofCaughtErrorMap]|ValidationCaughtError<Issue>;
Le hook init sera invoqué lors du démarrage de l’application dans le
navigateur.
typeClientInit=()=>MaybePromise<void>;
Handle
Le hook handle est exécuté à chaque fois que le serveur SvelteKit reçoit
une requête et en détermine la
réponse.
Il reçoit un objet event représentant la requête et une fonction appelée resolve, qui rend la
route et génère une Response.
Ceci vous permet de modifier les en-têtes ou les corps des réponses, ou contourner entièrement
SvelteKit (pour, par exemple, implémenter des routes programmatiquement).
Le hook client handleError est exécuté pour chaque erreur lancée
pendant une navigation, sauf pour les redirections.
Les erreurs qui ont déjà été transformées par le hook serveur ne lui sont pas passées pour ne pas
les traiter une seconde fois.
La propriété kind permet de discriminer entre les erreurs d’application (lancées avec
l’utilitaire error), les erreurs de framework (générées par
SvelteKit lui-même, comme les 404s), et les erreurs inconnues (lancées par votre code, ou par du
code que votre code exécute).
Le hook renvoie un objet satisfaisant l’interface App.Error, dans lequel status et message
sont optionnelles — renvoyez-les uniquement pour écraser les valeurs par défaut. Les propriétés
omises sont héritées de l’erreur attrapée : le corps passé à error(...) pour les erreurs
d’applicaction, le statut et un message sûr pour les erreurs de framework, et 500 / 'Internal Error' pour les erreurs inconnues. Ne renvoyez rien pour ne garder toutes les valeurs par défaut
(si vous choisissez d’augmenter App.Error avec des propriétés requises, vous devrez alors les
fournir).
Assurez-vous que cette fonction ne jette jamais d’erreur.
Le hook handleFetch vous permet de modifier (ou remplacer) le
résultat d’un appel event.fetch exécuté sur le serveur (ou
lors du prérendu) au sein d’un endpoint, d’une fonction load, d’une action, de handle, de
handleError, ou de reroute.
Le hook serveur handleError est exécuté pour chaque erreur lancée
La propriété kind permet de discriminer entre les erreurs d’application (lancées avec
l’utilitaire error), les erreurs de framework (générées par
SvelteKit lui-même, comme les 404s), et les erreurs inconnues (lancées par votre code, ou par du
code que votre code exécute).
Le hook renvoie un objet satisfaisant l’interface App.Error, dans lequel status et message
sont optionnelles — renvoyez-les uniquement pour écraser les valeurs par défaut. Les propriétés
omises sont héritées de l’erreur attrapée : le corps passé à error(...) pour les erreurs
d’applicaction, le statut et un message sûr pour les erreurs de framework, et 500 / 'Internal Error' pour les erreurs inconnues. Ne renvoyez rien pour ne garder toutes les valeurs par défaut
(si vous choisissez d’augmenter App.Error avec des propriétés requises, vous devrez alors les
fournir).
Assurez-vous que cette fonction ne jette jamais d’erreur.
input le morceau de html et l’info de s’il s’agit du dernier morceau ou non
Applique des transformations personnalisées sur le HTML. Si done est vrai, il s’agit du dernier
morecau de HTML. Il n’y a pas de garantie que les morceaux de HTML soient bien formés (il se peut
qu’ils incluent la balise ouvrante d’un élément, mais pas sa balise fermante, par exemple), mais ils
seront toujours découpés sur des frontières pertinentes comme %sveltekit.head% ou les composants
de layout ou de page.
Détermine quels en-tête devraient être inclus dans les réponses sérialisées lorsqu’une fonction
load charge une ressource avec fetch.
Par défaut, aucun ne sera inclus.
Détermine quels fichiers devraient être préchargés. Les fichiers sont préchargés via des balises
<link> ajoutées à la balise <head> ; si output.linkHeaderPreload est activée, les pages
dynamiquement rendues utiliseront plutôt les en-têtes de réponse
Link.
Par défaut, les fichiers js et css seront préchargés.
Pour les fichiers font, input a également une propriété filename, le chemin du fichier source
relatif à la racine du projet, de sorte qu’un filtre puisse le retrouver en se servant de ce chemin
plutôt que du chemin haché. Les fichiers js et css sont compilés et n’ont aucun nom de fichier
source.
ServerInit
Disponible depuis la version 2.10.0
Le hook init sera invoqué avant que le serveur ne réponde à sa première
requête.
typeServerInit=()=>MaybePromise<void>;
Transport
Disponible depuis la version 2.11.0
Le hook transport vous perment de transporter des types personnalisés
au travers de la frontière serveur/client.
Chaque transporteur possède une paire de fonctions encode et decode. Sur le serveur, encode
détermine si une valeur est une instance du type personnalisé, et, si c’est le cas, renvoie un
encodage non-falsy de la valeur pouvant être un objet ou un tableau (ou false sinon).
Dans le navigateur, decode transforme la valeur encodée en une instance du type personnalisé.
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.