Using Environment Variables
Access environment variables throughimport.meta.env:
src/pages/index.astro
.env Files
Store environment variables in.env files in your project root:
.env
Add
.env files to .gitignore to avoid committing secrets to version control..env File Priority
Astro loads environment variables from multiple files in this order (highest priority first):1
.env.production.local
Production environment, local overrides (gitignored)
2
.env.production
Production environment
3
.env.local
All environments, local overrides (gitignored)
4
.env
All environments
Public vs Private Variables
- Public Variables
- Private Variables
Variables prefixed with Accessible in any file:
PUBLIC_ are available everywhere:.env
src/components/Analytics.astro
Type Safety
Type your environment variables for better IntelliSense and type checking:src/env.d.ts
- Autocomplete environment variable names
- Show type errors for missing variables
- Catch typos at compile time
Astro Environment Schema
For advanced type safety and validation, use Astro’s environment schema:astro.config.mjs
Field Types
String
String
Number
Number
Boolean
Boolean
Enum
Enum
Access Levels
'client' | 'server'
required
Where the variable can be accessed
'public' | 'secret'
required
Whether the variable is public or contains secrets
Secret client variables are not allowed for security reasons. Secrets must be server-only.
Runtime Access
Access validated environment variables at runtime:Default Values
Provide fallback values for optional variables:src/components/Config.astro
astro.config.mjs
Common Patterns
- API Configuration
- Database Connection
- Feature Flags
.env
src/lib/api.ts
Loading .env in Scripts
Load environment variables in Node.js scripts:scripts/seed-db.ts
Platform-Specific Variables
Many hosting platforms provide their own environment variables:Built-in Variables
Astro provides several built-in variables:'development' | 'production'
Current mode (
astro dev vs astro build)boolean
Whether running in production
boolean
Whether running in development
string
The
site URL from your configstring
The
base path from your configSecurity Best Practices
1
Never commit secrets
Add
.env and .env.local to .gitignore:.gitignore
2
Use PUBLIC_ carefully
Only use
PUBLIC_ for values safe to expose:- ✅ API endpoints
- ✅ Public IDs
- ❌ API keys
- ❌ Passwords
- ❌ Secrets
3
Provide example file
Create
.env.example with dummy values:.env.example
4
Validate on startup
Check required variables exist:
src/lib/env.ts
Related Resources
Configuration
Astro configuration options
TypeScript
TypeScript setup and types
Deployment
Deploy your Astro site
SSR
Server-side rendering