Advanced (अपडेट: 2/6/2026)

Claude Code के साथ Edge Computing: Workers, cache और region routing

Claude Code से Edge runtime डिजाइन करें: Workers, region routing, cache keys, pitfalls और verification commands.

Claude Code के साथ Edge Computing: Workers, cache और region routing

Edge computing का मतलब पूरे backend को user के पास ले जाना नहीं है। इसका मतलब है कि request के application तक पहुंचने से पहले, user के नजदीक छोटे फैसले किए जाएं। जैसे country के हिसाब से redirect, छोटा cache, A/B test bucket, या preview page के लिए हल्का auth gate.

Edge runtime को performance का जादुई बटन समझना खतरनाक है। यह normal Node.js server जैसा नहीं होता। कौन से APIs मिलेंगे, code कितनी देर चलेगा, कौन से packages चलेंगे, request metadata कैसा होगा और cache कैसे काम करेगा, इन सबकी सीमा होती है। अगर आप Claude Code से सिर्फ “इसे edge-ready बना दो” कहेंगे, तो वह Node-only API मिला सकता है, cache key गलत बना सकता है, या country code को billing और permission का proof मान सकता है।

यह guide 2 जून 2026 को देखी गई official documentation पर आधारित है। काम करते समय Cloudflare Workers, Workers Request API, Workers Cache API, Vercel Edge Runtime, Deno Deploy runtime और Claude Code overview साथ रखें। Platform-specific पढ़ाई के लिए Cloudflare Workers with Claude Code और Vercel Edge Functions with Claude Code भी देखें।

पहले तय करें कि Edge पर क्या चलेगा

सबसे पहला design decision है: entry decision और business logic अलग करें। अगर फैसला URL, headers, cookies या छोटे request body से हो सकता है, तो वह Edge के लिए अच्छा candidate है। अगर काम में deep database read, लंबी LLM call, image processing, PDF generation, payment settlement या background workflow चाहिए, तो उसे normal API या queue में रखें।

Use caseEdge पर रखने का कारणबाहर रखना बेहतर
Country या language routingCountry code या language header से entry जल्दी चुनी जा सकती हैTax, invoice, inventory
Short cachePublic response user के पास serve हो सकता हैDB update, regeneration job
A/B assignmentCookie से page render से पहले bucket चुना जा सकता हैStatistics और revenue decision
Light auth gatePreview और admin path जल्दी block हो सकते हैंSession creation, permission audit
Webhook entry checkछोटी signature check bad request रोक सकती हैPayment, email, retry

इस table को Claude Code prompt में डालें। इससे generated code review करना आसान होगा, क्योंकि Edge work और origin work पहले से अलग होंगे।

flowchart LR
  User["User request"] --> Edge["Edge runtime"]
  Edge --> Geo["Country / language branch"]
  Edge --> Cache["Short cache"]
  Edge --> Gate["Light auth gate"]
  Edge --> Origin["Origin API / database"]
  Origin --> Queue["Queue or background work"]

Claude Code को देने वाला prompt

Edge implementation में prompt सिर्फ “fast बनाओ” नहीं होना चाहिए। उसे constraints बताने चाहिए। Claude Code code जल्दी लिखता है, लेकिन cache keys, region branch, secrets और verification commands अगर requirements में नहीं हैं, तो छूट सकते हैं।

Implement a small Cloudflare Workers + TypeScript Edge runtime API.

Files:
- wrangler.toml
- src/index.ts

Requirements:
- GET /health returns JSON
- GET /api/edge-content returns locale and CTA copy based on country
- Use request.cf.country when Cloudflare provides it
- Also support a CF-IPCountry header for local curl verification
- Cache each locale separately for 60 seconds with the Cache API
- Return cache hit/miss through X-Edge-Cache
- Use Web APIs such as Request, Response, URL, and crypto; do not use Node-only APIs
- Include at least three curl or build commands that verify the behavior

Do not:
- Use pseudocode
- Hard-code API tokens or secrets
- Treat country code as proof for billing, permissions, or legal decisions

कुछ शब्द पहले समझा दें। runtime वह environment है जहां code चलता है। cache key cache से response ढूंढने का नाम है। colo Cloudflare data center का identifier है। ऐसी छोटी व्याख्या Claude Code को beginner-friendly comments और handoff लिखने में मदद करती है।

Cloudflare Workers का copy-paste example

यह Worker जानबूझकर छोटा रखा गया है। /api/edge-content Cloudflare metadata या local test header से country पढ़ता है, उसे locale में बदलता है और Cache API से response को 60 seconds cache करता है। Local testing के लिए CF-IPCountry header curl में दिया जा सकता है।

name = "claude-edge-router"
main = "src/index.ts"
compatibility_date = "2026-06-02"

[vars]
DEFAULT_LOCALE = "en"
// src/index.ts
export interface Env {
  DEFAULT_LOCALE: string;
}

type Locale = "ja" | "en" | "zh" | "ko" | "es" | "fr" | "de" | "pt" | "hi" | "id";

type CfRequest = Request & {
  cf?: {
    country?: string;
    colo?: string;
    city?: string;
  };
};

