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: ```env /// file: .env.local API_KEY=19f401ba-e8b0-48c4-8c77-b0ebb26d97fe ``` After following the setup below, they can be imported via the following modules: - [`$app/env/private`]($app-env-private) - [`$app/env/public`]($app-env-public) > [!LEGACY] > The `$env/*` modules, along with `$app/environment` were removed in SvelteKit 3 in favour of explicit environment variables that were added in SvelteKit 2.62 as an experimental option. ### Setup Add a `src/env.ts` (or `src/env.js`) file that exports a `variables` object: ```ts /// file: src/env.ts import { defineEnvVars } from '@sveltejs/kit/hooks'; export const variables = defineEnvVars({ // ... }); ``` Each value in the object passed to [`defineEnvVars`](@sveltejs-kit-hooks#defineEnvVars) is an [`EnvVarConfig`](@sveltejs-kit#EnvVarConfig) object that configures the environment variable. > [!NOTE] `defineEnvVars` returns 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`: ```ts /// file: src/env.ts import { defineEnvVars } from '@sveltejs/kit/hooks'; export const variables = defineEnvVars({ +++API_KEY: {}+++ }); ``` > [!NOTE] 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`: ```js import { API_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`: ```ts /// file: src/env.ts import { defineEnvVars } from '@sveltejs/kit/hooks'; export const variables = defineEnvVars({ GOOGLE_ANALYTICS_ID: { +++public: 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%`: ```html
%sveltekit.head%