Skip to main content

Variables d’environment

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éfinids dans un fichier .env ou .env.local seront ajoutées à l'environnement :

.env
API_KEY=19f401ba-e8b0-48c4-8c77-b0ebb26d97fe

Par défaut, chaque variable d'environnement est rendue implicitement disponible au sein de votre application via les modules suivants :

Variables d'environnement explicites

Depuis SvelteKit 2.63, vous pouvez activer les variables d'environnement explicites, ce qui vous permet plutôt d'importer vos variables d'environnement depuis ces modules :

Additionnellement, le module $app/environment est renommé en $app/env.

Les variables d'environnement explicites seront le comportement par défaut de SvelteKit 3. Les modules $env/*, ainsi que $app/environment, seront supprimés.

Mise en place

Pour activer les variables d'environnement explicites, mettez votre configuration à jour...

svelte.config
export default {
	
kit: {
    experimental: {
        explicitEnvironmentVariables: boolean;
    };
}
kit
: {
experimental: {
    explicitEnvironmentVariables: boolean;
}
experimental
: {
explicitEnvironmentVariables: booleanexplicitEnvironmentVariables: true } } };

... et ajoutez un fichier src/env.ts (ou src/env.js) exportant un objet variables :

src/env
import { function defineEnvVars<T extends Record<string, EnvVarConfig<any>>>(variables: T): T

Utility for defining environment variables, which are made available via $app/env/public and $app/env/private.

defineEnvVars
} from '@sveltejs/kit/hooks';
export const const variables: {}variables = defineEnvVars<{}>(variables: {}): {}

Utility for defining environment variables, which are made available via $app/env/public and $app/env/private.

defineEnvVars
({
// ... });

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 :

src/env
import { function defineEnvVars<T extends Record<string, EnvVarConfig<any>>>(variables: T): T

Utility for defining environment variables, which are made available via $app/env/public and $app/env/private.

defineEnvVars
} from '@sveltejs/kit/hooks';
export const
const variables: {
    API_KEY: {};
}
variables
=
defineEnvVars<{
    API_KEY: {};
}>(variables: {
    API_KEY: {};
}): {
    API_KEY: {};
}

Utility for defining environment variables, which are made available via $app/env/public and $app/env/private.

defineEnvVars
({
type API_KEY: {}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 :

import { import API_KEYAPI_KEY } from '$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 :

src/env
import { function defineEnvVars<T extends Record<string, EnvVarConfig<any>>>(variables: T): T

Utility for defining environment variables, which are made available via $app/env/public and $app/env/private.

defineEnvVars
} from '@sveltejs/kit/hooks';
export const
const variables: {
    GOOGLE_ANALYTICS_ID: {
        public: true;
    };
}
variables
=
defineEnvVars<{
    GOOGLE_ANALYTICS_ID: {
        public: true;
    };
}>(variables: {
    GOOGLE_ANALYTICS_ID: {
        public: true;
    };
}): {
    GOOGLE_ANALYTICS_ID: {
        public: true;
    };
}

Utility for defining environment variables, which are made available via $app/env/public and $app/env/private.

defineEnvVars
({
type GOOGLE_ANALYTICS_ID: {
    public: true;
}
GOOGLE_ANALYTICS_ID
: {
public: truepublic: true } });

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% :

src/app
<!doctype html>
<html lang="en">
	<head>
		<meta charset="utf-8" />
		<link rel="icon" href="%sveltekit.assets%/favicon.png" />
		<meta name="viewport" content="width=device-width, initial-scale=1" />
		%sveltekit.head%

		<script
			async
			src="https://www.googletagmanager.com/gtag/js?id=%sveltekit.env.GOOGLE_ANALYTICS_ID%"
		></script>

		<script>
			window.dataLayer ??= [];
			function gtag(){dataLayer.push(arguments)}
			gtag('js', new Date());
			gtag('config', '%sveltekit.env.GOOGLE_ANALYTICS_ID%');
		</script>
	</head>
	<body data-sveltekit-preload-data="hover">
		<div style="display: contents">%sveltekit.body%</div>
	</body>
</html>

Validation

Vous pouvez préciser un validateur de Standard Schema comme Zod ou Valibot pour vérifier que'une variable d'nvironnement est définie correctement :

src/env
import { function defineEnvVars<T extends Record<string, EnvVarConfig<any>>>(variables: T): T

Utility for defining environment variables, which are made available via $app/env/public and $app/env/private.

defineEnvVars
} from '@sveltejs/kit/hooks';
import * as import vv from 'valibot'; export const
const variables: {
    GOOGLE_ANALYTICS_ID: {
        public: true;
        schema: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.RegexAction<string, undefined>]>;
    };
}
variables
=
defineEnvVars<{
    GOOGLE_ANALYTICS_ID: {
        public: true;
        schema: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.RegexAction<string, undefined>]>;
    };
}>(variables: {
    GOOGLE_ANALYTICS_ID: {
        public: true;
        schema: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.RegexAction<string, undefined>]>;
    };
}): {
    GOOGLE_ANALYTICS_ID: {
        public: true;
        schema: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.RegexAction<string, undefined>]>;
    };
}

