0
0
Svelteframework~15 mins

Environment variables ($env) in Svelte - Deep Dive

Choose your learning style9 modes available
Overview - Environment variables ($env)
What is it?
Environment variables in Svelte are special values that store configuration data outside your code. They help your app know things like API keys or URLs without hardcoding them. SvelteKit uses the $env module to access these variables safely during build or runtime. This keeps sensitive info secure and makes your app flexible across different setups.
Why it matters
Without environment variables, you'd have to write secret keys or settings directly in your code. This is risky because anyone can see them, and changing settings means editing code and redeploying. Environment variables let you change important data without touching code, making apps safer and easier to manage in different places like development, testing, or production.
Where it fits
Before learning environment variables, you should understand basic Svelte app structure and how to run Svelte projects. After this, you can learn about deployment and configuration management to see how environment variables help apps adapt to different servers or cloud platforms.
Mental Model
Core Idea
Environment variables are secret notes your app reads to know how to behave without changing its code.
Think of it like...
Imagine your app is a chef who follows a recipe, but the recipe has blank spaces for secret ingredients written on sticky notes. These notes are environment variables that tell the chef what special spices to add depending on the kitchen.
┌─────────────────────────────┐
│       Your Svelte App       │
│  ┌───────────────────────┐ │
│  │  $env Module Reads     │ │
│  │  Environment Variables │ │
│  └──────────┬────────────┘ │
│             │              │
│   ┌─────────▼─────────┐    │
│   │  Secret Configs   │    │
│   │  (API keys, URLs) │    │
│   └───────────────────┘    │
└─────────────────────────────┘
Build-Up - 6 Steps
1
FoundationWhat are Environment Variables
🤔
Concept: Introduce what environment variables are and why they exist.
Environment variables are values stored outside your program that hold configuration data. They can be things like API keys, URLs, or flags that tell your app how to run. Instead of writing these values directly in your code, you keep them separate so you can change them easily without touching the code.
Result
You understand that environment variables are like external settings your app reads to behave differently in different situations.
Knowing that environment variables separate configuration from code helps you build safer and more flexible apps.
2
FoundationAccessing Environment Variables in Svelte
🤔
Concept: Learn how SvelteKit provides access to environment variables using the $env module.
SvelteKit offers special modules named $env/static/private and $env/static/public to access environment variables at build time. Variables starting with VITE_ or PUBLIC_ are public and can be exposed to the browser, while others remain private to the server. You import these modules to read your variables safely.
Result
You can write code like `import { VITE_API_URL } from '$env/static/public';` to get your API URL inside your Svelte app.
Understanding the difference between public and private environment variables prevents accidental exposure of secrets.
3
IntermediateStatic vs Dynamic Environment Variables
🤔Before reading on: do you think environment variables can change while the app runs, or are they fixed once the app starts? Commit to your answer.
Concept: Distinguish between static variables available at build time and dynamic variables available at runtime.
Static environment variables are embedded into your app during build. They cannot change without rebuilding. Dynamic environment variables are read when the app runs, allowing changes without rebuilding. SvelteKit supports both via $env/static and $env/dynamic modules.
Result
You know when to use static variables for fixed config and dynamic variables for runtime flexibility.
Knowing this difference helps you choose the right approach for your app's needs and avoid bugs caused by stale config.
4
IntermediateNaming Conventions and Security
🤔Before reading on: do you think all environment variables are safe to expose to the browser? Commit to yes or no.
Concept: Learn how naming affects which variables are exposed to client-side code and why this matters.
In SvelteKit, environment variables starting with VITE_ or PUBLIC_ are exposed to the browser. Others remain private on the server. This naming rule helps protect secrets like API keys from leaking to users. Always prefix public variables correctly and never expose sensitive data.
Result
You avoid accidentally leaking secrets by following naming conventions.
Understanding naming rules is key to keeping your app secure and trustworthy.
5
AdvancedUsing Environment Variables in Different Environments
🤔Before reading on: do you think you need to change your code to use different environment variables for development and production? Commit to your answer.
Concept: Learn how to manage environment variables for multiple environments without changing code.
You create different .env files like .env.development and .env.production with different values. Your build tool or deployment system loads the right file automatically. Your code stays the same, but the app behaves differently depending on where it runs.
Result
You can switch between environments easily and safely.
Knowing this setup saves time and prevents mistakes when deploying your app.
6
ExpertInternal Handling and Build-Time Replacement
🤔Before reading on: do you think environment variables are read from the OS every time your app runs, or replaced during build? Commit to your answer.
Concept: Understand how SvelteKit replaces environment variables at build time for static variables.
SvelteKit replaces references to static environment variables with their actual values during the build process. This means the final code contains the values directly, not a lookup. Dynamic variables are read from process.env at runtime on the server. This design improves performance and security.
Result
You grasp why static variables are faster and safer but less flexible.
Understanding build-time replacement clarifies why changing static variables requires rebuilding your app.
Under the Hood
At build time, SvelteKit scans your code for imports from $env/static and replaces them with the actual environment variable values. This is done by the bundler plugin that injects the values directly into the compiled JavaScript. For dynamic variables, the app reads from process.env at runtime on the server side. Public variables are exposed to client code by embedding them in the bundle, while private ones remain only on the server.
Why designed this way?
This design balances security, performance, and flexibility. Embedding static variables at build time avoids runtime overhead and accidental leaks. Dynamic variables allow runtime configuration changes without rebuilding. The naming convention prevents secrets from leaking to the browser. Alternatives like reading all variables at runtime would slow apps and risk exposing secrets.
┌───────────────┐        ┌───────────────────────┐
│  Source Code  │        │  Environment Variables │
│  (imports)   │───────▶│  (OS or .env files)    │
└───────────────┘        └──────────┬────────────┘
                                   │
                      Build Time  ▼ Runtime
                    ┌───────────────┐
                    │ Bundler Plugin│
                    │ Replaces vars │
                    └───────┬───────┘
                            │
                    ┌───────▼────────┐
                    │ Compiled Code  │
                    │ with embedded  │
                    │ static vars    │
                    └───────────────┘
