Next.js CORS設定

Next.jsでnext.config.jsヘッダー、ミドルウェア、APIルートハンドラーを使用してCORSヘッダーを設定します。静的および動的オリジンパターンを解説します。

Framework Config

詳細な説明

Next.jsでのCORS — 3つのアプローチ

Next.jsは静的または動的なオリジン処理の必要性に応じて、CORSヘッダーを設定する複数の方法を提供します。

アプローチ1: next.config.js headers()

静的オリジンに最適。ヘッダーはエッジ/CDNレイヤーで設定されます。

// next.config.js
module.exports = {
  async headers() {
    return [
      {
        source: "/api/:path*",
        headers: [
          { key: "Access-Control-Allow-Origin", value: "https://app.example.com" },
          { key: "Access-Control-Allow-Methods", value: "GET, POST, PUT, DELETE, OPTIONS" },
          { key: "Access-Control-Allow-Headers", value: "Content-Type, Authorization" },
          { key: "Access-Control-Allow-Credentials", value: "true" },
          { key: "Access-Control-Max-Age", value: "3600" },
        ],
      },
    ];
  },
};

アプローチ2: ミドルウェア(動的オリジン)

複数オリジンや正規表現ベースの検証に最適。

// middleware.ts
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";

const allowedOrigins = ["https://app.example.com", "https://admin.example.com"];

export function middleware(request: NextRequest) {
  const origin = request.headers.get("origin") ?? "";
  const isAllowed = allowedOrigins.includes(origin);

  if (request.method === "OPTIONS") {
    return new NextResponse(null, {
      status: 204,
      headers: {
        "Access-Control-Allow-Origin": isAllowed ? origin : "",
        "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS",
        "Access-Control-Allow-Headers": "Content-Type, Authorization",
        "Access-Control-Max-Age": "3600",
        ...(isAllowed && { "Access-Control-Allow-Credentials": "true" }),
      },
    });
  }

  const response = NextResponse.next();
  if (isAllowed) {
    response.headers.set("Access-Control-Allow-Origin", origin);
    response.headers.set("Access-Control-Allow-Credentials", "true");
    response.headers.set("Vary", "Origin");
  }
  return response;
}

export const config = { matcher: "/api/:path*" };

アプローチ3: ルートごとのAPIハンドラー

エンドポイントごとのきめ細かな制御に最適。

// app/api/data/route.ts
export async function OPTIONS() {
  return new Response(null, {
    status: 204,
    headers: {
      "Access-Control-Allow-Origin": "https://app.example.com",
      "Access-Control-Allow-Methods": "GET, OPTIONS",
      "Access-Control-Allow-Headers": "Content-Type",
      "Access-Control-Max-Age": "3600",
    },
  });
}

どのアプローチを選ぶか

必要性 アプローチ
静的オリジン、全APIルート next.config.js
複数/動的オリジン ミドルウェア
エンドポイントごとに異なるCORS ルートハンドラー

ユースケース

フルスタック開発者がフロントエンドとAPIが同じコードベースにあるが異なるドメインにデプロイされるNext.jsアプリケーション(例:固有URLのVercelプレビューデプロイメント)を構築しています。動的オリジン処理が必要です。

試してみる — CORS Header Builder

フルツールを開く