0
0
Svelteframework~3 mins

Why Environment variables ($env) in Svelte? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

Discover how to keep your app's secrets safe and switch settings without breaking a sweat!

The Scenario

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.

The Problem

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.

The Solution

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.

Before vs After
Before
const apiUrl = 'http://localhost:3000/api'; // change manually for production
After
import { env } from '$env/dynamic/public';
const apiUrl = env.PUBLIC_API_URL;
What It Enables

You can build apps that adapt automatically to different environments, keeping secrets safe and code clean.

Real Life Example

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.

Key Takeaways

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.