$env/dynamic/public module provides access to public environment variables that can be accessed on both the client and server at runtime. These variables are prefixed with PUBLIC_ by default and are safe to expose to browsers.
Usage
This module can be imported anywhere - in both client-side and server-side code.
Environment Variable
An object containing all environment variables that match the
publicPrefix configuration (default: PUBLIC_).Public environment variables are safe to expose to client-side code and are embedded in the JavaScript sent to browsers.Example: Component
Example: Client Hook
Example: Server Load Function
Example: Prerendering
Configuration
You can configure the public prefix using theenv.publicPrefix option in your svelte.config.js:
PUBLIC_ will be available in $env/dynamic/public and exposed to browsers.
Setting Public Environment Variables
Create a.env file in your project root:
When to Use Dynamic vs Static
Use Dynamic
- Environment variables that change between deployments
- Different values for dev/staging/production
- Runtime configuration
- A/B testing configurations
Use Static
- Build-time constants
- Values that never change
- Better performance (inlined at build time)
- Type-safe access with TypeScript
Security Warning
Prerendering Behavior
Dynamic public environment variables are evaluated at runtime, including during prerendering:- Values are read from
process.envwhen the page is prerendered - The same values are embedded in the generated HTML
- Client-side JavaScript can still access these values via the
envobject
See Also
- $env/static/public - Static public environment variables
- $env/dynamic/private - Dynamic server-only environment variables
- Configuration - Environment variable configuration options