पाठ 16 / 24

.env Files सही तरीक़े से

असली .env files ignore करें, `.env.example` commit करें और startup पर ज़रूरी variables जाँचें।

Example अंदर, secret बाहर

Variable के नाम और नक़ली मानों के साथ .env.example commit करें ताकि साथी जानें क्या सेट करना है। असली .env बनाने से पहले उसे .gitignore में डालें, क्योंकि पहले से commit हुई फ़ाइल को ignore करने से वह history से नहीं हटती।

Local, repo, CI, production

Secret कई जगहों से गुज़रता है। हर जगह के पास उसे पाने का सुरक्षित तरीक़ा होना चाहिए।

चार जगहें जहाँ से secret गुज़रता है।
चित्र 6.1 — Local machine, repository, CI और production।

Variable न हो तो तुरंत विफल हों

ऐप शुरू होते समय ज़रूरी variables जाँचें ताकि secret न होने पर बाद में अजीब errors की जगह तुरंत साफ़ failure मिले।

const required = ["DATABASE_URL", "STRIPE_KEY"];
for (const name of required) {
  if (!process.env[name]) {
    throw new Error(`Missing environment variable: ${name}`);
  }
}

पहले .gitignore देखें

पहले commit से पहले git status चलाएँ और पक्का करें कि .env सूची में नहीं है। कौन-सा नियम उसे ignore करता है यह git check-ignore -v .env से देखें।

त्वरित जाँच: Environment configuration के लिए क्या commit होना चाहिए?

  • असली मानों वाली .env
  • Placeholder मानों वाली .env.example
  • कभी कुछ नहीं, नाम भी नहीं
  • .env की zip
Answer

Placeholder मानों वाली .env.example — Example बिना असली secrets दिखाए बताता है कि क्या सेट करना है।