0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

個人的備忘録:CORSMiddlewareって何?FastAPIでの設定方法を確認してみた

Last updated at Posted at 2025-04-29

はじめに

バックエンドAPIとフロントエンドが異なるドメインやポートで動作する場合、ブラウザのセキュリティ制約によりCORSの設定が必要になります。

FastAPIでは、CORSMiddleware を使用して簡単にCORS設定を行うことが可能です。

今回取り扱う設定例はこちらです。

app.add_middleware(
    CORSMiddleware,
    allow_origins=["https://xxx.xyz", "https://api.xxx.xyz", "http://localhost"],
    allow_credentials=True,
    allow_methods=["GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"],
    allow_headers=["Content-Type", "Authorization", "X-CSRF-Token", "Access-Control-Allow-Origin"],
)

個人の備忘録程度の走り書きとなっておりますが、温かい目で見守っていただければ幸いです。

設定内容の解説

項目 内容
allow_origins Next.js(xxx.xyzドメイン)とローカル(localhost)からのリクエストを許可
allow_credentials CookieやAuthorizationヘッダなど認証情報つきリクエストを許可
allow_methods 各種HTTPメソッド(GET, POST, PUT, DELETE, PATCH, OPTIONS)を許可
allow_headers 特定ヘッダー(Content-Type, Authorization, X-CSRF-Tokenなど)を許可

これにより、Next.jsとFastAPI間のAPI通信がスムーズに行えるようになります。


補足点

  • 本番環境 (https://xxx.xyz, https://api.xxx.xyz) だけでなく、開発環境 (http://localhost) も許可されている
  • 認証情報 (credentials) を正しく取り扱える
  • メソッドやヘッダーも広く許可しており、一般的なAPI操作が問題なくできる

まとめ

  • FastAPIのCORS設定は、CORSMiddlewareを使って柔軟に管理できる
  • 本番・開発両方に適切なオリジン設定を施すことが重要
  • allow_headersにはレスポンスヘッダーを含めない
  • 必要に応じてlocalhostのポート番号も指定する

CORS設定は、セキュリティにも直結する重要なポイントです。今回の改善ポイントも意識しながら、適切な設定を心がけましょう...!

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?