const SUPPORTED_LOCALES = new Set<Locale>([
  "ja",
  "en",
  "zh",
  "ko",
  "es",
  "fr",
  "de",
  "pt",
  "hi",
  "id",
]);

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

    if (url.pathname === "/health") {
      return json({ ok: true, runtime: "cloudflare-workers" });
    }

    if (url.pathname === "/api/edge-content") {
      return handleEdgeContent(request, env, ctx);
    }

    return json({ error: "not_found" }, 404);
  },
} satisfies ExportedHandler<Env>;

async function handleEdgeContent(
  request: Request,
  env: Env,
  ctx: ExecutionContext
): Promise<Response> {
  const url = new URL(request.url);
  const country = getCountry(request);
  const locale = localeFromCountry(country, env.DEFAULT_LOCALE);
  const cacheKey = buildCacheKey(request, locale);
  const cached = await caches.default.match(cacheKey);

  if (cached) {
    return withHeaders(cached, {
      "X-Edge-Cache": "HIT",
      "X-Edge-Locale": locale,
    });
  }

  const body = {
    locale,
    country,
    colo: getColo(request),
    path: url.pathname,
    cta: localizedCta(locale),
    generatedAt: new Date().toISOString(),
  };

  const response = json(body, 200, {
    "Cache-Control": "public, max-age=0, s-maxage=60, stale-while-revalidate=300",
    "X-Edge-Cache": "MISS",
    "X-Edge-Locale": locale,
  });

  ctx.waitUntil(caches.default.put(cacheKey, response.clone()));
  return response;
}

function buildCacheKey(request: Request, locale: Locale): Request {
  const url = new URL(request.url);
  url.search = "";
  url.pathname = `/__edge-cache/${locale}${url.pathname}`;
  return new Request(url.toString(), { method: "GET" });
}

function getCountry(request: Request): string {
  const cf = (request as CfRequest).cf;
  return (
    request.headers.get("CF-IPCountry") ||
    request.headers.get("x-country") ||
    cf?.country ||
    "US"
  ).toUpperCase();
}

function getColo(request: Request): string {
  return (request as CfRequest).cf?.colo || "local";
}

function localeFromCountry(country: string, fallback: string): Locale {
  const normalizedFallback = SUPPORTED_LOCALES.has(fallback as Locale)
    ? (fallback as Locale)
    : "en";

  switch (country) {
    case "JP":
      return "ja";
    case "CN":
    case "TW":
    case "HK":
      return "zh";
    case "KR":
      return "ko";
    case "ES":
    case "MX":
    case "AR":
      return "es";
    case "FR":
      return "fr";
    case "DE":
      return "de";
    case "BR":
    case "PT":
      return "pt";
    case "IN":
      return "hi";
    case "ID":
      return "id";
    default:
      return normalizedFallback;
  }
}

function localizedCta(locale: Locale): string {
  const messages: Record<Locale, string> = {
    ja: "Claude Code教材を見る",
    en: "Explore Claude Code templates",
    zh: "查看 Claude Code 教材",
    ko: "Claude Code 템플릿 보기",
    es: "Ver plantillas de Claude Code",
    fr: "Voir les modèles Claude Code",
    de: "Claude Code Vorlagen ansehen",
    pt: "Ver modelos de Claude Code",
    hi: "Claude Code टेम्पलेट देखें",
    id: "Lihat template Claude Code",
  };
  return messages[locale];
}

function json(data: unknown, status = 200, headers: HeadersInit = {}): Response {
  return new Response(JSON.stringify(data, null, 2), {
    status,
    headers: {
      "Content-Type": "application/json; charset=utf-8",
      "X-Content-Type-Options": "nosniff",
      ...headers,
    },
  });
}

function withHeaders(response: Response, headers: Record<string, string>): Response {
  const next = new Response(response.body, response);
  for (const [key, value] of Object.entries(headers)) {
    next.headers.set(key, value);
  }
  return next;
}

सबसे जरूरी बात cache key है। इसमें locale शामिल है। अगर यह नहीं होगा, तो Japanese CTA किसी English या Hindi visitor को मिल सकता है। Query string हटाने से utm_source जैसे tracking parameters cache को बेकार entries में नहीं तोड़ते।

Vercel और Deno तक pattern बढ़ाना

Vercel Edge Middleware page render से पहले headers सेट कर सकता है, A/B bucket रख सकता है और regional entry redirect कर सकता है। लेकिन Edge Runtime की सीमाएं देखें और ऐसे packages न इस्तेमाल करें जिन्हें Node-only APIs चाहिए।

// middleware.ts
import { NextRequest, NextResponse } from "next/server";

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

export function middleware(request: NextRequest) {
  const country = request.headers.get("x-vercel-ip-country") || "US";
  const bucket = request.cookies.get("edge_bucket")?.value || chooseBucket();
  const response = NextResponse.next();

  response.headers.set("x-edge-country", country);
  response.headers.set("x-edge-bucket", bucket);
  response.cookies.set("edge_bucket", bucket, {
    maxAge: 60 * 60 * 24 * 30,
    sameSite: "lax",
    secure: true,
  });

  if (country === "JP" && request.nextUrl.pathname === "/pricing") {
    return NextResponse.redirect(new URL("/jp/pricing", request.url));
  }

  return response;
}

