How to load environment variables
Learn environment variables management in different environments and deployment scenarios.
Link to section: local-developmentLocal development
Link to section: using-env-filesUsing .env files
The most common way to manage environment variables during development is using .env files:
DATABASE_HOST=localhost
DATABASE_PORT=5432
NODE_ENV=development
API_KEY=your-secret-key
LOG_LEVEL=debugLink to section: best-practices-for-env-filesBest practices for .env files
-
Document required variables Create a
.env.examplefile to document required variables:.env.example DATABASE_HOST=localhost DATABASE_PORT=5432 NODE_ENV=development API_KEY=your-secret-key-here LOG_LEVEL=info -
Gitignore configuration Add these patterns to your
.gitignore:.gitignore .env .env.* !.env.example -
Environment-specific files Use different files for different environments:
.env.development- Development settings.env.test- Test environment settings.env.production- Production defaults (if needed)
Link to section: loading-environment-variablesLoading environment variables
Link to section: using-dotenvUsing dotenv
The simplest way to load environment variables is using the dotenv package:
import 'dotenv/config';
// or
import * as dotenv from 'dotenv';
dotenv.config();Link to section: framework-specific-solutionsFramework-specific solutions
Many frameworks have built-in support for environment variables:
Link to section: nextjsNext.js
- Automatically loads
.env*files - Supports environment-specific files (
.env.development,.env.production) - Next.js Environment Variables Documentation
Link to section: viteVite
- Automatically loads
.envfiles - Supports mode-specific files (
.env.development,.env.production) - Vite Env Variables Documentation
Link to section: expressExpress
import express from 'express';
import dotenv from 'dotenv';
dotenv.config();
const app = express();Link to section: nestjsNest.js
import { ConfigModule } from '@nestjs/config';
@Module({
imports: [
ConfigModule.forRoot({
isGlobal: true,
}),
],
})Link to section: runtime-argumentsRuntime arguments
You can also supply variables when running your application:
DATABASE_HOST=localhost DATABASE_PORT=5432 npm startLink to section: production-deploymentProduction deployment
Link to section: cloud-platformsCloud platforms
Link to section: awsAWS
- Use AWS Systems Manager Parameter Store for non-sensitive values
- Use AWS Secrets Manager for sensitive values
- Set environment variables in ECS Task Definitions or Lambda configurations
Link to section: google-cloud-platformGoogle Cloud Platform
- Use Cloud Secret Manager for sensitive values
- Set environment variables in Cloud Run or App Engine configurations
Link to section: azureAzure
- Use Azure Key Vault for sensitive values
- Configure App Settings in Azure App Service
Link to section: container-environmentsContainer environments
Link to section: dockerDocker
ENV NODE_ENV=productionservices:
app:
environment:
- NODE_ENV=production
- DATABASE_HOST=dbLink to section: kubernetesKubernetes
spec:
containers:
- name: app
env:
- name: NODE_ENV
value: "production"
- name: DATABASE_HOST
valueFrom:
configMapKeyRef:
name: app-config
key: database-hostLink to section: traditional-hostingTraditional hosting
- Set environment variables through the hosting platform's dashboard
- Use deployment scripts to configure environment variables
- Consider using configuration management tools
Link to section: security-best-practicesSecurity best practices
-
Never commit sensitive values
- Keep
.envfiles out of version control - Use secrets management services in production
- Keep
-
Use different values per environment
- Don't share sensitive credentials between environments
- Use environment-specific configurations
-
Access control
- Limit access to production environment variables
- Use role-based access control for secrets management
-
Encryption
- Encrypt sensitive values at rest
- Use secure channels for transmitting secrets
Link to section: validation-and-typesafetyValidation and typesafety
ArkEnv helps ensure your environment variables are valid:
import arkenv from 'arkenv';
export const env = arkenv({
// Required variables with validation
DATABASE_HOST: "string.host",
DATABASE_PORT: "number.port",
// Boolean values (accepts "true"/"false" strings, converts to boolean)
DEBUG: "boolean",
// Optional variables with defaults
LOG_LEVEL: "'debug' | 'info' | 'warn' | 'error' = 'info'",
// Optional variables
"FEATURE_FLAGS?": 'string[]'
});Link to section: common-patternsCommon patterns
Link to section: configuration-factoryConfiguration factory
Create a configuration factory to handle different environments:
import arkenv from 'arkenv';
const createConfig = () => {
const env = arkenv({
NODE_ENV: "'development' | 'test' | 'production'",
DATABASE_HOST: "string.host",
DATABASE_PORT: "number.port",
});
return {
isProduction: env.NODE_ENV === 'production',
database: {
host: env.DATABASE_HOST,
port: env.DATABASE_PORT,
}
};
};
export const config = createConfig();Link to section: feature-flagsFeature flags
Use environment variables for feature flags:
import arkenv from 'arkenv';
export const env = arkenv({
"ENABLE_BETA_FEATURES": 'boolean = false',
"MAINTENANCE_MODE": 'boolean = false',
"ALLOWED_ORIGINS": 'string[]'
});Link to section: troubleshootingTroubleshooting
Link to section: common-issuesCommon issues
-
Missing variables
- Check if
.envfile exists - Verify variable names match exactly
- Ensure variables are loaded before use
- Check if
-
Type errors
- Verify variable types match schema
- Check for typos in variable names
- Ensure all required variables are provided
-
Loading order
- Load environment variables before importing config
- Consider using a bootstrap file
- Check framework-specific loading behavior