Claude Code के साथ Implementing Environment Variable Management Best Practices
Claude Code का उपयोग करके implementing environment variable management best practices सीखें। Practical tips और code examples शामिल हैं।
environment variablesmanagementがimportantな理由
applicationdevelopmentでは、APIkeyやdatabase接続情報 आदिの機密情報をsafeにmanagementするज़रूरीがあり है।environment variablesはउस基本手段ですが、型safe性やvalidationが不足しがち है।Claude Code का उपयोग करके、robustなenvironment variablesmanagementの仕組みを素早くbuild किया जा सकता है。
型safeなenvironment variablesの読み込み
> environment variablesをzodでvalidationして型safeに読み込むmoduleを作って。
> 必須・任意の区別と、デフォルト値のsettingsもできる तरहして。
import { z } from 'zod';
const envSchema = z.object({
NODE_ENV: z.enum(['development', 'staging', 'production']).default('development'),
PORT: z.coerce.number().int().positive().default(3000),
DATABASE_URL: z.string().url(),
REDIS_URL: z.string().url().optional(),
API_KEY: z.string().min(1, 'API_KEYは必須です'),
JWT_SECRET: z.string().min(32, 'JWT_SECRETは32文字以ऊपरज़रूरीです'),
CORS_ORIGINS: z.string().transform((s) => s.split(',')).default('http://localhost:3000'),
LOG_LEVEL: z.enum(['debug', 'info', 'warn', 'error']).default('info'),
});
export type Env = z.infer<typeof envSchema>;
function loadEnv(): Env {
const result = envSchema.safeParse(process.env);
if (!result.success) {
const formatted = result.error.format();
console.error('environment variablesのvalidationerror:');
for (const [key, value] of Object.entries(formatted)) {
if (key !== '_errors' && value && '_errors' in value) {
console.error(` ${key}: ${(value as any)._errors.join(', ')}`);
}
}
process.exit(1);
}
return result.data;
}
export const env = loadEnv();
.envfileのtemplatemanagement
> .env.exampleを自動generateするスクリプトを作って。
> 実際の値は含めず、説明コメント付きで。
import fs from 'fs';
import path from 'path';
function generateEnvExample(envPath: string, outputPath: string) {
const envContent = fs.readFileSync(envPath, 'utf-8');
const lines = envContent.split('\n');
const exampleLines = lines.map((line) => {
if (line.startsWith('#') || line.trim() === '') return line;
const [key] = line.split('=');
const descriptions: Record<string, string> = {
DATABASE_URL: '# database接続URL (例: postgresql://user:pass@localhost:5432/db)',
API_KEY: '# APIkey (本番環境ではsafeにmanagementしてください)',
JWT_SECRET: '# JWT署名用シークレット (32文字以ऊपर)',
};
const comment = descriptions[key?.trim()] || '';
return `${comment}\n${key?.trim()}=`;
});
fs.writeFileSync(outputPath, exampleLines.join('\n'));
}
環境ごとのsettings切り替え
> 環境ごとに異なるsettingsをmanagementするConfigclassを作って。
> development, staging, productionの3環境にsupportして。
interface AppConfig {
database: { pool: number; ssl: boolean };
cache: { ttl: number; enabled: boolean };
logging: { level: string; format: string };
}
const configs: Record<string, AppConfig> = {
development: {
database: { pool: 5, ssl: false },
cache: { ttl: 60, enabled: false },
logging: { level: 'debug', format: 'pretty' },
},
production: {
database: { pool: 20, ssl: true },
cache: { ttl: 3600, enabled: true },
logging: { level: 'warn', format: 'json' },
},
};
export function getConfig(): AppConfig {
const nodeEnv = env.NODE_ENV;
return configs[nodeEnv] ?? configs.development;
}
シークレットのローテーションsupport
機密情報のローテーションをsafeにकरनाため、複数versionのシークレットを同時に保持する仕組みもbuild किया जा सकता है。
class SecretManager {
private secrets: Map<string, string[]> = new Map();
register(key: string, ...values: string[]) {
this.secrets.set(key, values.filter(Boolean));
}
getCurrent(key: string): string {
const values = this.secrets.get(key);
if (!values || values.length === 0) {
throw new Error(`Secret not found: ${key}`);
}
return values[0];
}
verify(key: string, token: string, verifyFn: (secret: string, token: string) => boolean): boolean {
const values = this.secrets.get(key) ?? [];
return values.some((secret) => verifyFn(secret, token));
}
}
const secrets = new SecretManager();
secrets.register('JWT_SECRET', env.JWT_SECRET, process.env.JWT_SECRET_PREVIOUS ?? '');
Summary
Claude Code का उपयोग करके、zodによる型safeなvalidation、環境別settings、シークレットmanagement तक、environment variablesmanagementの仕組みを一貫してbuild किया जा सकता है。securityの基本 के रूप मेंauthenticationimplementationガイドभी reference के लिए देखें。testのautomationके बारे मेंはtest戦略の記事में विस्तार सेबताया गया है。
zodके details के लिएZodofficial documentationदेखें。environment variablesmanagementのsecurityके बारे मेंはOWASP Configuration Guideभी reference के लिएなり है।
मुफ़्त PDF: 5 मिनट में Claude Code चीटशीट
बस अपना ईमेल दर्ज करें और हम तुरंत A4 एक-पृष्ठ चीटशीट PDF भेज देंगे।
हम आपकी व्यक्तिगत जानकारी की सुरक्षा करते हैं और स्पैम नहीं भेजते।
लेखक के बारे में
Masa
Claude Code का गहराई से उपयोग करने वाले इंजीनियर। claudecode-lab.com चलाते हैं, जो 10 भाषाओं में 2,000 से अधिक पेजों वाला टेक मीडिया है।
संबंधित लेख
Claude Code ke liye 7 CLAUDE.md templates jo aap real projects me copy kar sakte hain
Solo app, content site, API, team repo aur legacy codebase ke liye 7 practical CLAUDE.md templates, plus common failure cases.
Claude Code Approval aur Sandbox Guide | Roz ke kaam ke liye safe settings
Claude Code me allow, ask, deny aur sandbox ko kaise baantna chahiye - practical settings, hooks aur real workflow examples ke saath.
Claude Code की सम्पूर्ण शुरुआती गाइड 2026 | शून्य से प्रोफेशनल उपयोग तक 7 स्टेप्स में
पहली बार Claude Code उपयोग करने वालों के लिए पूरी गाइड। इंस्टॉलेशन से लेकर असली डेवलपमेंट वर्कफ्लो में शामिल करने तक — Masa के शुरुआती अनुभव के आधार पर।