Claude Code के साथ Vercel Edge Functions Usage Guide
Claude Code का उपयोग करके vercel edge functions usage guide सीखें। Practical tips और code examples शामिल हैं।
Vercel Edge Functionsको Claude Code सेimplement करना
Vercel Edge Functionsは、世界मेंのエッジロケーションでcodeを実行できるserverレス環境 है।コールドスタートがほぼなく、userに近い場所でprocessingを行えるため、超低レイテンシーなAPIやmiddleware build किया जा सकता है。Claude Code का उपयोग करके、Edge Runtime特有の制約を考慮したimplementationもスムーズに進められ है।
Middlewareのimplementation
> Next.jsのMiddlewareでauthenticationcheckと地理ベースの
> routingをimplement करो。
// 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;
// authenticationcheck
const token = request.cookies.get('session-token')?.value;
if (pathname.startsWith('/dashboard') && !token) {
return NextResponse.redirect(new URL('/login', request.url));
}
// 地理ベースのrouting
if (pathname === '/' && geo?.country) {
const country = geo.country;
if (country === 'JP') {
return NextResponse.rewrite(new URL('/ja', request.url));
}
}
// securityheaderのadd
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のcreate
> Edge Runtimeで動作するAPIendpointを作って。
> KVストアを使ったレート制限もimplement करो。
// 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') || '';
// レート制限check
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 सेdatafetch
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秒あたり100request
}
A/Btestのimplementation
> Edge FunctionsでA/Btestのroutingをimplement करो。
> Cookieベースのバケット割り当てで。
// middleware.ts (A/Btest部分)
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画像の動的generate
> Edge Functionsで動的OGP画像 generateする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がある点にध्यानがज़रूरी है।fs、path、child_process आदिは利用でき नहीं है।Claude Codeに制約を伝えれば、Edge互換なcode generateしてくれ है।
Summary
Vercel Edge Functionsを使えば、超低レイテンシーなAPIやmiddlewareを世界मेंで実行でき है।Claude Code का लाभ उठाकर、Edge Runtime特有のimplementationpatternもefficiently習得でき है।エッジコンピューティング入門やA/Btestimplementationभी reference के लिए देखें。
Vercel Edge Functionsके details के लिएVercelofficial documentationをदेखें。
Related Posts
Claude Code से अपने Side Projects को Supercharge कैसे करें [Examples के साथ]
Claude Code से personal development projects को dramatically speed up करना सीखें। Real-world examples और idea से deployment तक practical workflow शामिल है।
Claude Code से Refactoring कैसे Automate करें
Claude Code से efficiently code refactoring automate करना सीखें। Real-world projects के लिए practical prompts और concrete refactoring patterns शामिल हैं।
Claude Code के साथ Complete CORS Configuration Guide
Claude Code का उपयोग करके complete CORS configuration guide सीखें। Practical tips और code examples शामिल हैं।