Svelte 71 🧡 Environment Variables Management ($env/static/public, $env/dynamic/private)
Managing configuration across environments—development, staging, and production—is a core requirement for any robust web application. SvelteKit provides a sophisticated and secure approach to this through its $env module system. Unlike standard Node.js process.env which exposes everything globally, SvelteKit requires explicit imports, ensuring that sensitive server-side secrets never accidentally leak to the client-side browser bundle.
The system is categorized into four distinct modules based on two axes: “Static vs. Dynamic” (build-time vs. runtime availability) and “Public vs. Private” (exposed to browser vs. server-only). This granular control allows developers to bake environment-specific settings into their code at build time for performance or fetch them dynamically for flexibility, all while maintaining a strict security boundary.
Key point: The $env module system mandates a clear security separation: variables imported from private modules are locked to the server, while those from public modules are safely bundled for the browser, preventing the accidental exposure of API keys and database credentials.
Why exists
The security boundary problem. Modern web apps require database passwords and API tokens that must remain on the server. $env imports force you to decide the visibility of a variable at the import level, making it architecturally difficult to leak a secret.
The build-time vs. runtime trade-off. Some configurations, like public API base URLs, are known at build time and can be inlined for performance. Others, like server-specific hostnames, might change depending on the runtime container. Static and dynamic imports cover both use cases.
The global scope pollution problem. Accessing process.env globally leads to code that is hard to test and debug because variables can be mutated or accessed anywhere. Explicit imports make dependencies visible and traceable.
The type-safety requirement. SvelteKit generates type definitions for your environment variables based on your .env files. This means your code won’t compile if you try to access a variable that isn’t defined, catching configuration bugs before you even deploy.
The cross-platform compatibility problem. process.env is a Node.js specific global. By using $env, SvelteKit abstracts the environment, allowing your code to run seamlessly across different server environments or edge runtimes without relying on Node-specific globals.
a. Static vs. Dynamic variables
Static environment variables are imported from $env/static/public or $env/static/private. These values are replaced during the build process; if the variable is not set at build time, it will be undefined or an empty string. This is ideal for fixed configuration like API endpoints.
import { PUBLIC_API_URL } from '$env/static/public';
// This value is baked into the code at build time.
console.log(PUBLIC_API_URL);
Dynamic variables are imported from $env/dynamic/public or $env/dynamic/private. These are resolved at runtime, meaning they can be updated without rebuilding your application. This is useful for variables that change depending on the deployment environment, like specific cluster hostnames.
b. Private vs. Public variables
Private variables are accessed via $env/static/private or $env/dynamic/private. These are only available on the server. If you attempt to import these in a file that runs in the browser, the build will fail, enforcing a physical layer of security that prevents client-side secrets.
// Only available on the server
import { SECRET_DB_PASSWORD } from '$env/static/private';
Public variables are accessed via $env/static/public or $env/dynamic/public. These variables must be prefixed with PUBLIC_ to be eligible for import. This naming convention acts as a visual and programmatic signal that these values are safe to be included in the browser bundle and accessible by any user visiting your site.
c. The import ecosystem
SvelteKit provides four primary entry points. Understanding these combinations is the key to mastering the environment configuration system.
// Build-time, only on server
import { DB_URL } from '$env/static/private';
// Build-time, available to browser
import { PUBLIC_CDN_URL } from '$env/static/public';
// Runtime, only on server
import { env } from '$env/dynamic/private';
const { API_KEY } = env;
// Runtime, available to browser
import { env as publicEnv } from '$env/dynamic/public';
const { PUBLIC_THEME } = publicEnv;
For dynamic imports, you access them from an env object rather than direct exports. This is because the values are not known until the application is executing on the server or in the browser, making the object property lookup necessary.
Complete Example Session
// ============================================
// PART 1: PRIVATE STATIC CONFIG (SERVER)
// ============================================
import { DATABASE_URL } from '$env/static/private';
// Used in +page.server.js to connect to the DB
// ============================================
// PART 2: PUBLIC STATIC CONFIG (BROWSER)
// ============================================
import { PUBLIC_BASE_URL } from '$env/static/public';
// Used in components for navigation or image paths
// ============================================
// PART 3: DYNAMIC PRIVATE CONFIG (RUNTIME)
// ============================================
import { env } from '$env/dynamic/private';
const secret = env.STRIPE_SECRET_KEY;
// Read at runtime to pick up current container env
// ============================================
// PART 4: DYNAMIC PUBLIC CONFIG (RUNTIME)
// ============================================
import { env as publicEnv } from '$env/dynamic/public';
const featureFlag = publicEnv.PUBLIC_ENABLE_BETA;
// Switch features based on runtime environment variables
This sequence covers the full range: static server-only secrets, static public configuration, runtime server secrets, and runtime browser flags.
Quick Reference
The Matrix of Environment Imports
| Type | Static (Build-time) | Dynamic (Runtime) |
|---|---|---|
| Private (Server Only) | $env/static/private | $env/dynamic/private |
| Public (Browser Safe) | $env/static/public | $env/dynamic/public |
Access Patterns
| Mode | Import Syntax | Usage |
|---|---|---|
| Static | import { VAR } from ... | Direct import variable |
| Dynamic | import { env } from ... | env.VAR |
Best Practices
✅ Do This:
// Always prefix public variables with PUBLIC_
// Example: PUBLIC_STRIPE_KEY // ✅
// Keep secrets in .env and access via private
import { SECRET_KEY } from '$env/static/private'; // ✅
// Use static variables for build-time constants
import { PUBLIC_CDN } from '$env/static/public'; // ✅
❌ Don’t Do This:
// Don't import private secrets in client-side code
import { SECRET_DB_PASS } from '$env/static/private'; // ❌
// Don't use process.env directly
const key = process.env.API_KEY; // ❌
// Don't forget to prefix public variables
import { API_KEY } from '$env/static/public'; // ❌
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Leakage | Importing private in client-side | Move logic to server-only |
| Build error | Variable not defined at build-time | Use dynamic for runtime vars |
| Typos | Variable name mismatch | Check your .env vs import name |
| Prefix error | Public var lacks PUBLIC_ | Rename key in .env |
Real-World Examples
1. Database URL
import { DATABASE_URL } from '$env/static/private';
2. Public API Base
import { PUBLIC_API_URL } from '$env/static/public';
3. Runtime Secret
import { env } from '$env/dynamic/private';
const key = env.API_KEY;
4. Runtime Feature Flag
import { env } from '$env/dynamic/public';
const beta = env.PUBLIC_BETA_MODE === 'true';
5. Analytics ID
import { PUBLIC_GA_ID } from '$env/static/public';
6. Stripe Key
import { STRIPE_SECRET } from '$env/static/private';
7. Build Version
import { PUBLIC_BUILD_ID } from '$env/static/public';
8. Cluster ID
import { env } from '$env/dynamic/private';
const cluster = env.CLUSTER_ID;
9. Logging Level
import { env } from '$env/dynamic/private';
const log = env.LOG_LEVEL;
10. CDN Asset Base
import { PUBLIC_ASSETS_URL } from '$env/static/public';
Visual
The Security Matrix
┌─────────────────────────────────────────────────────────┐
│ │ STATIC (Build) │ DYNAMIC (Runtime) │
│ ───────────── ┼ ───────────────── ┼ ─────────────────── │
│ PRIVATE │ Server-Only │ Server-Only │
│ │ (High Security) │ (High Security) │
│ ───────────── ┼ ───────────────── ┼ ─────────────────── │
│ PUBLIC │ Browser-Safe │ Browser-Safe │
│ │ (Public Bundled) │ (Safe to Client) │
└─────────────────────────────────────────────────────────┘
The Build-time Static Flow
┌─────────────────────────────────────────────────────────┐
│ .env File │
│ │ │
│ ▼ │
│ Build-time (SvelteKit) ──► Replaces variables │
│ │ │
│ ▼ │
│ Bundled JavaScript (Code has hardcoded strings) │
└─────────────────────────────────────────────────────────┘
The Runtime Dynamic Flow
┌─────────────────────────────────────────────────────────┐
│ Environment Variables (OS level) │
│ │ │
│ ▼ │
│ $env/dynamic/* ──► Look up at runtime │
│ │ │
│ ▼ │
│ Code Execution (Uses live value) │
└─────────────────────────────────────────────────────────┘
Summary
| Item | Value |
|---|---|
| Private storage | $env/static/private |
| Public storage | $env/static/public |
| Runtime check | $env/dynamic/* |
| Security requirement | PUBLIC_ prefix for public vars |
| Type safety | Automatic via SvelteKit |
Key takeaways:
- Import locations matter. Where you import the variable dictates where it can be used, creating a hard physical barrier against secret leakage.
- Static vs. Dynamic. Use
staticfor performance and constants; usedynamicwhen values can change or are injected at runtime by your hosting provider. - Always prefix public.
PUBLIC_is a mandatory contract for any variable that needs to reach the browser bundle. - Rely on types. SvelteKit generates the environment types automatically—let your editor help you by highlighting missing or misconfigured variables.
- Avoid global process.env. Standardize all environment access through the
$envmodule system for consistent, traceable configuration.
Remember: The $env system is one of SvelteKit’s most important security features. By requiring you to explicitly opt-in to where and when an environment variable is used, it prevents entire classes of common web security vulnerabilities. Keep your secrets strictly in private modules, ensure your public variables are prefixed, and let the system handle the complexity of environmental configuration.
Stop using slow, ad-bloated tool sites! 🤮
🔎 Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)
⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free
🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!