Use Cases

Claude CodeでVercel Edge Functionsを活用する方法

Claude Codeを活用したVercel Edge Functionsの実装ガイド。ミドルウェア、エッジAPI、A/Bテスト、地理的ルーティングまで実践的に解説します。

Vercel Edge FunctionsをClaude Codeで実装する

Vercel Edge Functionsは、世界中のエッジロケーションでコードを実行できるサーバーレス環境です。コールドスタートがほぼなく、ユーザーに近い場所で処理を行えるため、超低レイテンシーなAPIやミドルウェアを構築できます。Claude Codeを使えば、Edge Runtime特有の制約を考慮した実装もスムーズに進められます。

Middlewareの実装

> Next.jsのMiddlewareで認証チェックと地理ベースの
> ルーティングを実装して。
// middleware.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';

export const config = {
  matcher: [
    '/((?!_next/static|_next/image|favicon.ico|public).*)',
  ],
};

export function middleware(request: NextRequest) {
  const { pathname, searchParams } = request.nextUrl;
  const geo = request.geo;

  // 認証チェック
  const token = request.cookies.get('session-token')?.value;
  if (pathname.startsWith('/dashboard') && !token) {
    return NextResponse.redirect(new URL('/login', request.url));
  }

  // 地理ベースのルーティング
  if (pathname === '/' && geo?.country) {
    const country = geo.country;
    if (country === 'JP') {
      return NextResponse.rewrite(new URL('/ja', request.url));
    }
  }

  // セキュリティヘッダーの追加
  const response = NextResponse.next();
  response.headers.set('X-Frame-Options', 'DENY');
  response.headers.set('X-Content-Type-Options', 'nosniff');
  response.headers.set(
    'Strict-Transport-Security',
    'max-age=31536000; includeSubDomains'
  );

  return response;
}

Edge API Routeの作成

> Edge Runtimeで動作するAPIエンドポイントを作って。
> KVストアを使ったレート制限も実装して。
// app/api/data/route.ts
export const runtime = 'edge';

export async function GET(request: Request) {
  const { searchParams } = new URL(request.url);
  const query = searchParams.get('q') || '';

  // レート制限チェック
  const ip = request.headers.get('x-forwarded-for') || 'unknown';
  const isAllowed = await checkRateLimit(ip);
  if (!isAllowed) {
    return new Response(
      JSON.stringify({ error: 'Rate limit exceeded' }),
      { status: 429, headers: { 'Content-Type': 'application/json' } }
    );
  }

  // Edge KVからデータ取得
  const data = await fetchData(query);

  return new Response(JSON.stringify(data), {
    headers: {
      'Content-Type': 'application/json',
      'Cache-Control': 's-maxage=60, stale-while-revalidate=300',
    },
  });
}

async function checkRateLimit(ip: string): Promise<boolean> {
  // Vercel KV(Upstash Redis)を使用
  const key = `rate-limit:${ip}`;
  const kv = await import('@vercel/kv');
  const current = await kv.default.incr(key);

  if (current === 1) {
    await kv.default.expire(key, 60); // 60秒ウィンドウ
  }

  return current <= 100; // 60秒あたり100リクエスト
}

A/Bテストの実装

> Edge FunctionsでA/Bテストのルーティングを実装して。
> Cookieベースのバケット割り当てで。
// middleware.ts (A/Bテスト部分)
function abTest(request: NextRequest): NextResponse {
  const bucket = request.cookies.get('ab-bucket')?.value;
  let variant: 'a' | 'b';

  if (bucket === 'a' || bucket === 'b') {
    variant = bucket;
  } else {
    variant = Math.random() < 0.5 ? 'a' : 'b';
  }

  const url = request.nextUrl.clone();

  if (url.pathname === '/landing') {
    url.pathname = `/landing/${variant}`;
    const response = NextResponse.rewrite(url);

    if (!bucket) {
      response.cookies.set('ab-bucket', variant, {
        maxAge: 60 * 60 * 24 * 30, // 30日
        httpOnly: true,
      });
    }

    return response;
  }

  return NextResponse.next();
}

OGP画像の動的生成

> Edge Functionsで動的OGP画像を生成するAPIを作って。
// app/api/og/route.tsx
import { ImageResponse } from 'next/og';

export const runtime = 'edge';

export async function GET(request: Request) {
  const { searchParams } = new URL(request.url);
  const title = searchParams.get('title') || 'Default Title';

  return new ImageResponse(
    (
      <div
        style={{
          display: 'flex',
          flexDirection: 'column',
          justifyContent: 'center',
          alignItems: 'center',
          width: '100%',
          height: '100%',
          background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
          color: 'white',
          padding: '40px',
        }}
      >
        <h1 style={{ fontSize: 60, textAlign: 'center' }}>{title}</h1>
      </div>
    ),
    { width: 1200, height: 630 }
  );
}

Edge Runtimeの制約

Edge Runtimeでは使えないNode.js APIがある点に注意が必要です。fspathchild_process などは利用できません。Claude Codeに制約を伝えれば、Edge互換なコードを生成してくれます。

まとめ

Vercel Edge Functionsを使えば、超低レイテンシーなAPIやミドルウェアを世界中で実行できます。Claude Codeを活用すれば、Edge Runtime特有の実装パターンも効率的に習得できます。エッジコンピューティング入門A/Bテスト実装も参考にしてください。

Vercel Edge Functionsの詳細はVercel公式ドキュメントを参照してください。

#Claude Code #Vercel #Edge Functions #エッジコンピューティング #サーバーレス