Cloudflare PagesでNext.jsを動かすにはEdge Runtimeの指定が必須

Cloudflare Pages で Next.js をデプロイした際に発生したエラー

Cloudflare Pages に Next.js プロジェクトをデプロイしたところ、ローカルでは問題なく動作していたにもかかわらず、ビルド時に次のようなエラーが発生した。

⚡️ ERROR: Failed to produce a Cloudflare Pages build from the project. ⚡️
⚡️ The following routes were not configured to run with the Edge Runtime: ⚡️
 
⚡️ - /api/form
⚡️ - /posts/[id]
⚡️
⚡️ Please make sure that all your non-static routes export the following edge runtime route segment config: ⚡️
⚡️ export const runtime = 'edge';
⚡️
⚡️ You can read more about the Edge Runtime on the Next.js documentation: ⚡️
⚡️ https://nextjs.org/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes

要約すると、非静的ルートが Edge Runtime で動作する設定になっていないため、Cloudflare Pages のビルドが失敗したという内容である。

なぜこのエラーが起きたのか?

Next.js は、特に何も指定しない限り Node.js Runtime を使用する。一方で、Cloudflare Pages / Workers は 非静的ルートをEdge Runtimeで動かすことを前提としている

つまり、

という不一致が原因で、API Route や SSRページがCloudflare上で正しく処理されず、ビルドが失敗していた。

特にエラー対象となっていたルート

今回のエラーでは、以下の 2 つのルートが問題として指摘されていた。

どちらも サーバー側の処理が必要なルート であり、Node.js Runtimeのままでは Cloudflare Pagesで動作しない。

解決方法:export const runtime = 'edge' を付ける

Cloudflare Pages で Next.js の非静的ルートを正しく動作させるには、該当ルートで Runtime を Edge に切り替える必要がある。

export const runtime = 'edge';

この宣言を追加することで、Next.js が対象ルートを Edge Runtime で扱うようになり、Cloudflare Pages のビルドも正常に完了する。

実際の修正例(API Route)

// app/api/form/route.ts
import { NextRequest, NextResponse } from "next/server";
 
export const runtime = "edge";
 
export async function POST(req: NextRequest) {
  const data = await req.json();
 
  if (!data.name || !data.message) {
    return NextResponse.json({ error: "Missing fields" }, { status: 400 });
  }
 
  return NextResponse.json({ ok: true });
}

このように Runtime を Edge に切り替えたところ、Cloudflare Pages のビルドは正常に完了し、デプロイ後も問題なく動作した。

Edge Runtime とは何か

Edge Runtime は Node.js ではなく、より軽量で高速に動作する実行環境 であり、Cloudflare Workers と同じ仕組みのうえで動作する。

世界中のエッジ拠点で実行されるため、低レイテンシでレスポンスできるという利点がある。

ただし制約もあり、

という点に注意が必要。

どのルートに runtime = 'edge' が必要か

Cloudflare Pagesでは、以下のケースで Edge Runtime を必ず指定する必要がある。

1. API Route (app/api/**/route.ts)

サーバー側で処理する以下のようなルートは、すべて Edge Runtime を要求する。

これらは 必ず Edge Runtime を指定する必要がある

2. 動的レンダリング(SSR)を行うページ

次のような「リクエストごとに処理が走る」ページも Edge Runtime を必要とする。

一方、完全に静的化できるページであれば Runtime 設定は不要 である。

まとめ