haihai Blog

Cloudflare Workers Hello Worold

2024-03-27

はじめに

ターミナルから C3 (create-cloudflare-cli) を利用し、 Cloudflare Workers のプロジェクト作成とアプリケーションのデプロイを行います。

事前準備

C3 を利用するための、ツールのバージョンなど詳細については、 Cloudflare Docs - Get started guide をご確認ください。

  • Cloudflare アカウントがあること
  • npm をインストールしていること
  • Node.js をインストールしていること

Cloudflare Workers のプロジェクトを作成し、デプロイする

ブラウザで Cloudflare にログインした状態で、ターミナルから npm create cloudflare@latest コマンドを実行します。
最初に create-cloudflare パッケージのインストールについて質問があり、 y を選択しました。

その後、プロジェクトについての質問に答えるとローカルにプロジェクトが作成され、続いてデプロイするかどうかの質問があります。
デプロイするとデフォルトでは、 Cloudflare Workers & Pages に設定したサブドメインが利用されました。
例: project-name.subdomain.workers.dev

$ npm create cloudflare@latest
Need to install the following packages:
create-cloudflare@2.16.0
Ok to proceed? (y) y

using create-cloudflare version 2.16.0

╭ Create an application with Cloudflare Step 1 of 3
│
├ In which directory do you want to create your application?
│ dir ./{project-name}
│
├ What type of application do you want to create?
│ type "Hello World" Worker
│
├ Do you want to use TypeScript?
│ yes 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 2024-03-20
│
├ Do you want to use git for version control?
│ yes git
│
├ Initializing git repo
│ initialized git
│
├ Committing new files
│ git commit
│
╰ Application configured

以降に、デプロイするか質問があります。今回は yes を選択します。

╭ Deploy with Cloudflare Step 3 of 3
│
├ Do you want to deploy your application?
│ yes deploy via `npm run deploy`
│
├ Logging into Cloudflare checking authentication status
│ not logged in
│
├ Logging into Cloudflare This will open a browser window
│ allowed via `wrangler login`
│
├ Selecting Cloudflare account retrieving accounts
│ account {your-account}'s Account
│
├ Deploying your application
│ deployed via `npm run deploy`
│
├  SUCCESS  View your deployed application at https://{project-name}.{subdomain}.workers.dev
│
│ Navigate to the new directory cd {project-name}
│ Run the development server npm run start
│ Deploy your application npm run deploy
│ Read the documentation https://developers.cloudflare.com/workers
│ Stuck? Join us at https://discord.gg/cloudflaredev
│
├ Waiting for DNS to propagate
│ DNS propagation complete.
│
├ Waiting for deployment to become available
│ deployment is ready at: https://{project-name}.{subdomain}.workers.dev
│
├ Opening browser
│
╰ See you again soon!

テンプレートから作成したプロジェクトを確認する

プロジェクトの処理内容をちらっと確認します。
/src/index.ts ファイルに処理が記載されています。Hello World! を返却してくれそうな雰囲気があります。

export default {
  async fetch(
    request: Request,
    env: Env,
    ctx: ExecutionContext
  ): Promise<Response> {
    return new Response('Hello World!')
  }
}

ブラウザからデプロイ先の URL https://{project-name}.{subdomain}.workers.dev へアクセスすると Hello World! が表示されました。

Cloudflare Workers  を変更する

/src/index.ts ファイルのコメントに動作検証およびデプロイする方法について記載があります(英語)。

  • ターミナルで npm run dev を実行して開発サーバーを起動します。
  • http://localhost:8787/ でブラウザのタブを開き、Worker の動作を確認します。
  • npm run deploy を実行してワーカーを公開します。

開発サーバーを起動し、ブラウザで動作を確認しながらプログラムを修正します。
受信したリクエストヘッダーの cf (Cloudflare のグローバルネットワークが提供するリクエストに関する情報)から region と city を表示するように修正します。

  export default {
    async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
-     return new Response('Hello World!');
+     const region = request.cf?.region ?? "region は不明";
+     const city = request.cf?.city ?? "city は不明";
+     return new Response("あなたは、 " + region + " の " + city + " からアクセスしています。");
    },
  };

http://localhost:8787/ へアクセスし、開発サーバー上で表示内容が変更されていることを確認します。

npm run deploy を実行してワーカーを公開(更新)します。

公開後、デプロイ先の URL https://{project-name}.{subdomain}.workers.dev へアクセスすると変更内容が反映されていることが確認できました。

まとめ

プロジェクト作成からデプロイまで非常にスムーズに行えました。

開発サーバーの起動が簡単で、プログラムの動作確認が実施しやすかったです。
また、開発サーバー起動後の操作が初めての人でも使いやすいようになっていて非常にわかりやすかったです。

開発サーバー起動後の画面

 ⛅️ wrangler 3.38.0 (update available 3.39.0)
-------------------------------------------------------
⎔ Starting local server...
[wrangler:inf] Ready on http://localhost:8787
╭─────────────────────────────────────────────╮
│ [b] open a browser, [d] open Devtools, [l] turn off local mode, [c] clear console, [x] to exit │
╰─────────────────────────────────────────────╯

参考 URL