function chooseBucket(): "a" | "b" {
  const bytes = new Uint8Array(1);
  crypto.getRandomValues(bytes);
  return bytes[0] < 128 ? "a" : "b";
}

Deno Deploy में भी Request और Response वाली Web API style रखें। Cloudflare-specific field जैसे request.cf को सीधे copy न करें। हर provider के headers और environment variables अलग हो सकते हैं, इसलिए prompt में साफ लिखें।

// main.ts
Deno.serve((request: Request) => {
  const url = new URL(request.url);
  const country = request.headers.get("x-country") || "US";

  if (url.pathname !== "/api/edge-content") {
    return Response.json({ error: "not_found" }, { status: 404 });
  }

  return Response.json({
    runtime: "deno-deploy",
    country,
    message: country === "JP" ? "Japan entry" : "Default edge entry",
  });
});

Verification commands

Edge code के लिए types, local HTTP, region branch, cache headers और deploy readiness check करें। Claude Code से कहें कि वह handoff में ये commands और expected result लिखे।

npm create cloudflare@latest claude-edge-router -- --type=hello-world
cd claude-edge-router
npm install -D typescript wrangler
npx wrangler types
npx tsc --noEmit
npx wrangler dev

दूसरे terminal में curl चलाएं।

curl -i http://127.0.0.1:8787/health
curl -i -H "CF-IPCountry: JP" http://127.0.0.1:8787/api/edge-content
curl -i -H "CF-IPCountry: US" http://127.0.0.1:8787/api/edge-content
curl -i -H "CF-IPCountry: JP" "http://127.0.0.1:8787/api/edge-content?utm_source=test"
npx wrangler deploy --dry-run

Expected behavior सरल है। Same locale और path की पहली request X-Edge-Cache: MISS देगी, अगली HIT देगी। JP ja बनेगा, US en बनेगा, और tracking query अलग cache entry नहीं बनाएगी।

आम pitfalls

पहला pitfall है Edge पर बहुत ज्यादा काम रखना। लंबी LLM calls, heavy ORM work, PDF, image conversion और complex billing आम तौर पर origin API या queue में बेहतर रहते हैं। Edge को entry gate रखें, पूरा backend नहीं।

दूसरा pitfall है cache key का गलत design। अगर locale, login state, price display या experiment bucket response बदलते हैं, तो वे key में होने चाहिए। अगर utm_* या timestamp जैसा noise key में आ गया, तो cache hit कम होंगे।

तीसरा pitfall है geography पर जरूरत से ज्यादा भरोसा करना। request.cf.country और x-vercel-ip-country default experience के लिए ठीक हैं, लेकिन tax, age, permission या billing proof नहीं हैं। VPN, company proxy और CDN routing country बदल सकते हैं।

चौथा pitfall है Claude Code को सिर्फ provider name देना। “Workers में बना दो” से यह नहीं पता चलता कि Cache API, KV, D1, Vercel compatibility या origin fallback चाहिए। Boundary तय करने के लिए Claude Code serverless functions और performance optimization guide भी देखें।

Revenue path और अगला कदम

Multilingual content site में Edge runtime revenue path भी सुधार सकता है। आप free PDF की copy भाषा के हिसाब से दिखा सकते हैं, reader को सही language CTA पर भेज सकते हैं, ad parameters को cache से पहले normalize कर सकते हैं और template CTA fast रख सकते हैं।

Reusable materials के लिए ClaudeCodeLab products देखें। Team में prompts, review rules और Edge/Node boundary standardize करनी हो तो Claude Code training and consulting देखें। जल्दी शुरुआत के लिए free cheat sheet ठीक है।

वास्तव में आजमाया गया परिणाम

इस update में Masa ने local Workers sample में CF-IPCountry: JP और CF-IPCountry: US बदलकर locale, X-Edge-Cache और tracking parameters हटाने वाली cache key देखी। Useful finding यह था कि local verification में test headers को request.cf.country से पहले पढ़ना चाहिए, वरना repeated checks में country branch अटकी हुई लग सकती है। Cache key भी /__edge-cache/${locale}${pathname} रखी गई ताकि regional content mix न हो। Claude Code को brief देते समय header priority, geo branch और cache key को साथ review करने को कहें।

Summary

Edge computing का मतलब सब कुछ Edge पर भेजना नहीं है। मतलब है छोटे request decisions user के पास करना और heavy work तथा final decisions normal API में रखना। Claude Code को runtime limits, cache-key rules, region branches और verification commands शुरुआत में दें। इससे implementation fast भी होगी और review भी आसान होगा।

#Claude Code #edge computing #Cloudflare Workers #Vercel #performance
मुफ़्त

मुफ़्त PDF: Claude Code cheatsheet

Email डालें और commands, review habits तथा safe workflow वाली एक-page PDF पाएँ.

हम आपका data सुरक्षित रखते हैं और spam नहीं भेजते.

Masa

लेखक के बारे में

Masa

Claude Code workflow और team adoption पर काम करने वाला engineer.