Environment variables
Environment variables are values your app needs that exist separately from the app's source code. They allow you to use sensitive information like API keys and database credentials without storing them in version control.
During development, and at build time, variables defined in a .env or .env.local file will be added to the environment:
API_KEY=19f401ba-e8b0-48c4-8c77-b0ebb26d97feBy default, every environment variable is implicitly available inside your app via the following modules:
Explicit environment variables
As of SvelteKit 2.62, you can opt into explicit environment variables, in which case you instead import environment variables from these modules:
Additionally, the $app/environment module is renamed to $app/env.
Explicit environment variables will become the default in SvelteKit 3. The
$env/*modules, along with$app/environment, will be removed.
Setup
To opt in, update your configuration...
export default {
kit: {
experimental: {
explicitEnvironmentVariables: boolean;
};
}
kit: {
experimental: {
explicitEnvironmentVariables: boolean;
}
experimental: {
explicitEnvironmentVariables: booleanexplicitEnvironmentVariables: true
}
}
};...and add a src/env.ts (or src/env.js) file that exports a variables object:
import { function defineEnvVars<T extends Record<string, EnvVarConfig<any>>>(variables: T): TUtility 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({
// ...
});Each value in the object passed to defineEnvVars is an EnvVarConfig object that configures the environment variable.
defineEnvVarsreturns its argument unaltered — it exists purely to help with type safety.
Private variables
By default, all variables are considered private. For example, you don't want to reveal your API_KEY:
import { function defineEnvVars<T extends Record<string, EnvVarConfig<any>>>(variables: T): TUtility 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: {}
});Since no configuration is needed for this variable, we can use an empty object (
{}).
Now that API_KEY is defined, it can be imported into app code via $app/env/private:
import { import API_KEYAPI_KEY } from '$app/env/private';The $app/env/private module cannot be imported into code that runs in the browser, so that you can't accidentally reveal your secrets in a JavaScript bundle.
Public variables
Some variables are perfectly safe — necessary, even — to expose to the browser. For these, we can specify public: true:
import { function defineEnvVars<T extends Record<string, EnvVarConfig<any>>>(variables: T): TUtility 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 can now be imported from $app/env/public, or used in your app.html template as %sveltekit.env.GOOGLE_ANALYTICS_ID%:
<!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
You can specify a Standard Schema validator such as Zod or Valibot to check that an environment variable value is correct:
import { function defineEnvVars<T extends Record<string, EnvVarConfig<any>>>(variables: T): TUtility 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;
validate: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.RegexAction<string, undefined>]>;
};
}
variables = defineEnvVars<{
GOOGLE_ANALYTICS_ID: {
public: true;
validate: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.RegexAction<string, undefined>]>;
};
}>(variables: {
GOOGLE_ANALYTICS_ID: {
public: true;
validate: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.RegexAction<string, undefined>]>;
};
}): {
GOOGLE_ANALYTICS_ID: {
public: true;
validate: 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;
validate: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.RegexAction<string, undefined>]>;
}
GOOGLE_ANALYTICS_ID: {
public: truepublic: true,
validate: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.RegexAction<string, undefined>]>validate: 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 pipeAdds a pipeline to a schema, that can validate and transform its input.
import vv.function string(): v.StringSchema<undefined> (+1 overload)
export stringCreates a string schema.
import vv.regex<string>(requirement: RegExp): v.RegexAction<string, undefined> (+1 overload)
export regexregex(/G-[A-Z0-9]+/))
}
});If a value is invalid, the app will fail to start (or build).
You can use validators to make values optional, or transform them (such as turning a string into a boolean, or parsing JSON) — see your validation library's documentation to learn how.
Static variables
If a variable is configured with static: true, it will be inlined into your application code, enabling optimisations like dead-code elimination:
import { function defineEnvVars<T extends Record<string, EnvVarConfig<any>>>(variables: T): TUtility 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;
validate: v.SchemaWithPipe<readonly [v.OptionalSchema<v.StringSchema<undefined>, "">, v.TransformAction<string, boolean>]>;
};
}
variables = defineEnvVars<{
SHOW_DEBUG_OVERLAY: {
public: true;
static: true;
validate: v.SchemaWithPipe<readonly [v.OptionalSchema<v.StringSchema<undefined>, "">, v.TransformAction<string, boolean>]>;
};
}>(variables: {
SHOW_DEBUG_OVERLAY: {
public: true;
static: true;
validate: v.SchemaWithPipe<readonly [v.OptionalSchema<v.StringSchema<undefined>, "">, v.TransformAction<string, boolean>]>;
};
}): {
SHOW_DEBUG_OVERLAY: {
public: true;
static: true;
validate: 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;
validate: v.SchemaWithPipe<readonly [v.OptionalSchema<v.StringSchema<undefined>, "">, v.TransformAction<string, boolean>]>;
}
SHOW_DEBUG_OVERLAY: {
public: truepublic: true,
static: truestatic: true,
// coerce to true/false
validate: v.SchemaWithPipe<readonly [v.OptionalSchema<v.StringSchema<undefined>, "">, v.TransformAction<string, boolean>]>validate: 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.
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.
optional(import vv.function string(): v.StringSchema<undefined> (+1 overload)
export string
Creates a string schema.
string(), ''),
import vv.transform<string, boolean>(operation: (input: string) => boolean): v.TransformAction<string, boolean>
export transform
Creates a custom transformation action.
transform((str: stringstr) => str: stringstr !== '')
)
}
});Because this variable is static, the <DebugOverlay> component shown here will be excluded from the JavaScript bundle unless SHOW_DEBUG_OVERLAY is truthy:
<script>
import { SHOW_DEBUG_OVERLAY } from '$app/env/public';
import DebugOverlay from '$lib/components/DebugOverlay.svelte';
</script>
{#if SHOW_DEBUG_OVERLAY}
<DebugOverlay />
{/if}But if the variable is set before building the app...
SHOW_DEBUG_OVERLAY=true npm run build...then the component will be included and shown.
Documenting variables
You can document the purpose of an environment variable by adding a description:
import { function defineEnvVars<T extends Record<string, EnvVarConfig<any>>>(variables: T): TUtility 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: 'How long to cache responses, in seconds'
}
});Hovering over CACHE_TTL_SECONDS in your app code will show the description.
Edit this page on GitHub llms.txt