Advanced

Leveraging Edge Computing with Claude Code

Aprenda sobre leveraging edge computing usando o Claude Code. Dicas praticas e exemplos de codigo incluidos.

エッジコンピューティングとは

エッジコンピューティングは、ユーザーに地理的に近いサーバーで処理を実行する技術です。レイテンシを大幅に削減し、高速なレスポンスを実現できます。Claude Codeを活用して、エッジ対応のアプリケーションを構築しましょう。

Cloudflare Workers

// src/index.ts
export default {
  async fetch(
    request: Request,
    env: Env,
    ctx: ExecutionContext
  ): Promise<Response> {
    const url = new URL(request.url);

    // Routing
    switch (url.pathname) {
      case "/api/geo":
        return handleGeo(request);
      case "/api/cache":
        return handleCachedData(request, env, ctx);
      default:
        return new Response("Not Found", { status: 404 });
    }
  },
};

function handleGeo(request: Request): Response {
  // Cloudflareが自動で付与するヘッダー
  const country = request.headers.get("cf-ipcountry") || "unknown";
  const city = request.cf?.city || "unknown";

  return Response.json({
    country,
    city,
    message: `こんにちは!${city}からのアクセスですね。`,
  });
}

async function handleCachedData(
  request: Request,
  env: Env,
  ctx: ExecutionContext
): Promise<Response> {
  const cacheKey = new URL(request.url).pathname;

  // KVストアからキャッシュ取得
  const cached = await env.MY_KV.get(cacheKey);
  if (cached) {
    return Response.json(JSON.parse(cached), {
      headers: { "X-Cache": "HIT" },
    });
  }

  // オリジンからデータ取得
  const data = await fetch("https://api.example.com/data").then(
    (r) => r.json()
  );

  // KVにキャッシュ(TTL: 5分)
  ctx.waitUntil(
    env.MY_KV.put(cacheKey, JSON.stringify(data), {
      expirationTtl: 300,
    })
  );

  return Response.json(data, {
    headers: { "X-Cache": "MISS" },
  });
}

Vercel Edge Functions

// app/api/personalize/route.ts
import { NextRequest } from "next/server";

export const runtime = "edge";

export async function GET(request: NextRequest) {
  const country = request.geo?.country || "JP";
  const region = request.geo?.region || "unknown";

  // 地域に応じたコンテンツ
  const content = await getLocalizedContent(country);

  // エッジキャッシュ設定
  return Response.json(
    {
      content,
      servedFrom: region,
      timestamp: Date.now(),
    },
    {
      headers: {
        "Cache-Control": "public, s-maxage=60, stale-while-revalidate=300",
      },
    }
  );
}

async function getLocalizedContent(country: string) {
  const priceMultiplier: Record<string, number> = {
    JP: 1,
    US: 0.0067,
    EU: 0.0061,
  };

  return {
    currency: country === "JP" ? "USD" : country === "US" ? "USD" : "EUR",
    multiplier: priceMultiplier[country] || 1,
  };
}

エッジでの認証処理

// middleware.ts(Vercel Edge Middleware)
import { NextRequest, NextResponse } from "next/server";
import { jwtVerify } from "jose";

const secret = new TextEncoder().encode(process.env.JWT_SECRET!);

export async function middleware(request: NextRequest) {
  // 公開パスはスキップ
  const publicPaths = ["/", "/login", "/api/auth"];
  if (publicPaths.some((p) => request.nextUrl.pathname.startsWith(p))) {
    return NextResponse.next();
  }

  const token = request.cookies.get("token")?.value;
  if (!token) {
    return NextResponse.redirect(new URL("/login", request.url));
  }

  try {
    const { payload } = await jwtVerify(token, secret);

    // リクエストヘッダーにユーザー情報を付与
    const response = NextResponse.next();
    response.headers.set("x-user-id", payload.sub as string);
    response.headers.set("x-user-role", payload.role as string);
    return response;
  } catch {
    return NextResponse.redirect(new URL("/login", request.url));
  }
}

export const config = {
  matcher: ["/dashboard/:path*", "/api/protected/:path*"],
};

エッジでのA/Bテスト

export const runtime = "edge";

export async function middleware(request: NextRequest) {
  // 既存のバリアント割り当てを確認
  const variant = request.cookies.get("ab-variant")?.value;

  if (!variant) {
    // Randomly assign to new users
    const newVariant = Math.random() < 0.5 ? "A" : "B";
    const response = NextResponse.next();
    response.cookies.set("ab-variant", newVariant, {
      maxAge: 60 * 60 * 24 * 30,
    });

    // バリアントに応じたページにリライト
    if (newVariant === "B") {
      return NextResponse.rewrite(
        new URL("/variants/b" + request.nextUrl.pathname, request.url)
      );
    }
    return response;
  }

  if (variant === "B") {
    return NextResponse.rewrite(
      new URL("/variants/b" + request.nextUrl.pathname, request.url)
    );
  }

  return NextResponse.next();
}

Claude Codeでの活用

エッジ関数の実装をClaude Codeに依頼する例です。パフォーマンス最適化はSSR vs SSG比較、キャッシュ戦略はRedisキャッシュ設計も参照してください。

Vercel Edge FunctionsでAPIを実装して。
- 地域別のコンテンツ出し分け
- エッジでのJWT検証
- KVストアでのキャッシュ
- A/Bテストのミドルウェア

Cloudflare Workersの詳細はCloudflare Workers公式ドキュメントを参照してください。Claude Codeの使い方は公式ドキュメントで確認できます。

Summary

エッジコンピューティングはレイテンシ削減とスケーラビリティの両立を実現します。Claude Codeを使えば、プラットフォーム固有のAPIやベストプラクティスを理解した上でエッジ対応コードを効率的に実装できます。

#Claude Code #edge computing #Cloudflare Workers #Vercel #performance