YEND.DEV

Cloudflare WorkersでHello Worldまで試す

  • Cloudflare
  • Cloudflare Workers
  • TypeScript
Xで共有する
目次

Cloudflare WorkersでHello Worldまで試したのでメモ。

前提

  • Cloudflareアカウントは取得済み
  • Node.js: v22.8.0

Workers Project の作成

次のコマンドを実行して、Cloudflare Workersのプロジェクトを作成する。

sh
$ npm create cloudflare@latest

セットアップ時にいくつか質問される。今回は以下のような設定を選択した。

  • 作成するディレクトリはhello-world
  • テンプレートはHello World exampleを選択
  • 言語はTypeScriptを選択
  • デプロイは同時には行わないのでNoを選択

全体の設定は下記のようになる。

sh
 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である。

ローカルでの動作確認

ローカルで動作確認を行うために、次のコマンドを実行する。

sh
# プロジェクトディレクトリに移動
$ 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を初めて使用する場合、ログインが必要である。

ローカルサーバーが起動したら、curlhttp://localhost:8787にリクエストを投げてみる。次のようにHello World!が返ってくれば問題ない。

sh
$ curl  http://localhost:8787
Hello World!%

コードの確認

src/index.tsを確認してみる。

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!"に変更する。

ts
export default {
	async fetch(request, env, ctx): Promise<Response> {
		return new Response('Hello Worker!');
	},
} satisfies ExportedHandler<Env>;

"Hello Worker!"が返ってくることを確認できる。

sh
$ curl http://localhost:8787
Hello Worker!%

さらに、リクエスト元の国を判定して表示するように、コードを次のように変更してみる。

ts
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など)。上記のコードではアクセスしてきた国に応じて異なる文字列を返している。

sh
$ curl http://localhost:8787
Hello JP!%

日本からのリクエストの場合は"Hello JP!"が返ってくる。

デプロイ

Workerのデプロイを行うために次のコマンドを実行する。

sh
$ 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!"が返ってくることを確認できる。

sh
$ curl https://hello-world.[YOUR_SUBDOMAIN].workers.dev
Hello JP!%

以上でCloudflare WorkersでHello Worldを試すことができた。

参考