til/applied-sciences/engineering/cloudflare-wrangler-and-pages-functions
cloudflare-wrangler-and-pages-functions.mdupdated 2026-07-162618 words
ダブルクリックで英日反転
Applied Sciences · Engineering

Cloudflare Wrangler and Pages Functions

EN

Wrangler is Cloudflare's official CLI for developing and deploying Workers and Pages. Pages Functions extend a static site with serverless backend logic, bundled at build time into a single Worker.

What Wrangler does

  • `wrangler dev` — starts a local dev server that mirrors production.
  • `wrangler deploy` — publishes your code to Cloudflare's edge network.
  • Git integration lets Pages auto-deploy on every push to main, so manual `wrangler deploy` is often unnecessary.

Pages Functions basics

  • Place files in the repo-root `functions/` directory; file name = URL path.
  • Example: `functions/api/hello.js` is accessible at `/api/hello`.
  • Dynamic segments use bracket syntax: `[id].js`.
  • At build time all files are bundled into one Worker (the Functions bundle).

Building a REST API

  • Export named handlers like `onRequestGet(context)` to match HTTP methods.
  • Return `Response.json(...)` for JSON responses.

Common failure causes

  • `functions/` placed outside the repo root — files won't be included in the build.
  • `_routes.json` `exclude` list contains `/api/*` — requests hit static files instead.
  • Pages dashboard has Functions disabled, or `wrangler.toml` is written for Workers, not Pages.
Point `functions/` at the repo root, match file names to URL paths, and let Wrangler (or Git) handle the rest.
Applied Sciences · Engineering

Cloudflare Wrangler と​ Pages Functions

JP

Wrangler​(=Cloudflare公式CLI)は​ Workers / Pages の​開発・デプロイを​担う​ツール。​Pages Functions は​静的サイトに​サーバーレスの​バックエンド処理を​追加する​仕組みで、​ビルド時に​単一の​ Worker へ​バンドルされる。

Wrangler の​役割

  • `wrangler dev` — 本番に​近い​環境を​ローカルで​再現する​dev サーバーを​起動。
  • `wrangler deploy` — コードを​ Cloudflare の​エッジ​(=地理的に​最寄りの​データセンター)に​公開。
  • GitHub 連携すれば​ main ブランチへの​ push で​自動デプロイされ、​手動実行が​不要に​なる。

Pages Functions の​基本

  • リポジトリルートの​ `functions/` に​ファイルを​置くだけ。​ファイル名が​ URL パスに​なる。
  • 例: `functions/api/hello.js` → `/api/hello` で​アクセス可能。
  • 動的パラメーターは​ブラケット記法 `[id].js` で​表現。
  • ビルド時に​すべての​ファイルが​1つの​ Worker へ​結合される​(Functions bundle)。

REST API の​実装

  • `onRequestGet(context)` などの​名前​付きエクスポートで​ HTTP メソッドに​対応。
  • `Response.json(...)` で​ JSON レスポンスを​返す。

よく​ある​不具合の​原因

  • `functions/` が​リポジトリルート以外に​ある​ — ビルドに​含まれない。
  • `_routes.json`​(ルーティング制御ファイル)の​ `exclude` に​ `/api/*` が​入っている​ — 静的ファイル扱いに​なる。
  • Pages ダッシュボードで​ Functions が​無効、​または​ `wrangler.toml` が​ Workers 用設定に​なっている。
`functions/` は​リポジトリルートに​置き、​ファイル名と​ URL パスを​一致させれば、​あとは​ Wrangler​(または​ Git 連携)が​自動で​処理する。
148 notestil