Bird
Raised Fist0
Svelteframework~15 mins

Environment variables ($env) in Svelte - Deep Dive

Choose your learning style10 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.

Practice

(1/5)
1. What is the main reason to use environment variables in a Svelte project?
easy
A. To avoid using any external libraries
B. To write all code inside a single file
C. To make the app run faster by skipping variables
D. To store settings outside the code for safety and flexibility

Solution

  1. Step 1: Understand environment variables purpose

    Environment variables keep sensitive or changeable settings outside the main code, so you can change them without editing code.
  2. Step 2: Connect to safety and flexibility

    This separation helps keep secrets safe and lets you adjust settings easily for different environments like development or production.
  3. Final Answer:

    To store settings outside the code for safety and flexibility -> Option D
  4. Quick Check:

    Environment variables = safety and flexibility [OK]
Hint: Environment variables keep secrets outside code [OK]
Common Mistakes:
  • Thinking environment variables speed up the app
  • Believing environment variables are for code organization only
  • Confusing environment variables with libraries
2. Which import statement correctly accesses public environment variables in a Svelte component?
easy
A. import { PUBLIC_API_KEY } from '$env/static/public';
B. import { API_KEY } from '$env/static/private';
C. import { API_KEY } from '$env/dynamic/private';
D. import { PUBLIC_API_KEY } from '$env/dynamic/public';

Solution

  1. Step 1: Identify public environment variable import

    Public variables are accessed from '$env/static/public' when known at build time.
  2. Step 2: Match variable prefix and import path

    Public variables must start with 'PUBLIC_' and be imported from '$env/static/public' for static access.
  3. Final Answer:

    import { PUBLIC_API_KEY } from '$env/static/public'; -> Option A
  4. Quick Check:

    Public vars use static/public import [OK]
Hint: Public vars use $env/static/public import [OK]
Common Mistakes:
  • Using private import paths for public variables
  • Forgetting the PUBLIC_ prefix
  • Mixing dynamic and static imports incorrectly
3. Given this Svelte code snippet, what will be displayed if the environment variable PUBLIC_APP_NAME is set to 'MyApp'?
import { PUBLIC_APP_NAME } from '$env/static/public';

<h1>Welcome to {PUBLIC_APP_NAME}!</h1>
medium
A.

Welcome to MyApp!

B.

Welcome to PUBLIC_APP_NAME!

C.

Welcome to !

D. Error: Cannot find variable PUBLIC_APP_NAME

Solution

  1. Step 1: Understand import of PUBLIC_APP_NAME

    The variable PUBLIC_APP_NAME is imported from '$env/static/public', so its value is available at build time.
  2. Step 2: Check usage in template

    The variable is used inside the <h1> tag, so it will display the actual value 'MyApp'.
  3. Final Answer:

    <h1>Welcome to MyApp!</h1> -> Option A
  4. Quick Check:

    Static public env var shows actual value [OK]
Hint: Static public vars show real value in template [OK]
Common Mistakes:
  • Expecting variable name instead of value
  • Assuming variable is undefined without import
  • Confusing static and dynamic imports
4. You try to access a private environment variable in a Svelte component using this code:
import { SECRET_KEY } from '$env/static/private';

console.log(SECRET_KEY);
But you get an error during build. What is the likely cause?
medium
A. SECRET_KEY must start with PUBLIC_ prefix
B. You must import from '$env/dynamic/public' instead
C. Private variables cannot be imported in client-side code
D. You forgot to declare SECRET_KEY in .env file

Solution

  1. Step 1: Understand private env variable usage

    Private environment variables are only available on the server side and cannot be imported into client-side code.
  2. Step 2: Recognize build error cause

    Importing private variables in a component that runs in the browser causes build errors because secrets must stay server-only.
  3. Final Answer:

    Private variables cannot be imported in client-side code -> Option C
  4. Quick Check:

    Private vars are server-only [OK]
Hint: Private vars only on server, not client [OK]
Common Mistakes:
  • Adding PUBLIC_ prefix to private vars
  • Using dynamic public import for private vars
  • Assuming missing .env declaration causes build error
5. You want to show a greeting message in your Svelte app that changes based on a public environment variable PUBLIC_GREETING. You also want to update this message without rebuilding the app. Which approach should you use?
hard
A. Import PUBLIC_GREETING from $env/static/public and use it directly
B. Import PUBLIC_GREETING from $env/dynamic/public and use it in your component
C. Store PUBLIC_GREETING in a local variable inside the component
D. Hardcode the greeting message in the component

Solution

  1. Step 1: Understand static vs dynamic public env variables

    Static public variables are fixed at build time, so changes require rebuilding the app.
  2. Step 2: Use dynamic public env for runtime updates

    Dynamic public variables from '$env/dynamic/public' reflect environment changes without rebuilding, ideal for updating messages.
  3. Final Answer:

    Import PUBLIC_GREETING from $env/dynamic/public and use it in your component -> Option B
  4. Quick Check:

    Dynamic public env allows runtime updates [OK]
Hint: Use $env/dynamic/public for runtime env changes [OK]
Common Mistakes:
  • Using static public import for dynamic needs
  • Storing env vars in local variables without import
  • Hardcoding messages instead of using env vars
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard