Environment variables let you store important settings outside your code. This keeps secrets safe and makes your app flexible for different places.
0
0
Environment variables ($env) in Svelte
Introduction
You want to keep API keys hidden from public code.
You need different settings for development and production.
You want to change the app's behavior without changing code.
You want to share configuration safely across your team.
You want to avoid hardcoding URLs or passwords in your app.
Syntax
Svelte
import { env } from '$env/dynamic/public'; console.log(env.PUBLIC_API_URL);
Use $env/dynamic/public to access public environment variables in the browser.
Variables starting with PUBLIC_ are safe to expose to the client.
Examples
Access a public environment variable in a Svelte component or script.
Svelte
import { env } from '$env/dynamic/public'; console.log(env.PUBLIC_API_URL);
Access a private environment variable only on the server side.
Svelte
import { env } from '$env/static/private'; console.log(env.SECRET_KEY);
Access public environment variables statically for better performance.
Svelte
import { env } from '$env/static/public'; console.log(env.PUBLIC_BASE_URL);
Sample Program
This Svelte component shows how to display a public environment variable in the page.
Svelte
<script> import { env } from '$env/dynamic/public'; </script> <main> <h1>API URL:</h1> <p>{env.PUBLIC_API_URL}</p> </main>
OutputSuccess
Important Notes
Always prefix public environment variables with PUBLIC_ to expose them safely.
Private variables are only available on the server and never sent to the browser.
Use $env/static imports for better performance when variables don't change.
Summary
Environment variables store settings outside your code for safety and flexibility.
Use $env/dynamic/public to access public variables in the browser.
Prefix public variables with PUBLIC_ to share safely with client code.