目次
Cloudflare WorkersでHello Worldまで試したのでメモ。
前提
- Cloudflareアカウントは取得済み
- Node.js:
v22.8.0
Workers Project の作成
次のコマンドを実行して、Cloudflare Workersのプロジェクトを作成します。
$ npm create cloudflare@latest
セットアップ時にいくつか質問されます。今回は以下のような設定を選択しました。
- 作成するディレクトリは
hello-world
- テンプレートは
Hello World example
を選択 - 言語は
TypeScript
を選択 - デプロイは同時には行わないので
No
を選択
全体の設定は下記のようになります。
╭ Create an application with Cloudflare Step 1 of 3
│
├ In which directory do you want to create your application?
│ dir ./hello-world
│
├ What would you like to start with?
│ category Hello World example
│
├ Which template would you like to use?
│ type Hello World Worker
│
├ Which language do you want to use?
│ lang TypeScript
│
├ Copying template files
│ files copied to project directory
│
├ Updating name in `package.json`
│ updated `package.json`
│
├ Installing dependencies
│ installed via `npm install`
│
╰ Application created
╭ Configuring your application for Cloudflare Step 2 of 3
│
├ Installing @cloudflare/workers-types
│ installed via npm
│
├ Adding latest types to `tsconfig.json`
│ added @cloudflare/workers-types/2023-07-01
│
├ Retrieving current workerd compatibility date
│ compatibility date 2025-01-09
│
├ Do you want to use git for version control?
│ yes git
│
├ Initializing git repo
│ initialized git
│
├ Committing new files
│ git commit
│
╰ Application configured
╭ Deploy with Cloudflare Step 3 of 3
│
├ Do you want to deploy your application?
│ no deploy via `npm run deploy`
│
╰ Done
ローカルにhello-world
ディレクトリが作成され、その中にプロジェクトが作成されていればOKです。
ローカルでの動作確認
ローカルで動作確認を行うために、次のコマンドを実行します。
# プロジェクトディレクトリに移動
$ cd hello-world
# ローカルサーバーを起動
$ npx wrangler dev
> [email protected] dev
> wrangler dev
⛅️ wrangler 3.101.0
--------------------
⎔ Starting local server...
[wrangler:inf] Ready on http://localhost:8787
Wrangler はWorkers用の公式CLIツールです。Workersのプロジェクトを管理することができます。Wranglerを初めて使用する場合、ログインが必要です。
ローカルサーバーが起動したら、curl
でhttp://localhost:8787
にリクエストを投げてみます。次のようにHello World!
が返ってくれば問題ありません。
$ curl http://localhost:8787
Hello World!%
コードの確認
src/index.ts
を確認してみます。
export default {
async fetch(request, env, ctx): Promise<Response> {
return new Response('Hello World!');
},
} satisfies ExportedHandler<Env>;
This fetch() handler will be called when your Worker receives an HTTP request.
出典: https://developers.cloudflare.com/workers/get-started/guide/#3-write-code
Workerは、HTTPリクエストを受け取るたびにfetch
関数を呼び出します。
The Workers runtime expects fetch handlers to return a Response object or a Promise which resolves with a Response object.
出典: https://developers.cloudflare.com/workers/get-started/guide/#3-write-code
fetch
関数はResponse
オブジェクトを返すか、Response
オブジェクトを解決するPromiseを返す必要があるようです。
今回の例では、"Hello World!"
という文字列を持つResponse
オブジェクトを返しているのがわかります。
コードの編集
次に"Hello World!"
を"Hello Worker!"
に変更します。
export default {
async fetch(request, env, ctx): Promise<Response> {
return new Response('Hello Worker!');
},
} satisfies ExportedHandler<Env>;
"Hello Worker!"
が返ってくることを確認できます。
$ curl http://localhost:8787
Hello Worker!%
さらに、リクエスト元の国を判定して表示するように、コードを次のように変更してみます。
export default {
async fetch(request, env, ctx): Promise<Response> {
const country = request.cf?.country ?? 'unknown';
return new Response(`Hello ${country}!`);
},
} satisfies ExportedHandler<Env>;
Country of the incoming request. The two-letter country code in the request. This is the same value as that provided in the CF-IPCountry header, for example, "US".
参照: https://developers.cloudflare.com/workers/runtime-apis/request/#incomingrequestcfproperties
request.cf.country
は、リクエスト送信元の国を2文字のコードで取得します(例: 日本ならJP
、アメリカならUS
など)。上記のコードではアクセスしてきた国に応じて異なる文字列を返しています。
$ curl http://localhost:8787
Hello JP!%
日本からのリクエストの場合は"Hello JP!"
が返ってきます。
デプロイ
Workerのデプロイを行うために次のコマンドを実行します。
$ npx wrangler deploy
⛅️ wrangler 3.101.0
--------------------
Total Upload: 0.24 KiB / gzip: 0.19 KiB
Uploaded hello-world (2.97 sec)
Deployed hello-world triggers (0.31 sec)
https://hello-world.[YOUR_SUBDOMAIN].workers.dev
https://hello-world.[YOUR_SUBDOMAIN].workers.dev
にデプロイされました([YOUR_SUBDOMAIN]
は自分のサブドメインに置き換えてください)。
実際にリクエストを投げてみると、"Hello JP!"
が返ってくることを確認できます。
$ curl https://hello-world.[YOUR_SUBDOMAIN].workers.dev
Hello JP!%
以上でCloudflare WorkersでHello Worldを試すことができました。