Tips & Tricks

实现Environment Variable Management Best Practices:Claude Code 实战指南

了解implementing environment variable management best practices:Claude Code 实战. 包含实用技巧和代码示例。

环境变量管理が重要な理由

应用开发では、APIキーや数据库接続情報などの機密情報を安全に管理需要。环境变量は那个基本手段ですが、类型安全性や验证が不足しがちです。借助 Claude Code,堅牢な环境变量管理の仕組みを快速构建可以。

类型安全な环境变量の加载

> 环境变量をzodで验证して类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类型安全に読み込む模块を作って。
> 必須・任意の区別と、デフォルト値の配置もできるようにして。
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('環境変数のバリデーションエラー:');
    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();

.env文件の模板管理

> .env.exampleを自動生成するスクリプトを作って。
> 実際の値は含めず、説明评论付きで。
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: '# データベース接続URL (例: postgresql://user:pass@localhost:5432/db)',
      API_KEY: '# APIキー (本番環境では安全に管理してください)',
      JWT_SECRET: '# JWT署名用シークレット (32文字以上)',
    };

    const comment = descriptions[key?.trim()] || '';
    return `${comment}\n${key?.trim()}=`;
  });

  fs.writeFileSync(outputPath, exampleLines.join('\n'));
}

環境ごとの配置切换

> 環境ごとに異なる配置を管理するConfig类を作って。
> development, staging, productionの3環境に支持して。
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;
}

シークレットのローテーション支持

機密情報のローテーションを安全に行うため、複数バージョンのシークレットを同時に保持する仕組みも构建可以。

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 ?? '');

总结

借助 Claude Code,zod通过类型安全な验证、環境別配置、シークレット管理まで、环境变量管理の仕組みを一貫して构建可以。安全の基本作为认证实现指南也可以参考。测试の自动化相关内容请参阅测试戦略の文章で詳しく解説しています。

zod的详细信息请参阅Zod官方文档。环境变量管理の安全相关内容请参阅OWASP Configuration Guide也可以作为参考。

#Claude Code #environment variables #security #TypeScript #configuration