Myth Busters - 4 Common Misconceptions
Quick: do you think all environment variables are automatically safe to use in client-side code? Commit to yes or no.
Common Belief:All environment variables can be used anywhere in the app without risk.
Tap to reveal reality
Reality:Only variables explicitly marked as public (with VITE_ or PUBLIC_ prefix) are safe to expose to client-side code. Others remain private on the server.
Why it matters:Using private variables in client code leaks secrets to users, causing security breaches.
Quick: do you think changing an environment variable file always updates your running app immediately? Commit to yes or no.
Common Belief:Changing .env files instantly changes the app behavior without rebuilding or restarting.
Tap to reveal reality
Reality:Static environment variables are baked into the app at build time, so changes require rebuilding. Dynamic variables can update at runtime if the server reloads them.
Why it matters:Expecting instant changes without rebuilding leads to confusion and debugging headaches.
Quick: do you think environment variables are only for secrets like passwords? Commit to yes or no.
Common Belief:Environment variables are only for storing secret keys or passwords.
Tap to reveal reality
Reality:They also store non-secret configuration like API URLs, feature flags, or mode settings to make apps flexible.
Why it matters:Limiting environment variables to secrets misses their full power for app configuration.
Quick: do you think environment variables are read from the OS every time the app runs? Commit to yes or no.
Common Belief:The app reads environment variables from the operating system every time it runs.
Tap to reveal reality
Reality:Static environment variables are replaced during build, so the app does not read them from the OS at runtime.
Why it matters:Misunderstanding this can cause confusion about when changes take effect and how to debug.
Expert Zone
1
Static environment variables are replaced as literals in the code, so their values are visible in the final bundle, which means you must never include secrets as static public variables.
2
Dynamic environment variables are only available on the server side and cannot be accessed in client-side code, enforcing a strict security boundary.
3
The $env module imports are tree-shaken by the bundler, so unused environment variables do not bloat your final app size.
When NOT to use
Avoid using environment variables for user-specific or frequently changing data; use state management or databases instead. Also, do not store large data or complex objects in environment variables; they are meant for simple strings. For frontend-only apps without a backend, environment variables have limited use and you should rely on build-time config files.
Production Patterns
In production, teams use separate .env files or secret managers to inject environment variables securely. CI/CD pipelines load these variables during build and deployment. Apps use environment variables to toggle features, connect to different APIs, and keep secrets safe without code changes.
Connections
Configuration Management
Environment variables are a core technique within configuration management.
Understanding environment variables helps grasp how software adapts to different environments without code changes.
Secrets Management
Environment variables often store secrets, linking them to secure secrets management practices.
Knowing environment variables clarifies how secrets are injected safely into apps and why dedicated secret managers exist.
Operating System Environment
Environment variables originate from the OS environment concept.
Understanding OS environment variables helps explain how apps inherit configuration from their running system.
Common Pitfalls
#1Accidentally exposing secret keys to the browser.
Wrong approach:import { SECRET_API_KEY } from '$env/static/public'; console.log(SECRET_API_KEY); // This leaks secret to client
Correct approach:import { SECRET_API_KEY } from '$env/static/private'; // Use SECRET_API_KEY only on server side, never in client code
Root cause:Confusing public and private environment variable modules and ignoring naming conventions.
#2Expecting environment variable changes to reflect without rebuilding.
Wrong approach:// Change .env file // Run app without rebuilding console.log(import.meta.env.VITE_API_URL); // Still old value
Correct approach:// Change .env file // Rebuild app console.log(import.meta.env.VITE_API_URL); // Updated value
Root cause:Not understanding that static environment variables are replaced at build time.
#3Using environment variables for user input or dynamic data.
Wrong approach:process.env.USER_NAME = 'Alice'; // Trying to set env var at runtime
Correct approach:Use app state or database to store user data, not environment variables.
Root cause:Misunderstanding environment variables as runtime storage instead of configuration.
Key Takeaways
Environment variables let you keep configuration and secrets outside your code, making apps safer and easier to manage.
SvelteKit uses the $env module to access environment variables, separating public (client) and private (server) data by naming conventions.
Static environment variables are replaced during build, so changing them requires rebuilding your app.
Dynamic environment variables are read at runtime on the server, allowing flexible configuration without rebuilds.
Following naming and usage rules prevents accidental secret leaks and ensures your app behaves correctly across environments.