1
1

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 を触ってみたので手順の備忘録を残す

Last updated at Posted at 2025-12-04

Cloudflare WorkersでAPIをデプロイする手順

個人的にCloudflareとHono を触ってみたいなと思いたち、Claude Code に色々聞きながら進めてAPIを公開できました。
せっかくなので、手順の備忘録を残して置こうと思い、Cloudflare Workers + Hono + D1を使って、REST APIを構築・デプロイする手順を残していきます。

前提条件

  • Node.js がインストールされていること
  • Cloudflareアカウントを持っていること

1. プロジェクトの作成

npm create cloudflare@latest my-api

対話形式で以下を選択:

  • テンプレート: Web frameworkHono
  • TypeScript: Yes
  • Git: お好みで

2. プロジェクト構成

作成されるファイル構成:

my-api/
├── src/
│   └── index.ts      # メインのWorkerコード
├── package.json
├── tsconfig.json
├── wrangler.jsonc    # Cloudflare Workers設定
└── worker-configuration.d.ts

3. 依存パッケージのインストール

cd my-api
npm install

主な依存パッケージ:

  • hono - 軽量なWebフレームワーク
  • wrangler - Cloudflare Workers CLI

4. D1データベースの作成(本番環境)

Cloudflare D1(SQLiteベースのサーバーレスDB)を作成:

npx wrangler d1 create user-database

実行すると以下のような出力が表示される:

✅ Successfully created DB 'user-database'

[[d1_databases]]
binding = "DB"
database_name = "user-database"
database_id = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"

この database_id を次のステップで使用する。

5. wrangler.jsoncの設定

wrangler.jsonc にD1バインディングを追加:

{
  "$schema": "node_modules/wrangler/config-schema.json",
  "name": "my-api",
  "main": "src/index.ts",
  "compatibility_date": "2025-11-15",
  "d1_databases": [
    {
      "binding": "DB",
      "database_name": "user-database",
      "database_id": "your-database-id-here"
    }
  ]
}

6. データベーススキーマの作成

schema.sql ファイルを作成:

CREATE TABLE IF NOT EXISTS users (
  user_id TEXT PRIMARY KEY,
  nickname TEXT,
  comment TEXT,
  created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);

マイグレーション実行:

# ローカル開発用(.wrangler/state/に作成される)
npx wrangler d1 execute user-database --local --file=./schema.sql

# 本番環境用(Cloudflare上のD1に適用)
npx wrangler d1 execute user-database --remote --file=./schema.sql

注意: 本番環境へのスキーマ適用(--remote)は、デプロイ前に必ず実行すること。

7. APIの実装

import { Hono } from 'hono';

type Bindings = {
  DB: D1Database;
};

const app = new Hono<{ Bindings: Bindings }>();

// POST /users - ユーザー作成
app.post('/users', async (c) => {
  const { user_id, nickname } = await c.req.json();

  await c.env.DB.prepare(
    'INSERT INTO users (user_id, nickname) VALUES (?, ?)'
  ).bind(user_id, nickname).run();

  return c.json({ message: 'User created', user_id }, 201);
});

// GET /users/:user_id - ユーザー取得
app.get('/users/:user_id', async (c) => {
  const user_id = c.req.param('user_id');

  const user = await c.env.DB.prepare(
    'SELECT * FROM users WHERE user_id = ?'
  ).bind(user_id).first();

  if (!user) {
    return c.json({ message: 'User not found' }, 404);
  }

  return c.json(user);
});

export default app;

8. ローカル開発

npm run dev

http://localhost:8787 でローカルサーバーが起動。

9. デプロイ

# Cloudflareにログイン
npx wrangler login

# デプロイ
npm run deploy

デプロイ後、https://my-api.<your-subdomain>.workers.dev でAPIが公開される。

10. 動作確認

# ユーザー作成
curl -X POST https://my-api.xxx.workers.dev/users \
  -H "Content-Type: application/json" \
  -d '{"user_id": "user1", "nickname": "taro"}'

# ユーザー取得
curl https://my-api.xxx.workers.dev/users/user1

手順のまとめ

  1. npm create cloudflare でプロジェクト作成
  2. wrangler d1 create でD1データベース作成
  3. wrangler.jsonc にバインディング設定
  4. wrangler d1 execute でスキーマ適用
  5. HonoでAPIを実装
  6. npm run dev でローカル開発
  7. npm run deploy で本番デプロイ
1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?