0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Cloudflare R2のオブジェクトに変更があった際にWebhookを飛ばす方法

Posted at

はじめに

Cloudflare R2にオブジェクトが追加された際に、アップロードされたファイルを元にDBにデータの保存などを行う必要がありました。

ですが、Cloudflare R2にはWebhookを設定することができません。

今回はCloudflare Queuesという機能を使用して、Cloudflare Workersを経由しアプリケーションサーバーへWebhookを飛ばす方法を紹介します。

Cloudflare Queuesとは

Cloudflare Queuesは、Cloudflareが提供するメッセージングサービスです。
GCPでいうと、Cloud Tasks。AWSでいうと、Amazon Simple Queue Service (SQS)に相当します。

キューにメッセージを登録すると、事前に設定したCloudflare Workersに対しリクエストが送信されます。
(キューのConsumer設定のタイプをWorkersに設定している場合。)

構成

スクリーンショット 2025-09-19 17.08.52.png

  • Cloudflare R2
  • Cloudflare Queues
  • Cloudflare Workers

設定方法

1. Cloudflare Workersでワーカーを仮作成する

  1. Workersダッシュボードを開く
  2. 作成
  3. 「Hello Worldを開始する」を選択
  4. ワーカー名を指定(あとから変えれるので何でも良いです。)
  5. デプロイを押す
  6. コードを編集するを押す
  7. worker.jsに下記を仮設定
  8. デプロイを押す
export default {
    async fetch(batch, env, ctx) {
        //webhookを受け取りたいendpoint
        const webhook_endpoint = `https://example.com/webhook`; 

        const response = await fetch(webhook_endpoint, {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify(batch.messages)
        });
    
        return new Response(await response.text(), { status: response.status });
    }
};

2. Cloudflare Queuesでキューの作成を行う

  1. 右上のキューを作成を押す
  2. キューの名前を設定する(重複不可)
  3. 作成したキュー名を押す
  4. 設定を開く
  5. コンシューマーの追加を押す
    1. タイプ:Worker
    2. Worker:先ほど作成したWorker(最低限の設定なので各々調べて設定してください。)

3. Cloudflare R2でイベント通知設定を行う

  1. 該当のバケットを選択
  2. 設定を開く
  3. イベント通知の追加ボタンを押す
  4. 既存のキューに接続するから、先ほど作成したキューを選択
  5. イベントの種類を選択
  6. 通知を追加を押す
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?