Use Cases

Vercel Edge Functions Usage Guide: Claude Code 활용 가이드

vercel edge functions usage guide: Claude Code 활용. 실용적인 팁과 코드 예시를 포함합니다.

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 #edge computing #serverless