環境変数と設定
環境変数を使って、開発・本番で異なる設定を管理。セキュリティと柔軟性を両立させます。
なぜ環境変数を使うのか
コードに直書きのリスク
- ✗ パスワードがGitに残る
- ✗ 本番/開発の切り替えが面倒
- ✗ 設定変更にデプロイが必要
環境変数のメリット
- ○ 機密情報をコードから分離
- ○ 環境ごとに値を変えられる
- ○ 設定変更が容易
FastAPI での設定管理
.env ファイル
# .env DATABASE_URL=mysql+pymysql://user:password@localhost:3306/blog SECRET_KEY=your-super-secret-key-change-in-production DEBUG=true CORS_ORIGINS=http://localhost:3000
config.py(pydantic-settings使用)
from pydantic_settings import BaseSettings
from functools import lru_cache
class Settings(BaseSettings):
# データベース
database_url: str
# セキュリティ
secret_key: str
algorithm: str = "HS256"
access_token_expire_minutes: int = 30
# その他
debug: bool = False
cors_origins: str = "http://localhost:3000"
@property
def cors_origins_list(self) -> list[str]:
return [origin.strip() for origin in self.cors_origins.split(",")]
class Config:
env_file = ".env"
@lru_cache()
def get_settings():
return Settings()
settings = get_settings()
使用例
from config import settings
# データベース接続
engine = create_engine(settings.database_url)
# JWT生成
jwt.encode(data, settings.secret_key, algorithm=settings.algorithm)
# CORS設定
app.add_middleware(
CORSMiddleware,
allow_origins=settings.cors_origins_list,
)
Next.js での環境変数
.env.local(開発用)
# .env.local # ブラウザで使用する変数は NEXT_PUBLIC_ プレフィックス必須 NEXT_PUBLIC_API_URL=http://localhost:8000 # サーバーサイドのみで使用 API_SECRET_KEY=server-side-only-key
使用例
// クライアントサイド(NEXT_PUBLIC_ が必要)
const apiUrl = process.env.NEXT_PUBLIC_API_URL;
fetch(`${apiUrl}/posts`);
// サーバーサイド(Server Component / API Route)
const secretKey = process.env.API_SECRET_KEY;
注意:NEXT_PUBLIC_の変数はブラウザに露出します。機密情報には使わないでください。
環境ごとの設定ファイル
# ファイル構成 .env # 共通(Gitにコミット可) .env.local # ローカル開発(Git除外) .env.development # 開発環境 .env.production # 本番環境 # .gitignore に追加 .env.local .env.*.local
優先順位(Next.js)
- 1.
.env.local(最優先) - 2.
.env.[environment] - 3.
.env
Docker Compose での環境変数
# compose.yaml
services:
backend:
build: ./backend
env_file:
- ./backend/.env
environment:
- DATABASE_URL=${DATABASE_URL} # .envから参照
frontend:
build: ./frontend
env_file:
- ./frontend/.env.local
environment:
- NEXT_PUBLIC_API_URL=http://backend:8000
本番環境での管理
各種プラットフォーム
- Vercel: Project Settings → Environment Variables
- Railway: Variables タブ
- AWS: Systems Manager Parameter Store / Secrets Manager
- Render: Environment → Environment Variables
まとめ
- ✓ 機密情報は必ず環境変数で管理
-
✓
.env.localはGitにコミットしない -
✓
Next.jsで公開する変数は
NEXT_PUBLIC_プレフィックス - ✓ 本番環境はプラットフォームの管理機能を使う