Discover how to keep your app's secrets safe and switch settings without breaking a sweat!
Why Environment variables ($env) in Svelte? - Purpose & Use Cases
Imagine you have to change your app's API address every time you move from your computer to a friend's or from development to production.
You open your code and replace the URL everywhere manually.
This manual way is risky and slow.
You might forget one place, causing bugs or crashes.
Also, sharing your code with secrets like API keys becomes unsafe.
Environment variables let you store settings outside your code.
Svelte's $env feature reads these safely and automatically.
This means you can switch environments without touching your code.
const apiUrl = 'http://localhost:3000/api'; // change manually for production
import { env } from '$env/dynamic/public'; const apiUrl = env.PUBLIC_API_URL;
You can build apps that adapt automatically to different environments, keeping secrets safe and code clean.
A weather app uses $env to get the API key and URL, so it works on your laptop and on the web server without changes.
Manual config changes are error-prone and unsafe.
$env provides a clean, secure way to manage environment settings.
This helps apps run smoothly across development, testing, and production.