SCALE — Build Lab
開発パターン · CLOUDFLARE FUNCTION

Cloudflare Pages Functions CORS ヘルパ

CATEGORY開発パターン TYPECloudflare Function EFFORT30〜60分 DIFFICULTY
PRIMARY CODE
ts · scale-crm:functions/_lib/cors.ts
// CORS ヘルパー(同一オリジンのため緩め設定)
export const CORS_HEADERS = {
  'Access-Control-Allow-Origin': '*',
  'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
  'Access-Control-Allow-Headers': 'Content-Type, X-User',
};

export function corsResponse(body: any, status = 200): Response {
  return new Response(JSON.stringify(body), {
    status,
    headers: { 'Content-Type': 'application/json', ...CORS_HEADERS },
  });
}

export function corsError(message: string, status = 500): Response {
  return corsResponse({ error: message }, status);
}

export function handleOptions(): Response {
  return new Response(null, { status: 204, headers: CORS_HEADERS });
}

前提条件
Tailwind CSS v4TypeScript 5
USE CASES
  • 全 Cloudflare Pages Functions プロジェクト

Cloudflare Pages Functions CORS ヘルパ

:LiTarget: 用途

Cloudflare Pages Functions で CORS を統一処理するヘルパ。OPTIONS preflight + ヘッダー付与。

:LiSparkle: 特徴

  • CORS preflight 対応
  • 全レスポンスにヘッダー自動付与
  • 型安全
  • 使い回し容易

:LiCode: 実コード(SCALE Base より自動抽出)

:LiInfo: scale-crm:functions/_lib/cors.ts の中身そのもの。コピペ即可。

// CORS ヘルパー(同一オリジンのため緩め設定)
export const CORS_HEADERS = {
  'Access-Control-Allow-Origin': '*',
  'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
  'Access-Control-Allow-Headers': 'Content-Type, X-User',
};

export function corsResponse(body: any, status = 200): Response {
  return new Response(JSON.stringify(body), {
    status,
    headers: { 'Content-Type': 'application/json', ...CORS_HEADERS },
  });
}

export function corsError(message: string, status = 500): Response {
  return corsResponse({ error: message }, status);
}

export function handleOptions(): Response {
  return new Response(null, { status: 204, headers: CORS_HEADERS });
}

:LiFolder: ソースファイルのパス

/Users/oogushiyuuki/株式会社SCALE/scale-lead/functions/_lib/cors.ts

:LiHandPointer: 使い方

対象プロジェクトに該当ファイルをコピーして、props を流し込むだけ。

:LiAlertCircle: 注意事項

  • 依存パッケージを忘れず追加