🚀 Cloudflare Pages + Edge Functions

エッジネットワークで実行される動的 API のデモ

💡 このデモについて

以下のインタラクティブなデモでは、Cloudflare Pages Functions を使用した動的な API レスポンスを体験できます。
リアルタイムでエッジネットワークから応答が返されます。

1️⃣ Greeting API

クエリパラメータを受け取ってパーソナライズされたメッセージを返す基本的な API です。

使用例:
📢 レスポンス:
エンドポイント:
GET /api/greeting?name={name}
コード例を表示
// functions/api/greeting.js export default { async fetch(request, env, ctx) { const url = new URL(request.url); const name = url.searchParams.get('name') || 'World'; return new Response(JSON.stringify({ message: `Hello, ${name}!`, timestamp: new Date().toISOString() }), { headers: { 'Content-Type': 'application/json' } }); } };

2️⃣ ユーザー API

動的ルーティングで指定された ID のユーザー情報を返します。`/api/users/[id].js` の実装例です。

使用例:
👤 レスポンス:
エンドポイント:
GET /api/users/[id]
コード例を表示
// functions/api/users/[id].js export default { async fetch(request, env, ctx) { const userId = request.url.split('/').pop(); return new Response(JSON.stringify({ id: userId, name: `User ${userId}`, email: `user${userId}@example.com`, created: new Date().toISOString() }), { headers: { 'Content-Type': 'application/json' } }); } };

3️⃣ セキュアな API

環境変数で設定されたトークンを検証する認証付き API です。

トークンを入力:
🔐 レスポンス:
エンドポイント:
GET /api/secure (Headers: Authorization: Bearer {token})
コード例を表示
// functions/api/secure.js export default { async fetch(request, env, ctx) { const auth = request.headers.get('Authorization'); const token = env.API_SECRET; if (auth !== `Bearer ${token}`) { return new Response( JSON.stringify({ error: 'Unauthorized' }), { status: 401 } ); } return new Response(JSON.stringify({ data: 'Secret data', user: 'authenticated' }), { headers: { 'Content-Type': 'application/json' } }); } };

4️⃣ リアルタイムデータ

現在のサーバー時刻、地理情報、リクエスト情報をリアルタイムで返します。

⏰ レスポンス:
エンドポイント:
GET /api/realtime
コード例を表示
// functions/api/realtime.js export default { async fetch(request, env, ctx) { return new Response(JSON.stringify({ timestamp: new Date().toISOString(), epoch: Date.now(), ip: request.headers.get('CF-Connecting-IP'), country: request.headers.get('CF-IPCountry'), userAgent: request.headers.get('User-Agent') }), { headers: { 'Content-Type': 'application/json' } }); } };