Back to Blog
Node.jsEnvironmentConfigurationSecurity

Node.js Environment Variables

Master environment variables in Node.js. From basics to dotenv to production best practices.

B
Bootspring Team
Engineering
September 30, 2020
6 min read

Environment variables configure applications across environments. Here's how to use them effectively.

Basic Usage#

Loading code block...

Using dotenv#

Loading code block...

Configuration Module#

Loading code block...

TypeScript Configuration#

Loading code block...

Environment-Specific Files#

# File structure project/ ├── .env # Default/development ├── .env.local # Local overrides (gitignored) ├── .env.development # Development specific ├── .env.production # Production specific ├── .env.test # Test specific └── .env.example # Template (committed)
Loading code block...

Secrets Management#

Loading code block...

Docker Configuration#

Loading code block...
Loading code block...

Testing with Environment Variables#

Loading code block...

Validation and Defaults#

Loading code block...

Best Practices#

Security: ✓ Never commit .env files ✓ Use .env.example as template ✓ Rotate secrets regularly ✓ Use secret managers in production Organization: ✓ Group related variables ✓ Use consistent naming (UPPER_SNAKE_CASE) ✓ Document all variables ✓ Provide sensible defaults Validation: ✓ Validate on startup ✓ Fail fast on missing required vars ✓ Type-check values ✓ Use schema validation (zod) Development: ✓ Use dotenv for local dev ✓ Keep .env.example updated ✓ Test configuration loading ✓ Mock env vars in tests

Conclusion#

Environment variables are essential for configuration management. Use dotenv for local development, validate configuration on startup, and never commit secrets. Implement a robust configuration module with type safety and validation for production applications.

Share this article

Help spread the word about Bootspring

Related articles