Utility for defining environment variables, which are made available via $app/env/public and $app/env/private.

defineEnvVars
({
type GOOGLE_ANALYTICS_ID: {
    public: true;
    schema: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.RegexAction<string, undefined>]>;
}
GOOGLE_ANALYTICS_ID
: {
public: truepublic: true, schema: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.RegexAction<string, undefined>]>schema: import vv.
pipe<v.StringSchema<undefined>, v.RegexAction<string, undefined>>(schema: v.StringSchema<undefined>, item1: v.RegexAction<string, undefined> | v.PipeAction<string, string, v.RegexIssue<string>>): v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.RegexAction<string, undefined>]> (+20 overloads)
export pipe

Adds a pipeline to a schema, that can validate and transform its input.

@param
schema The root schema.
@param
item1 The first pipe item.
@returns
A schema with a pipeline.
pipe
(import vv.
function string(): v.StringSchema<undefined> (+1 overload)
export string

Creates a string schema.

@returns
A string schema.
string
(), import vv.
regex<string>(requirement: RegExp): v.RegexAction<string, undefined> (+1 overload)
export regex

Creates a regex validation action.

Hint: Be careful with the global flag g in your regex pattern, as it can lead to unexpected results. See MDN for more information.

@param
requirement The regex pattern.
@returns
A regex action.
regex
(/G-[A-Z0-9]+/))
} });

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 :

src/env
import { function defineEnvVars<T extends Record<string, EnvVarConfig<any>>>(variables: T): T

Utility for defining environment variables, which are made available via $app/env/public and $app/env/private.

defineEnvVars
} from '@sveltejs/kit/hooks';
import { const building: boolean

SvelteKit analyses your app during the build step by running it. During this process, building is true. This also applies during prerendering.

building
} from '$app/env'
import * as import vv from 'valibot'; export const
const variables: {
    SECRET: {
        schema: v.StringSchema<undefined> | v.OptionalSchema<v.StringSchema<undefined>, undefined>;
    };
}
variables
=
defineEnvVars<{
    SECRET: {
        schema: v.StringSchema<undefined> | v.OptionalSchema<v.StringSchema<undefined>, undefined>;
    };
}>(variables: {
    SECRET: {
        schema: v.StringSchema<undefined> | v.OptionalSchema<v.StringSchema<undefined>, undefined>;
    };
}): {
    SECRET: {
        schema: v.StringSchema<undefined> | v.OptionalSchema<v.StringSchema<undefined>, undefined>;
    };
}

Utility for defining environment variables, which are made available via $app/env/public and $app/env/private.

defineEnvVars
({
type SECRET: {
    schema: v.StringSchema<undefined> | v.OptionalSchema<v.StringSchema<undefined>, undefined>;
}
SECRET
: {
// optionnel lors de la compilation, mais requis au démarrage de l'application schema: v.StringSchema<undefined> | v.OptionalSchema<v.StringSchema<undefined>, undefined>schema: const building: boolean

SvelteKit analyses your app during the build step by running it. During this process, building is true. This also applies during prerendering.

building
? import vv.
optional<v.StringSchema<undefined>>(wrapped: v.StringSchema<undefined>): v.OptionalSchema<v.StringSchema<undefined>, undefined> (+1 overload)
export optional

Creates an optional schema.

@param
wrapped The wrapped schema.
@returns
An optional schema.
optional
(import vv.
function string(): v.StringSchema<undefined> (+1 overload)
export string

Creates a string schema.

@returns
A string schema.
string
()) : import vv.
function string(): v.StringSchema<undefined> (+1 overload)
export string

Creates a string schema.

@returns
A string schema.
string
()
} });

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

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 :

