Claude Code के साथ Leveraging Edge Computing
Claude Code का उपयोग करके leveraging edge computing सीखें। Practical tips और code examples शामिल हैं।
エッジコンピューティング क्या है
エッジコンピューティングは、userに地理的に近いserverでprocessingを実行する技術 है।レイテンシを大幅に削減し、fastなresponseを実現でき है।Claude Code का उपयोग करके、エッジsupportのapplication build करें।
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が自動で付与するheader
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ストア सेcachefetch
const cached = await env.MY_KV.get(cacheKey);
if (cached) {
return Response.json(JSON.parse(cached), {
headers: { "X-Cache": "HIT" },
});
}
// オリジン सेdatafetch
const data = await fetch("https://api.example.com/data").then(
(r) => r.json()
);
// KVにcache(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);
// エッジcachesettings
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,
};
}
エッジでのauthenticationprocessing
// 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) {
// 公開pathはスキップ
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);
// requestheaderにuser情報を付与
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/Btest
export const runtime = "edge";
export async function middleware(request: NextRequest) {
// 既存のバリアント割り当て confirm
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,
});
// バリアントに応じたpageにリlight
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 सेのutilization
エッジfunctionのimplementationをClaude Code को requestする例 है।performanceoptimizationはSSR vs SSG比較、cache戦略はRediscache設計もदेखें。
Vercel Edge FunctionsでAPIをimplement करो。
- 地域別のコンテンツ出し分け
- エッジでのJWT検証
- KVストアでのcache
- A/Btestのmiddleware
Cloudflare Workersके details के लिएCloudflare Workersofficial documentationをदेखें。Claude Codeのuse करने का तरीकाはofficial documentationでconfirmでき है।
Summary
エッジコンピューティングはレイテンシ削減とスケーラビリティの両立を実現し है।Claude Code का उपयोग करके、プラットform固有のAPIやベストプラクティスを理解したऊपरでエッジsupportcodeをefficientlyimplementationでき है।
Related Posts
Claude Code Hooks में Mastery: Auto-Format, Auto-Test, और बहुत कुछ
Claude Code hooks से auto-formatting और auto-testing setup करना सीखें। Practical configuration examples और real-world use cases शामिल हैं।
Claude Code MCP Server Setup और Practical Use Cases
Claude Code की MCP server capabilities की comprehensive guide। External tools connect करना, servers configure करना, और real-world integration examples सीखें।
CLAUDE.md लिखने की Complete Guide: Project Configuration की Best Practices
Effective CLAUDE.md files लिखने की thorough guide। अपना tech stack, conventions, और project structure communicate करना सीखें और Claude Code की output quality maximize करें।