$env/static/public module provides access to public environment variables that are replaced at build time and can be accessed on both the client and server. These variables must be prefixed with PUBLIC_ by default.
Usage
This module can be imported anywhere - in both client-side and server-side code.
Static Replacement
Static public variables are replaced at build time. For example:Example: Component
Example: API Client
Example: Configuration
Example: Feature Flags
Configuration
Configure the public prefix in yoursvelte.config.js:
PUBLIC_ will be available and exposed to browsers.
Setting Public Environment Variables
Create a.env file in your project root:
When to Use Static vs Dynamic
Use Static
- Build-time constants that don’t change
- Better performance (inlined at build time)
- Type-safe access with TypeScript
- Enables dead code elimination
Use Dynamic
- Values that change between deployments
- Different values per environment
- Runtime configuration
- A/B testing configurations
TypeScript Support
SvelteKit automatically generates types for your static public environment variables:.svelte-kit/ambient.d.ts based on your .env file.
Performance Benefits
Static public variables offer several advantages:- Zero runtime overhead - Values are inlined during build
- Better tree-shaking - Unused imports can be eliminated
- Smaller bundles - No need to ship environment variable runtime
- Faster execution - No object property lookup
Build-Time Substitution
During build, SvelteKit:- Reads all
PUBLIC_*environment variables - Generates TypeScript types
- Replaces imports with actual string values
- Optimizes the code (tree-shaking, minification)
Security Warning
Common Use Cases
- API endpoints -
PUBLIC_API_URL - Analytics IDs -
PUBLIC_ANALYTICS_ID - Feature flags -
PUBLIC_ENABLE_FEATURE_X - Site metadata -
PUBLIC_SITE_NAME,PUBLIC_SITE_URL - CDN URLs -
PUBLIC_CDN_URL - Map API keys -
PUBLIC_MAPBOX_KEY(public keys only!)
See Also
- $env/dynamic/public - Dynamic public environment variables
- $env/static/private - Static server-only environment variables
- Configuration - Environment variable configuration options