src/env
import { function defineEnvVars<T extends Record<string, EnvVarConfig<any>>>(variables: T): T

Utility for defining environment variables, which are made available via $app/env/public and $app/env/private.

defineEnvVars
} from '@sveltejs/kit/hooks';
import * as import vv from 'valibot'; export const
const variables: {
    SHOW_DEBUG_OVERLAY: {
        public: true;
        static: true;
        schema: v.SchemaWithPipe<readonly [v.OptionalSchema<v.StringSchema<undefined>, "">, v.TransformAction<string, boolean>]>;
    };
}
variables
=
defineEnvVars<{
    SHOW_DEBUG_OVERLAY: {
        public: true;
        static: true;
        schema: v.SchemaWithPipe<readonly [v.OptionalSchema<v.StringSchema<undefined>, "">, v.TransformAction<string, boolean>]>;
    };
}>(variables: {
    SHOW_DEBUG_OVERLAY: {
        public: true;
        static: true;
        schema: v.SchemaWithPipe<readonly [v.OptionalSchema<v.StringSchema<undefined>, "">, v.TransformAction<string, boolean>]>;
    };
}): {
    SHOW_DEBUG_OVERLAY: {
        public: true;
        static: true;
        schema: v.SchemaWithPipe<readonly [v.OptionalSchema<v.StringSchema<undefined>, "">, v.TransformAction<string, boolean>]>;
    };
}

Utility for defining environment variables, which are made available via $app/env/public and $app/env/private.

defineEnvVars
({
type SHOW_DEBUG_OVERLAY: {
    public: true;
    static: true;
    schema: v.SchemaWithPipe<readonly [v.OptionalSchema<v.StringSchema<undefined>, "">, v.TransformAction<string, boolean>]>;
}
SHOW_DEBUG_OVERLAY
: {
public: truepublic: true, static: truestatic: true, // transforme la valeur en true/false schema: v.SchemaWithPipe<readonly [v.OptionalSchema<v.StringSchema<undefined>, "">, v.TransformAction<string, boolean>]>schema: import vv.
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>]> (+20 overloads)
export pipe

Adds a pipeline to a schema, that can validate and transform its input.

@param
schema The root schema.
@param
item1 The first pipe item.
@returns
A schema with a pipeline.
pipe
(
import vv.
optional<v.StringSchema<undefined>, "">(wrapped: v.StringSchema<undefined>, default_: ""): v.OptionalSchema<v.StringSchema<undefined>, ""> (+1 overload)
export optional

Creates an optional schema.

@param
wrapped The wrapped schema.
@param
default_ The default value.
@returns
An optional schema.
optional
(import vv.
function string(): v.StringSchema<undefined> (+1 overload)
export string

Creates a string schema.

@returns
A string schema.
string
(), ''),
import vv.
transform<string, boolean>(operation: (input: string) => boolean): v.TransformAction<string, boolean>
export transform

Creates a custom transformation action.

@param
operation The transformation operation.
@returns
A transform action.
transform
((str: stringstr) => str: stringstr !== '')
) } });

Puisque cette variable est static, le composant <DebugOverlay> utilisé ici sera exclus du bundle JavaScript à moins que SHOW_DEBUG_OVERLAY ne soit vrai :

<script>
	import { SHOW_DEBUG_OVERLAY } from '$app/env/public';
	import DebugOverlay from '$lib/components/DebugOverlay.svelte';
</script>

{#if SHOW_DEBUG_OVERLAY}
	<DebugOverlay />
{/if}

Mais si la variable est définie lors de la compilation de l'applicaation...

SHOW_DEBUG_OVERLAY=true npm run build

... alors le composant sera inclus et affiché.

Documenter les variables

Vous pouvez documenter le rôle d'une variable d'environnement en ajoutant une description :

src/env
import { function defineEnvVars<T extends Record<string, EnvVarConfig<any>>>(variables: T): T

Utility for defining environment variables, which are made available via $app/env/public and $app/env/private.

defineEnvVars
} from '@sveltejs/kit/hooks';
export const
const variables: {
    CACHE_TTL_SECONDS: {
        description: string;
    };
}
variables
=
defineEnvVars<{
    CACHE_TTL_SECONDS: {
        description: string;
    };
}>(variables: {
    CACHE_TTL_SECONDS: {
        description: string;
    };
}): {
    CACHE_TTL_SECONDS: {
        description: string;
    };
}

Utility for defining environment variables, which are made available via $app/env/public and $app/env/private.

defineEnvVars
({
type CACHE_TTL_SECONDS: {
    description: string;
}
CACHE_TTL_SECONDS
: {
description: stringdescription: 'Combien de temps cacher les réponses, en secondes' } });

Survoler CACHE_TTL_SECONDS dans le code de votre application affichera alors la description.

Modifier cette page sur Github llms.txt