Skip to main content
Basic Svelte
Introduction
Reactivity
Props
Logic
Events
Bindings
Classes and styles
Attachments
Transitions
Advanced Svelte
Advanced reactivity
Reusing content
Motion
Advanced bindings
Advanced transitions
Context API
Special elements
<script module>
Next steps
Basic SvelteKit
Introduction
Routing
Loading data
Headers and cookies
Shared modules
Forms
API routes
$app/state
Errors and redirects
Advanced SvelteKit
Hooks
Page options
Link options
Advanced routing
Advanced loading
Environment variables
Conclusion

Some environment variables can safely be exposed to the browser. In this exercise, we’ll use two of them to control the page’s colour scheme.

Add values to the two environment variables in .env:

THEME_BACKGROUND="steelblue"
THEME_FOREGROUND="bisque"

Next, create src/env.js. Import defineEnvVars from @sveltejs/kit/env, and configure both variables with public: true:

src/env
import { defineEnvVars } from '@sveltejs/kit/env';

export const variables = defineEnvVars({
	THEME_BACKGROUND: {
		public: true
	},
	THEME_FOREGROUND: {
		public: true
	}
});

You can now import the variables into src/routes/+page.svelte from $app/env/public:

src/routes/+page
<script>
	const THEME_BACKGROUND = 'white';
	const THEME_FOREGROUND = 'black';
	import {
		THEME_BACKGROUND,
		THEME_FOREGROUND
	} from '$app/env/public';
</script>
<script lang="ts">
	const THEME_BACKGROUND = 'white';
	const THEME_FOREGROUND = 'black';
	import {
		THEME_BACKGROUND,
		THEME_FOREGROUND
	} from '$app/env/public';
</script>

Environment variables are dynamic by default, meaning their values are read when the app starts. If a variable is known when the app is built, you can add static: true to its configuration to inline its value into the bundle, enabling optimisations like dead-code elimination.

Prior to SvelteKit 3 you didn’t have the option to declare an env.js file - instead, you had to prefix your environment variables with PUBLIC_ to make them available via $env/dynamic/public and $env/static/public.

Edit this page on GitHub

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<script>
	const THEME_BACKGROUND = 'white';
	const THEME_FOREGROUND = 'black';
</script>
 
<main
	style:background={THEME_BACKGROUND}
	style:color={THEME_FOREGROUND}
>
	{THEME_FOREGROUND} on {THEME_BACKGROUND}
</main>
 
<style>
	main {
		position: fixed;
		display: flex;
		align-items: center;
		justify-content: center;
		left: 0;
		top: 0;
		width: 100%;
		height: 100%;
		font-size: 10vmin;
	}
</style>