Les variables d’environnement sont des valeurs dont votre application a besoin, mais qui existent en
dehors du code source de votre application. Elles vous permettent d’utiliser des informations
sensibles comme des clés d’API ou des authentifiants de bases de données sans les stocker dans votre
contrôle de version.
Lors du développement, et au moment de la compilation, les variables définies dans un fichier .env
ou .env.local seront ajoutées à l’environnement :
.env
API_KEY=19f401ba-e8b0-48c4-8c77-b0ebb26d97fe
Après avoir suivi la mise en place ci-dessous, les variables d’environnement peuvent être importées
via les modules suivantes :
Les modules $env/*, ainsi que $app/environment, ont été dépréciés avec SvelteKit 3 (et seront
supprimés avec SvelteKit 4) en faveur de variables d’environnement explicites qui ont été ajoutées
avec SvelteKit 2.62 en tant qu’option expérimentale.
Setup
Ajoutez un fichier src/env.ts (ou src/env.js) exportant un objet variables :
Utility for defining environment variables,
which are made available via $app/env/public and $app/env/private.
import{defineEnvVars}from'@sveltejs/kit/env';import*asvfrom'valibot';exportconstvariables=defineEnvVars({API_URL:{schema:v.pipe(v.string(),v.url())},PORT:{schema:(value)=>{if(value===undefined)return3000;constport=Number(value);if(!Number.isInteger(port))thrownewError('PORT must be an integer');returnport;}}});
Utility for defining environment variables,
which are made available via $app/env/public and $app/env/private.
import{defineEnvVars}from'@sveltejs/kit/env';import*asvfrom'valibot';exportconstvariables=defineEnvVars({API_URL:{schema:v.pipe(v.string(),v.url())},PORT:{schema:(value)=>{if(value===undefined)return3000;constport=Number(value);if(!Number.isInteger(port))thrownewError('PORT must be an integer');returnport;}}});
({ // ...
});
Chaque valeur de l’objet passée à defineEnvVars est un objet
EnvVarConfig qui configure la variable d’environnement.
defineEnvVars renvoie son argument inchangé — cette fonction n’existe que pour vous
aider avec le typage.
Variables privées
Par défaut, toutes les variables sont considérées privées. Par exemple, vous ne souhaitez pas
révéler votre API_KEY :
Utility for defining environment variables,
which are made available via $app/env/public and $app/env/private.
import{defineEnvVars}from'@sveltejs/kit/env';import*asvfrom'valibot';exportconstvariables=defineEnvVars({API_URL:{schema:v.pipe(v.string(),v.url())},PORT:{schema:(value)=>{if(value===undefined)return3000;constport=Number(value);if(!Number.isInteger(port))thrownewError('PORT must be an integer');returnport;}}});
Utility for defining environment variables,
which are made available via $app/env/public and $app/env/private.
import{defineEnvVars}from'@sveltejs/kit/env';import*asvfrom'valibot';exportconstvariables=defineEnvVars({API_URL:{schema:v.pipe(v.string(),v.url())},PORT:{schema:(value)=>{if(value===undefined)return3000;constport=Number(value);if(!Number.isInteger(port))thrownewError('PORT must be an integer');returnport;}}});
({API_KEY(property)API_KEY:{}:{}});
Puisqu’aucune configuration n’est nécessaire pour cette variable, nous pouvons utiliser un
objet vide ({}).
Maintenant que API_KEY est défini, elle peut être importée dans le code applicatif via
$app/env/private :
Le module $app/env/private ne peut pas être importé dans du code exécuté dans le navigateur, de
sorte que ne puissiez pas accidentellement révéler vos secrets dans un bundle JavaScript.
Variables publiques
Certaines variables peuvent être rendues accessibles dans le navigateur sans aucun danger — c’est
même parfois nécessaire. Pour ces variables, nous pouvons préciser public: true :
Utility for defining environment variables,
which are made available via $app/env/public and $app/env/private.
import{defineEnvVars}from'@sveltejs/kit/env';import*asvfrom'valibot';exportconstvariables=defineEnvVars({API_URL:{schema:v.pipe(v.string(),v.url())},PORT:{schema:(value)=>{if(value===undefined)return3000;constport=Number(value);if(!Number.isInteger(port))thrownewError('PORT must be an integer');returnport;}}});
Utility for defining environment variables,
which are made available via $app/env/public and $app/env/private.
import{defineEnvVars}from'@sveltejs/kit/env';import*asvfrom'valibot';exportconstvariables=defineEnvVars({API_URL:{schema:v.pipe(v.string(),v.url())},PORT:{schema:(value)=>{if(value===undefined)return3000;constport=Number(value);if(!Number.isInteger(port))thrownewError('PORT must be an integer');returnport;}}});
GOOGLE_ANALYTICS_ID peut maintenant être importée depuis $app/env/public, ou utilisée dans votre
fichier de template app.html en tant que %sveltekit.env.GOOGLE_ANALYTICS_ID% :
Utility for defining environment variables,
which are made available via $app/env/public and $app/env/private.
import{defineEnvVars}from'@sveltejs/kit/env';import*asvfrom'valibot';exportconstvariables=defineEnvVars({API_URL:{schema:v.pipe(v.string(),v.url())},PORT:{schema:(value)=>{if(value===undefined)return3000;constport=Number(value);if(!Number.isInteger(port))thrownewError('PORT must be an integer');returnport;}}});
Utility for defining environment variables,
which are made available via $app/env/public and $app/env/private.
import{defineEnvVars}from'@sveltejs/kit/env';import*asvfrom'valibot';exportconstvariables=defineEnvVars({API_URL:{schema:v.pipe(v.string(),v.url())},PORT:{schema:(value)=>{if(value===undefined)return3000;constport=Number(value);if(!Number.isInteger(port))thrownewError('PORT must be an integer');returnport;}}});
Hint: Be careful with the global flag g in your regex pattern, as it can lead to unexpected results. See MDN for more information.
requirement
The regex pattern.
A regex action.
(/G-[A-Z0-9]+/))}});
Si vous ne souhaitez pas intégrer une librairie de schéma, vous pouvez passer une fonction qui
renvoie la valeur (potentiellement transformée), ou jette une erreur expliquant le problème :
Utility for defining environment variables,
which are made available via $app/env/public and $app/env/private.
import{defineEnvVars}from'@sveltejs/kit/env';import*asvfrom'valibot';exportconstvariables=defineEnvVars({API_URL:{schema:v.pipe(v.string(),v.url())},PORT:{schema:(value)=>{if(value===undefined)return3000;constport=Number(value);if(!Number.isInteger(port))thrownewError('PORT must be an integer');returnport;}}});
Utility for defining environment variables,
which are made available via $app/env/public and $app/env/private.
import{defineEnvVars}from'@sveltejs/kit/env';import*asvfrom'valibot';exportconstvariables=defineEnvVars({API_URL:{schema:v.pipe(v.string(),v.url())},PORT:{schema:(value)=>{if(value===undefined)return3000;constport=Number(value);if(!Number.isInteger(port))thrownewError('PORT must be an integer');returnport;}}});
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.
('G-'))thrownewErrorvarError:ErrorConstructornew(message?:string,options?:ErrorOptions)=>Error(+1overload)('doit être un ID Google Analytics');returnvalue(parameter)value:string;}}});
Si une valeur est invalide, l’application échouera à se lancer (ou à compiler). Pour en désactiver
une, utilisez l’export building de $app/env en combinaison avec un
validateur qui accepte une valeur optionnelle :
Utility for defining environment variables,
which are made available via $app/env/public and $app/env/private.
import{defineEnvVars}from'@sveltejs/kit/env';import*asvfrom'valibot';exportconstvariables=defineEnvVars({API_URL:{schema:v.pipe(v.string(),v.url())},PORT:{schema:(value)=>{if(value===undefined)return3000;constport=Number(value);if(!Number.isInteger(port))thrownewError('PORT must be an integer');returnport;}}});
Utility for defining environment variables,
which are made available via $app/env/public and $app/env/private.
import{defineEnvVars}from'@sveltejs/kit/env';import*asvfrom'valibot';exportconstvariables=defineEnvVars({API_URL:{schema:v.pipe(v.string(),v.url())},PORT:{schema:(value)=>{if(value===undefined)return3000;constport=Number(value);if(!Number.isInteger(port))thrownewError('PORT must be an integer');returnport;}}});
({SECRET(property)SECRET:{schema:v.StringSchema<undefined>|v.OptionalSchema<v.StringSchema<undefined>,undefined>;}:{ // optionnel lors de la compilation, mais requis au démarrage de l'application
schema(property)schema:v.StringSchema<undefined>|v.OptionalSchema<v.StringSchema<undefined>,undefined>:building(alias)constbuilding:booleanimportbuilding
SvelteKit analyses your app during the build step by running it. During this process, building is true. This also applies during prerendering.
Vous pouvez utiliser le validateurs pour rendre des valeurs optionnelles, ou les transformer (comme
transformer une string en booléen, ou parser du JSON) — voir la documentation de votre librairie de
validation pour en savoir plus.
Variables statiques
Par défaut, les variables sont dynamiques. Si une variable est configurée avec static: true, elle
sera inlinée dans le code applicatif, permettant des optimisations telles que l’élimination de code
mort :
Utility for defining environment variables,
which are made available via $app/env/public and $app/env/private.
import{defineEnvVars}from'@sveltejs/kit/env';import*asvfrom'valibot';exportconstvariables=defineEnvVars({API_URL:{schema:v.pipe(v.string(),v.url())},PORT:{schema:(value)=>{if(value===undefined)return3000;constport=Number(value);if(!Number.isInteger(port))thrownewError('PORT must be an integer');returnport;}}});
Utility for defining environment variables,
which are made available via $app/env/public and $app/env/private.
import{defineEnvVars}from'@sveltejs/kit/env';import*asvfrom'valibot';exportconstvariables=defineEnvVars({API_URL:{schema:v.pipe(v.string(),v.url())},PORT:{schema:(value)=>{if(value===undefined)return3000;constport=Number(value);if(!Number.isInteger(port))thrownewError('PORT must be an integer');returnport;}}});
({SHOW_DEBUG_OVERLAY(property)SHOW_DEBUG_OVERLAY:{public:true;static:true;schema:v.SchemaWithPipe<readonly[v.OptionalSchema<v.StringSchema<undefined>,"">,v.TransformAction<string,boolean>]>;}:{public(property)public:true:true,static(property)static:true:true, // transforme la valeur en true/false
schema(property)schema:v.SchemaWithPipe<readonly[v.OptionalSchema<v.StringSchema<undefined>,"">,v.TransformAction<string,boolean>]>:vimportv.pipe(alias)pipe<v.OptionalSchema<v.StringSchema<undefined>,"">,v.TransformAction<string,boolean>>(schema:v.OptionalSchema<v.StringSchema<undefined>,"">,item1:v.TransformAction<string,boolean>|v.PipeAction<string,boolean,never>):v.SchemaWithPipe<readonly[v.OptionalSchema<v.StringSchema<undefined>,"">,v.TransformAction<string,boolean>]>(+20overloads)exportpipe
Adds a pipeline to a schema, that can validate and transform its input.
Puisque cette variable est static, le composant <DebugOverlay> utilisé ici sera exclus du bundle
JavaScript à moins que SHOW_DEBUG_OVERLAY ne soit vrai :
Utility for defining environment variables,
which are made available via $app/env/public and $app/env/private.
import{defineEnvVars}from'@sveltejs/kit/env';import*asvfrom'valibot';exportconstvariables=defineEnvVars({API_URL:{schema:v.pipe(v.string(),v.url())},PORT:{schema:(value)=>{if(value===undefined)return3000;constport=Number(value);if(!Number.isInteger(port))thrownewError('PORT must be an integer');returnport;}}});
Utility for defining environment variables,
which are made available via $app/env/public and $app/env/private.
import{defineEnvVars}from'@sveltejs/kit/env';import*asvfrom'valibot';exportconstvariables=defineEnvVars({API_URL:{schema:v.pipe(v.string(),v.url())},PORT:{schema:(value)=>{if(value===undefined)return3000;constport=Number(value);if(!Number.isInteger(port))thrownewError('PORT must be an integer');returnport;}}});
({CACHE_TTL_SECONDS(property)CACHE_TTL_SECONDS:{description:string;}:{description(property)description:string:'Combien de temps cacher les réponses, en secondes'}});
Survoler CACHE_TTL_SECONDS dans le code de votre application affichera alors la description.