今日已更新 218 条资讯 | 累计 31896 条内容
关于我们

Environment Variables the Safe Way

Binary Journal 2026年08月15日 08:02 0 次阅读 来源:Dev.to

Why Environment Variables Matter Every app has secrets: API keys, database URLs, admin passwords. Hardcoding them in source code is a one-way ticket to leaks. Even if your repo is private, you never know who forks it or what CI logs expose. Environment variables are the standard way to keep configuration out of code. But using them safely requires a few habits that go beyond just process.env . The Basics: Loading and Accessing In Node.js, you read env vars with process.env . But you should not access them raw everywhere. Create a central config module that validates and exposes them. // config.js const required = [ ' DB_URL ' , ' API_KEY ' , ' PORT ' ]; for ( const key of required ) { if ( ! process . env [ key ]) { throw new Error ( `Missing required env var: ${ key } ` ); } } module . exports = { dbUrl : process . env . DB_URL , apiKey : process . env . API_KEY , port : parseInt ( process . env . PORT , 10 ), }; Fail fast at startup. If a required variable is missing, crash immediately rather than failing later in a confusing way. Never Commit .env Files Tools like dotenv load variables from a .env file for local development. That file must stay out of version control. Add .env to your .gitignore immediately. Also add .env.local , .env.production , etc. if you use them. Instead of committing the actual values, commit a .env.example with placeholder or fake values. This documents what is needed without exposing anything. # .env.example DB_URL = postgres :// user : password @ localhost : 5432 / mydb API_KEY = your - api - key - here PORT = 3000 Use a Validation Library Manual checks are fine for small projects, but for anything serious use a schema validator like envalid or joi . They give you type coercion, defaults, and clear error messages. // with envalid const { cleanEnv , str , num } = require ( ' envalid ' ); const env = cleanEnv ( process . env , { DB_URL : str (), API_KEY : str (), PORT : num ({ default : 3000 }), }); module . exports = env ; This catches m

本文内容来源于互联网,版权归原作者所有
查看原文