Les “hooks” sont des fonctions que vous pouvez déclarer et que SvelteKit va appeler en réponse à des
évènements spécifiques, vous permettant de contrôler finement le comportement de l’application.
Il y a trois fichiers de hooks, tous optionnels :
src/hooks.server.js — les hooks serveur de votre application
src/hooks.client.js — les hooks client de votre application
src/hooks.js — les hooks de votre application qui peuvent être exécutés à la fois sur le client
et sur le serveur
Le code dans ces modules s’exécutera lors du démarrage de l’application, les rendant utile pour
l’initialisation de clients de bases de données, parmi d’autres choses.
handle
Peut être ajoutée dans le fichier src/hooks.server.js
Cette fonction est exécutée à chaque fois que le serveur SvelteKit reçoit une
requête — que cela se produise lors de l’exécution de
l’application ou lors du pré-rendu — et en détermine la
réponse. Elle reçoit un objet event représentant la requête
et une fonction appelée resolve, qui fait le rendu de la route et génère une Response. Ceci vous
permet de modifier les en-têtes ou body de réponse, ou d’implémenter un middleware (pour
par exemple rejeter les requêtes ayant une limite d’utilisation).
('Trop de requêtes',{status(property)ResponseInit.status?:number|undefined:429});}constresponseconstresponse:Response=awaitresolve(parameter)resolve:(event:RequestEvent,opts?:ResolveOptions)=>Promise<Response>(event(parameter)event:RequestEvent<Record<string,string>,string|null>);returnresponseconstresponse:Response;}
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).
('Trop de requêtes',{status(property)ResponseInit.status?:number|undefined:429});}constresponseconstresponse:Response=awaitresolve(parameter)resolve:(event:RequestEvent,opts?:ResolveOptions)=>Promise<Response>(event(parameter)event:RequestEvent<Record<string,string>,string|null>);returnresponseconstresponse:Response;};
Les requêtes demandant des assets statiques — incluant les pages déjà prérendues — ne sont
pas gérées par SvelteKit.
Si le hook handle est exécutée en tant que partie d’une requête de fonction distante initiée par
le client, route, params et url sont relatifs à la page depuis laquelle la fonction distante a
été appelée, et non l’URL du endpoint que SvelteKit crée pour la fonction distante. Ne les
utilisez jamais pour déterminer si oui ou non un utilisateur ou utilisatrice est autorisée à accéder
à certaines données, puisque ces valeurs font partie de la requête et peuvent donc être manipulées.
les queries ne sont de plus pas ré-exécutées lorsque l’utilisateur ou l’utilisatrice navigue (à
moins que l’argument de la query ait changé suite à une navigation), vous devriez donc être
conscient•e de la façon dont vous utilisez ces valeurs.
Si non implémentée, cette fonction vaut par défaut ({ event, resolve }) => resolve(event).
Durant le prérendu, Svelte parcourt vos pages à la recherche de liens et rend chaque route qu’il
trouve. Le fait de rendre la route provoque l’exécution de la fonction handle (et de toute autre
dépendance de route, comme load). Si vous avez besoin d’empêcher du code d’être exécuté lors de
cette phase, vérifier en amont que l’application n’est pas en train d’être compilée (via
building.
resolve supporte également un deuxième paramètre optionnel qui vous donne plus de contrôle sur la
manière dont la réponse va être rendue. Ce paramètre est un objet qui peut avoir les champs suivants
:
transformPageChunk(opts: { html: string, done: boolean }): MaybePromise<string | undefined> —
applique des transformations personnalisées au HTML. Si done vaut true, il s’agit du dernier
fragment. Il n’y a pas de garantie que chaque fragment individuel soit du HTML bien formé (il se
peut qu’un fragment inclut la balise ouvrante d’un élément mais pas sa balise fermante, par exemple)
mais ils seront toujours découpés à des endroits clés tels que %sveltekit.head ou les composants
de layout ou de page.
filterSerializedResponseHeaders(name: string, value: string): boolean — détermine quels en-têtes
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.
preload(input: { type: 'js' | 'css' | 'asset', path: string }) | { type: 'font', path: string, filename: string }): boolean — détermine
quels fichiers devraient être ajoutés à la balise <head> pour les précharger. La méthode est
appelée avec chaque fichier trouvé pendant la construction des fragments de code au moment de la
compilation — donc si vous avez par exemple import './styles.css' dans votre fichier
+page.svelte, preload sera appelé avec le chemin résolu menant à ce fichier CSS lorsque la page
sera visitée. Notez qu’en mode développement preload n’est pas appelé, puisqu’il dépend de
l’analyse se produisant lors de la compilation. Le préchargement peut améliorer la performance en
téléchargeant les assets plus tôt, mais cela peut aussi la pénaliser si trop de choses sont
téléchargées sans raison. Par défaut, les fichiers js et css seront préchargés. Les fichiers
asset ne sont actuellement pas préchargés du tout, mais il est possible que cela soit ajouté à
SvelteKit plus tard, en fonction des retours sur le sujet. 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é.
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
Replaces text in a string, using a regular expression or search string.
searchValue
A string or regular expression to search for.
replaceValue
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.
Determines which headers should be included in serialized responses when a load function loads a resource with fetch.
By default, none will be included.
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.
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.
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.
searchString
search string
position
If position is undefined, 0 is assumed, so as to search all of the String.
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
Replaces text in a string, using a regular expression or search string.
searchValue
A string or regular expression to search for.
replaceValue
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.
Determines which headers should be included in serialized responses when a load function loads a resource with fetch.
By default, none will be included.
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.
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.
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.
searchString
search string
position
If position is undefined, 0 is assumed, so as to search all of the String.
Notez que resolve(...) ne lèvera jamais d’erreur, mais renverra toujours une Promise<Response>
avec le statut approprié. Si une erreur est levée ailleurs lors de l’exécution de handle, elle est
traitée comme étant fatale, et SvelteKit répondra avec une représentation JSON de l’erreur ou avec
la page d’erreur de secours — qui peut être personnalisée via src/error.html — selon la valeur de
l’en-tête Accept. Vous pouvez en apprendre plus à propos de la gestion des erreurs here.
locals
Pour ajouter des données personnalisées à la requête, qui seront ensuite passées aux gestionnaires
des fichiers +server.js et aux fonctions load, remplissez l’objet event.locals, comme montré
ci-dessous.
Gets a cookie that was previously set with cookies.set, or from the request headers.
name
the name of the cookie
opts
the options, passed directly to cookie.parseCookie. See documentation here
('sessionid'));constresponseconstresponse:Response=awaitresolve(parameter)resolve:(event:RequestEvent,opts?:ResolveOptions)=>Promise<Response>(event(parameter)event:RequestEvent<Record<string,string>,string|null>); // Notez que modifier les en-têtes de réponse n'est pas toujours sécurisé.
// Les objets de réponse peuvent avoir des en-têtes immutables (par ex.
// Response.redirect() renvoyé par un endpoint).
// Modifier les en-têtes immutables jette une erreur TypeError.
// Dans ce cas, clonez la réponse ou évitez de créer un objet de réponse
// ayant des en-têtes immutables.
responseconstresponse:Response.headers(property)Response.headers:Headers
The headers read-only property of the Response interface contains the Headers object associated with the response.
The set() method of the Headers interface sets a new value for an existing header inside a Headers object, or adds the header if it does not already exist.
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).
Gets a cookie that was previously set with cookies.set, or from the request headers.
name
the name of the cookie
opts
the options, passed directly to cookie.parseCookie. See documentation here
('sessionid'));constresponseconstresponse:Response=awaitresolve(parameter)resolve:(event:RequestEvent,opts?:ResolveOptions)=>Promise<Response>(event(parameter)event:RequestEvent<Record<string,string>,string|null>); // Notez que modifier les en-têtes de réponse n'est pas toujours sécurisé.
// Les objets de réponse peuvent avoir des en-têtes immutables (par ex.
// Response.redirect() renvoyé par un endpoint).
// Modifier les en-têtes immutables jette une erreur TypeError.
// Dans ce cas, clonez la réponse ou évitez de créer un objet de réponse
// ayant des en-têtes immutables.
responseconstresponse:Response.headers(property)Response.headers:Headers
The headers read-only property of the Response interface contains the Headers object associated with the response.
The set() method of the Headers interface sets a new value for an existing header inside a Headers object, or adds the header if it does not already exist.
Peut être ajoutée dans le fichier src/hooks.server.js
Cette fonction vous permet de modifier (ou remplacer) le résultat d’un appel
event.fetch se produisant sur le serveur (ou pendant le pré-rendu)
au sein d’un endpoint, ou d’une fonction load, action, handle, handleError or reroute.
Par exemple, imaginons que votre fonction load fasse une requête vers une URL publique comme
https://api.yourapp.com lorsqu’un utilisateur ou utilisatrice effectue une navigation côté client
vers la page concernée. Lors du rendu serveur de cette page, cela aurait du sens d’appeler
directement l’API (en contournant tout éventuel proxy ou gestionnaire de charge qui pourrait se
trouver entre l’API et internet).
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.
('https://api.yourapp.com/')){ // clone la requête originale, mais change l'URL
request(parameter)request:Request=newRequestvarRequest:new(input:RequestInfo|URL,init?:RequestInit)=>Request
The Request interface of the Fetch API represents a resource request.
Replaces text in a string, using a regular expression or search string.
searchValue
A string or regular expression to search for.
replaceValue
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.
The handleFetch hook 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.
The handleFetch hook 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.
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.
('https://api.yourapp.com/')){ // clone la requête originale, mais change l'URL
request(parameter)request:Request=newRequestvarRequest:new(input:RequestInfo|URL,init?:RequestInit)=>Request
The Request interface of the Fetch API represents a resource request.
Replaces text in a string, using a regular expression or search string.
searchValue
A string or regular expression to search for.
replaceValue
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.
Les requêtes faites avec event.fetch suivent le modèle d’authentification du navigateur — pour les
requêtes de même origine, les en-têtes cookie et authorization sont relayés à moins que l’option
credentials soit définie comme "omit". Pour les requêtes d’origine différente (cross-origin),
cookie sera inclus si l’URL de la requête appartient à un sous-domaine de l’application — par
exemple si votre appliation est sur my-domain.com et que votre API est sur api.my-domain.com,
les cookies seront inclus dans la requête.
Il y a tout de même une limitation : si votre application et votre API sont sur des sous-domaines
frères — www.my-domain.com et api.my-domain.com par exemple — alors un cookie appartenant à un
domaine parent commun comme my-domain.com ne sera pas inclus, car SvelteKit n’a aucun moyen de
savoir à quel domaine appartient le cookie. Dans ces situations vous devrez manuellement inclure le
cookie en utilisant handleFetch :
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.
The set() method of the Headers interface sets a new value for an existing header inside a Headers object, or adds the header if it does not already exist.
The get() method of the Headers interface returns a byte string of all the values of a header within a Headers object with a given name. If the requested header doesn't exist in the Headers object, it returns null.
The handleFetch hook 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.
The handleFetch hook 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.
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.
The set() method of the Headers interface sets a new value for an existing header inside a Headers object, or adds the header if it does not already exist.
The get() method of the Headers interface returns a byte string of all the values of a header within a Headers object with a given name. If the requested header doesn't exist in the Headers object, it returns null.
Peut être ajoutée aux fichiers src/hooks.server.js et src/hooks.client.js
Cette fonction est appelée pour chaque erreur jetée lors du chargement, du rendu, ou du traitement
de la réponse à une requête. Elle permet deux choses :
vous pouvez afficher l’erreur
vous pouvez générer une représentation personnalisée de l’erreur que vous pouvez afficher aux
utilisateurs et utilisatrices, nettoyée des informations sensibles comme les messages ou les stack
traces
En plus de event, le hook reçoit un discriminant kind qui vous dit d’où l’erreur est venue,
ainsi que l’error elle-même :
'app' — l’erreur vient de votre application via error(...)
error est le corps de l’erreur, qui hérite de App.Error
renvoie par défaut le corps de l’erreur elle-même
'framework' — l’erreur vient de SvelteKit, comme une 404, 405 ou 413
error est { status, message }, où message est du texte non dangereux comme Not Found
renvoie par défaut ce même objet { status, message }
'validation' (uniquement sur le serveur) — l’erreur vient de la validation d’un argument d’une
fonction distante vis-à-vis de son Standard Schema
error est l’objet { status: 400, message: 'Bad Request' }, et issues contient les
problèmes de validation
renvoie par défaut l’objet error ; les problèmes ne sont pas exposés à moins que vous ne les
renvoyiez explicitement vous-même
pour accéder aux propriétés des problèmes spécifiques à la librairie de validation, paramétrez
HandleServerError avec le type de problème, par exemple HandleServerError<CustomIssue>
'unknown' — on ne sait pas ce qu’il s’est mal passé ; l’erreur a été jetée par votre code, ou du
code que votre code exécute
error est la valeur jetée, qui peut contenir des informations sensibles à ne pas exposer au
public
renvoie par défaut { status: 500, message: 'Internal Error' }
La prochaine section, Errors, explique les autres catégories plus en détail. Les
redirections ne sont pas des erreurs, et n’atteignent jamais ce hook.
Ce hook renvoie un objet héritant de App.Error, dans lequel status et message
sont optionnels — renvoyez-les uniquement pour écraser les valeurs par défaut décrites dans la liste
ci-dessus.
Si vous augmentez App.Error avec des propriétés additionnelles requises, le hook doit
les renvoyer.
Pour ajouter plus d’informations à l’objet page.error de manière typée, augmentez l’interface
App.Error existante avec vos propriétés supplémentaires. Les propriété intégrées status et
message sont déjà présentes et n’ont pas besoin d’être re-déclarées. Par exemple, vous pouvez
ajouter un ID de suivi que vous utilisateurs et utilisatrices pourront utiliser pour contacter votre
support :
It's possible to tell SvelteKit how to type objects inside your app by declaring the App namespace. By default, a new project will have a file called src/app.d.ts containing the following:
The export {} line exists because without it, the file would be treated as an ambient module which prevents you from adding import declarations.
If you need to add ambient declare module declarations, do so in a separate file like src/ambient.d.ts.
By populating these interfaces, you will gain type safety when using event.locals, event.platform, and data from load functions.
{interfaceErrorinterfaceApp.Error
Defines the common shape of expected and unexpected errors. Expected errors are thrown using the error function. Every error passes through the handleError hooks, which must return this shape (with status and message optional, since they default to those of the caught error).
==='app'){ // vous avez créé cette erreur avec `error(...)`, elle hérite donc déjà
// de `App.Error` — on la relaie inchangée
returnerror(parameter)error:App.Error
The randomUUID() method of the Crypto interface is used to generate a v4 UUID using a cryptographically secure random number generator.
Available only in secure contexts.
==='framework'){ // une 404 (ou similaire) — `error.status` et `error.message` peuvent être exposés
// au public sans risque, on les garde donc, et on leur ajoute une autre propriété
return{...error(parameter)error:{status:number;message:string;}
The caught error. Its type depends on kind
,errorId(property)errorId:`${string}-${string}-${string}-${string}-${string}`};} // exemple d'intégration avec https://sentry.io/
Sentry(alias)module"@sentry/sveltekit"importSentry.captureExceptionconstcaptureException:(error:any,opts:any)=>void(error(parameter)error:unknown
The caught error. Its type depends on kind
,{extra(property)extra:{event:RequestEvent<Record<string,string>,string|null>;errorId:`${string}-${string}-${string}-${string}-${string}`;}:{event(property)event:RequestEvent<Record<string,string>,string|null>,errorId(property)errorId:`${string}-${string}-${string}-${string}-${string}`}}); // `status` et `message` sont optionels — nous écrasons uniquement `message`,
// pour que le statut garde sa valeur par défaut de 500
return{message(property)message?:string|undefined:'Oups !',errorId(property)errorId:`${string}-${string}-${string}-${string}-${string}`};}
The server-side handleError hook runs for every error thrown while responding to a request, except redirects.
The kind property discriminates between app errors (thrown with the error helper),
framework errors (generated by SvelteKit itself, such as 404s), validation errors (caused by invalid remote function arguments)
and unknown errors (thrown by your code, or code it calls).
The hook returns an object matching App.Error, in which status and message are optional — return them only to
override the defaults. Omitted properties are inherited from the caught error: the body passed to error(...) for app errors,
the status and safe message for framework and validation errors, and 500/'Internal Error' for unknown errors. Return nothing to
keep the defaults entirely (if you augment App.Error with required properties, you must return those).
Make sure that this function never throws an error.
The server-side handleError hook runs for every error thrown while responding to a request, except redirects.
The kind property discriminates between app errors (thrown with the error helper),
framework errors (generated by SvelteKit itself, such as 404s), validation errors (caused by invalid remote function arguments)
and unknown errors (thrown by your code, or code it calls).
The hook returns an object matching App.Error, in which status and message are optional — return them only to
override the defaults. Omitted properties are inherited from the caught error: the body passed to error(...) for app errors,
the status and safe message for framework and validation errors, and 500/'Internal Error' for unknown errors. Return nothing to
keep the defaults entirely (if you augment App.Error with required properties, you must return those).
Make sure that this function never throws an error.
==='app'){ // vous avez créé cette erreur avec `error(...)`, elle hérite donc déjà
// de `App.Error` — on la relaie inchangée
returnerror(parameter)error:App.Error
The randomUUID() method of the Crypto interface is used to generate a v4 UUID using a cryptographically secure random number generator.
Available only in secure contexts.
==='framework'){ // une 404 (ou similaire) — `error.status` et `error.message` peuvent être exposés
// au public sans risque, on les garde donc, et on leur ajoute une autre propriété
return{...error(parameter)error:{status:number;message:string;}
The caught error. Its type depends on kind
,errorId(property)errorId:`${string}-${string}-${string}-${string}-${string}`};} // exemple d'intégration avec https://sentry.io/
Sentry(alias)module"@sentry/sveltekit"importSentry.captureExceptionconstcaptureException:(error:any,opts:any)=>void(error(parameter)error:unknown
The caught error. Its type depends on kind
,{extra(property)extra:{event:RequestEvent<Record<string,string>,string|null>;errorId:`${string}-${string}-${string}-${string}-${string}`;}:{event(property)event:RequestEvent<Record<string,string>,string|null>,errorId(property)errorId:`${string}-${string}-${string}-${string}-${string}`}}); // `status` et `message` sont optionels — nous écrasons uniquement `message`,
// pour que le statut garde sa valeur par défaut de 500
return{message(property)message?:string|undefined:'Oups !',errorId(property)errorId:`${string}-${string}-${string}-${string}-${string}`};};
The randomUUID() method of the Crypto interface is used to generate a v4 UUID using a cryptographically secure random number generator.
Available only in secure contexts.
,errorId(property)errorId:`${string}-${string}-${string}-${string}-${string}`};} // exemple d'intégration avec https://sentry.io/
Sentry(alias)module"@sentry/sveltekit"importSentry.captureExceptionconstcaptureException:(error:any,opts:any)=>void(error(parameter)error:unknown
The client-side handleError hook runs for every error thrown while navigating, except redirects.
Errors that were already transformed by the server-side hook are not passed to it a second time.
The kind property discriminates between app errors (thrown with the error helper),
framework errors (generated by SvelteKit itself, such as 404s) and unknown errors (thrown by your code, or code it calls).
The hook returns an object matching App.Error, in which status and message are optional — return them only to
override the defaults. Omitted properties are inherited from the caught error: the body passed to error(...) for app errors,
the status and safe message for framework errors, and 500/'Internal Error' for unknown errors. Return nothing to
keep the defaults entirely (if you augment App.Error with required properties, you must return those).
Make sure that this function never throws an error.
The client-side handleError hook runs for every error thrown while navigating, except redirects.
Errors that were already transformed by the server-side hook are not passed to it a second time.
The kind property discriminates between app errors (thrown with the error helper),
framework errors (generated by SvelteKit itself, such as 404s) and unknown errors (thrown by your code, or code it calls).
The hook returns an object matching App.Error, in which status and message are optional — return them only to
override the defaults. Omitted properties are inherited from the caught error: the body passed to error(...) for app errors,
the status and safe message for framework errors, and 500/'Internal Error' for unknown errors. Return nothing to
keep the defaults entirely (if you augment App.Error with required properties, you must return those).
Make sure that this function never throws an error.
The randomUUID() method of the Crypto interface is used to generate a v4 UUID using a cryptographically secure random number generator.
Available only in secure contexts.
,errorId(property)errorId:`${string}-${string}-${string}-${string}-${string}`};} // exemple d'intégration avec https://sentry.io/
Sentry(alias)module"@sentry/sveltekit"importSentry.captureExceptionconstcaptureException:(error:any,opts:any)=>void(error(parameter)error:unknown
Dans le fichier src/hooks.client.js, le type de handleError est HandleClientError au
lieu de HandleServerError, et event est un NavigationEvent plutôt qu’un RequestEvent.
Les erreurs qui étaient déjà transformées par le hook serveur ne sont pas passées au hook client une
deuxième fois.
Lors du développement, si une erreur se produit à cause d’une erreur de syntaxe dans votre code
Svelte, l’erreur fournie aura une propriété frame mettant en valeur la position de l’erreur.
Assurez-vous que handleError ne jette jamais d’erreur.
init
Peut être ajoutée aux fichiers src/hooks.server.js et src/hooks.client.js
Cette fonction est exécutée une seule fois, lorsque le serveur est créé ou lorsque l’application
démarre dans le navigateur. C’est une fonction pratique pour effectuer des opérations asynchrones
comme l’initialisation d’une connexion à une base de données.
Si votre environnement support le fait d’écrire await à la racine de votre fichier,
utiliser la fonction init n’est pas vraiment différente d’initialiser votre logique
d’initialisation à la racine du module, mais certains environnements — le plus connu étant Safari
— ne le supportent pas.
The init will be invoked before the server responds to its first request
2.10.0
=async()=>{awaitdbimportdb.connectany();};
Dans le navigateur, les tâches asynchrones au sein de init vont retarder l’hydratation,
soyez donc conscient•e de ce que vous y faites.
reroute
Peut être ajoutée au fichier src/hooks.js ; elle est exécutée à la fois sur le serveur
et sur le client.
Cette fonction est exécutée avant handle et vous permet de changer la manière dont les URLs sont
traduites en routes. Le chemin renvoyé (qui vaut par défaut url.pathname) est utilisé pour
sélectionner la route et ses paramètres.
Par exemple, vous pourriez avoir une page src/routes/[[lang]]/about/+page.svelte, qui devrait être
accessible en tant que /en/about, /de/ueber-uns ou /fr/a-propos. Vous pourriez implémenter
ceci avec reroute :
The pathname property of the URL interface represents a location in a hierarchical structure. It is a string constructed from a list of path segments, each of which is prefixed by a / character.
The pathname property of the URL interface represents a location in a hierarchical structure. It is a string constructed from a list of path segments, each of which is prefixed by a / character.
The pathname property of the URL interface represents a location in a hierarchical structure. It is a string constructed from a list of path segments, each of which is prefixed by a / character.
The pathname property of the URL interface represents a location in a hierarchical structure. It is a string constructed from a list of path segments, each of which is prefixed by a / character.
Le paramètre lang sera correctement déduit du chemin renvoyé.
Le fait d’utiliser reroute ne changera pas le contenu de la barre d’adresse, ni la valeur de
event.url.
Depuis la version 2.18, le hook reroute peut être asynchrone, vous permettant de (par exemple)
récupérer des données depuis votre backend pour décider vers quelle route re-router. Assurez-vous
que la récupération de données soit rapide, car cela retardera la navigation sinon. Si vous avez
besoin de récupérer des données, utilisez la fonction fetch fourni en argument. Celle-ci hérite
des mêmes bénéfices que la fonction fetch fournie aux fonctions
load, avec l’inconvénient que params et id ne seront pas rendus disponibles pour
handleFetch car la route n’est à ce moment-là pas encore déterminée.
({url(parameter)url:URL,fetch(parameter)fetch:{(input:RequestInfo|URL,init?:RequestInit):Promise<Response>;(input:string|URL|Request,init?:RequestInit):Promise<Response>;}}){ // Demandez à un endpoint spécial de votre application quelle est la destination
if(url(parameter)url:URL.pathname(property)URL.pathname:string
The pathname property of the URL interface represents a location in a hierarchical structure. It is a string constructed from a list of path segments, each of which is prefixed by a / character.
The URL interface is used to parse, construct, normalize, and encode URLs. It works by providing properties which allow you to easily read and modify the components of a URL.
The searchParams read-only property of the URL interface returns a URLSearchParams object allowing access to the GET decoded query arguments contained in the URL.
The set() method of the URLSearchParams interface sets the value associated with a given search parameter to the given value. If there were several matching values, this method deletes the others. If the search parameter doesn't exist, this method creates it.
The pathname property of the URL interface represents a location in a hierarchical structure. It is a string constructed from a list of path segments, each of which is prefixed by a / character.
The reroute hook allows you to modify the URL before it is used to determine which route to render.
2.3.0
=async({url(parameter)url:URL,fetch(parameter)fetch:{(input:RequestInfo|URL,init?:RequestInit):Promise<Response>;(input:string|URL|Request,init?:RequestInit):Promise<Response>;}})=>{ // Demandez à un endpoint spécial de votre application quelle est la destination
if(url(parameter)url:URL.pathname(property)URL.pathname:string
The pathname property of the URL interface represents a location in a hierarchical structure. It is a string constructed from a list of path segments, each of which is prefixed by a / character.
The URL interface is used to parse, construct, normalize, and encode URLs. It works by providing properties which allow you to easily read and modify the components of a URL.
The searchParams read-only property of the URL interface returns a URLSearchParams object allowing access to the GET decoded query arguments contained in the URL.
The set() method of the URLSearchParams interface sets the value associated with a given search parameter to the given value. If there were several matching values, this method deletes the others. If the search parameter doesn't exist, this method creates it.
The pathname property of the URL interface represents a location in a hierarchical structure. It is a string constructed from a list of path segments, each of which is prefixed by a / character.
La fonction reroute est considérée comme une fonction pure et idempotent. Par
conséquence, elle doit toujours renvoyer le même résultat pour une entrée donnée, et ne doit pas
avoir d’effets de bord. Avec ces considérations, SvelteKit va cacher le résultat de reroute sur
le client afin que reroute ne soit exécutée qu’une seule fois par URL unique.
transport
Peut être ajoutée au fichier src/hooks.js ; elle est exécutée à la fois sur le serveur
et sur le client.
Une collection de transporteurs, qui vous permettent de fournir des types personnalisés — renvoyés
depuis une fonction load, au travers de la frontière serveur/client. Chaque transporteur contient
une fonction encode, qui encode les valeurs sur le serveur (ou renvoie une valeur falsy pour ce
qui n’est pas une instance du type) et une fonction decode correspondante :
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.