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

Claude Code के साथ Vercel Edge Functions की व्यावहारिक गाइड

Claude Code और Vercel Edge Runtime: Middleware, signed webhook, A/B test, cache तैयारी और production pitfalls।

Claude Code के साथ Vercel Edge Functions की व्यावहारिक गाइड

Edge को सिर्फ “तेज” लगने की वजह से न चुनें

Vercel Edge Functions, Edge Runtime में JavaScript चलाती हैं। यह सामान्य Node.js process नहीं है। इसमें Web APIs जैसे fetch, Request, Response, URL, TextEncoder और Web Crypto मिलते हैं। आसान भाषा में, Edge Runtime आपके app के दरवाजे पर बैठा एक हल्का guard है। यह request की URL, headers, cookies और छोटा body देखकर तुरंत निर्णय ले सकता है।

Claude Code यहाँ उपयोगी है क्योंकि असली Edge काम केवल एक file में नहीं होता। Country redirect में middleware.ts, Vercel headers और local बनाम preview अंतर आते हैं। A/B test में cookie, request header, analytics और rollback आते हैं। Signed webhook में raw body, HMAC signature, environment variables, body size limit और internal API forwarding शामिल होते हैं। इसलिए Claude Code से केवल “Edge function बना दो” न कहें; उसे runtime boundary, tests, logs और production difference भी review करने को कहें।

जून 2026 तक, Vercel Edge Runtime documentation Edge को हर workload का solution नहीं बताती। उसमें supported APIs, limits, regions और कुछ cases में Node.js बेहतर होने की बात है। Next.js के Middleware और Route Handlers भी Web Request और Response APIs पर आधारित हैं। Practical rule यह है: छोटे request decisions Edge में रखें, durable work backend में रखें।

Webhook retry और idempotency के लिए Claude Code webhook implementation देखें। Performance और cache की बड़ी तस्वीर के लिए Claude Code performance optimization उपयोगी है।

पांच practical use cases

Edge तब अच्छा है जब जवाब request metadata या छोटे signed payload से मिल जाए। Heavy dependency, long database transaction, private network connection, large upload या long LLM stream को Edge में रखना risk बढ़ाता है।

Use caseEdge क्यों ठीक हैNode.js या backend में क्या रखें
Country redirectx-vercel-ip-country से entry पर route चुन सकते हैंuser preference, pricing rule, account policy
A/B testcookie से stable bucket बनता हैanalytics aggregation, experiment decision
Light auth/signatureगलत preview या webhook request जल्दी block होती हैsession, roles, audit logs
Cache preprocessingURL और query normalize होकर cache key stable रहती हैrevalidation, inventory, costly computation
Webhook receiveछोटा raw body verify करके internal API को भेज सकते हैंpayment finalization, email, retry, CRM

यह table Claude Code prompt में भी डालें। जब आप पहले से बता देते हैं कि Edge में क्या रहेगा और बाहर क्या रहेगा, तब generated code में fs, Buffer, direct DB client या secret logging आने की संभावना कम होती है।

flowchart LR
  A["User request"] --> B["Next.js Middleware"]
  B --> C{"Small decision"}
  C --> D["Country redirect"]
  C --> E["A/B bucket"]
  C --> F["Light auth"]
  B --> G["Edge Route Handler"]
  G --> H["HMAC signature check"]
  H --> I["Internal API or queue"]

इस diagram में Edge full backend नहीं है। Middleware request को classify करता है। Route Handler छोटा signed webhook verify करता है। Durable state, retry और side effects internal API, queue या worker में जाते हैं।

Copy-paste Next.js Middleware

यह middleware.ts country redirect, A/B bucket, preview gate और security headers को साथ दिखाता है। यह request.geo के बजाय Vercel headers इस्तेमाल करता है, ताकि Next.js version और local environment के फर्क से कम break हो। Local में x-vercel-ip-country आम तौर पर नहीं होता, इसलिए country behavior को Preview Deployment पर check करें।

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

const PUBLIC_FILE = /\.(?:png|jpg|jpeg|gif|svg|webp|ico|css|js|map|txt)$/i;
const SECRET_HEADER = "x-edge-shared-secret";

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

function chooseBucket(request: NextRequest): "a" | "b" {
  const current = request.cookies.get("ab_bucket")?.value;
  if (current === "a" || current === "b") return current;

  const random = new Uint8Array(1);
  crypto.getRandomValues(random);
  return random[0] < 128 ? "a" : "b";
}

function localeFromCountry(country: string | null): string | null {
  switch (country?.toUpperCase()) {
    case "JP":
      return "ja";
    case "KR":
      return "ko";
    case "CN":
    case "TW":
    case "HK":
      return "zh";
    case "BR":
      return "pt";
    case "ES":
    case "MX":
      return "es";
    default:
      return null;
  }
}

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

  if (PUBLIC_FILE.test(pathname)) {
    return NextResponse.next();
  }

  if (pathname === "/") {
    const country = request.headers.get("x-vercel-ip-country");
    const locale = localeFromCountry(country);
    if (locale) {
      return NextResponse.redirect(new URL(`/${locale}/`, request.url), 307);
    }
  }

  if (pathname.startsWith("/beta")) {
    const bucket = chooseBucket(request);
    const requestHeaders = new Headers(request.headers);
    requestHeaders.set("x-ab-bucket", bucket);

    const response = NextResponse.next({
      request: { headers: requestHeaders },
    });

    if (!request.cookies.has("ab_bucket")) {
      response.cookies.set("ab_bucket", bucket, {
        maxAge: 60 * 60 * 24 * 30,
        path: "/",
        sameSite: "lax",
        secure: request.nextUrl.protocol === "https:",
      });
    }

    return response;
  }

  if (pathname.startsWith("/preview")) {
    const expected = process.env.EDGE_SHARED_SECRET;
    const actual = request.headers.get(SECRET_HEADER);
    if (!expected || actual !== expected) {
      return NextResponse.redirect(new URL("/login", request.url), 307);
    }
  }

  const response = NextResponse.next();
  response.headers.set("x-content-type-options", "nosniff");
  response.headers.set("referrer-policy", "strict-origin-when-cross-origin");
  return response;
}

इस sample में boundaries जानबूझकर छोटी हैं। A/B test केवल bucket assign करता है, winner नहीं चुनता। Preview gate full authentication नहीं है। Country redirect केवल / पर चलता है ताकि redirect loop न बने।

Edge Route Handler में signed webhook verify करना

HMAC का मतलब है कि sender और receiver एक secret share करते हैं, और original body से signature बनाते हैं। Edge Runtime में Node.js का crypto.createHmac या Buffer नहीं मानना चाहिए; Web Crypto और TextEncoder का उपयोग करें।

// app/api/webhooks/provider/route.ts
export const runtime = "edge";
export const preferredRegion = ["iad1", "hnd1"];

const MAX_BODY_BYTES = 256_000;

function hexToBytes(hex: string): Uint8Array {
  const clean = hex.replace(/^sha256=/, "").trim();
  if (!/^[0-9a-f]+$/i.test(clean) || clean.length % 2 !== 0) {
    return new Uint8Array();
  }

  const bytes = new Uint8Array(clean.length / 2);
  for (let index = 0; index < clean.length; index += 2) {
    bytes[index / 2] = Number.parseInt(clean.slice(index, index + 2), 16);
  }
  return bytes;
}

async function hmacSha256(secret: string, payload: string): Promise<Uint8Array> {
  const encoder = new TextEncoder();
  const key = await crypto.subtle.importKey(
    "raw",
    encoder.encode(secret),
    { name: "HMAC", hash: "SHA-256" },
    false,
    ["sign"],
  );
  const signature = await crypto.subtle.sign("HMAC", key, encoder.encode(payload));
  return new Uint8Array(signature);
}

function constantTimeEqual(a: Uint8Array, b: Uint8Array): boolean {
  if (a.length !== b.length) return false;

  let diff = 0;
  for (let index = 0; index < a.length; index += 1) {
    diff |= a[index] ^ b[index];
  }
  return diff === 0;
}

export async function POST(request: Request) {
  const secret = process.env.WEBHOOK_SECRET;
  const internalOrigin = process.env.INTERNAL_API_ORIGIN;
  const internalToken = process.env.INTERNAL_API_TOKEN;

  if (!secret || !internalOrigin || !internalToken) {
    return Response.json({ error: "server is not configured" }, { status: 500 });
  }

  const contentLength = Number(request.headers.get("content-length") ?? "0");
  if (contentLength > MAX_BODY_BYTES) {
    return Response.json({ error: "payload too large" }, { status: 413 });
  }

  const rawBody = await request.text();
  const rawBodyBytes = new TextEncoder().encode(rawBody);
  if (rawBodyBytes.byteLength > MAX_BODY_BYTES) {
    return Response.json({ error: "payload too large" }, { status: 413 });
  }

  const provided = hexToBytes(request.headers.get("x-signature-sha256") ?? "");
  const expected = await hmacSha256(secret, rawBody);
  if (!constantTimeEqual(provided, expected)) {
    return Response.json({ error: "invalid signature" }, { status: 401 });
  }

  const event = JSON.parse(rawBody) as { id?: string; type?: string };
  if (!event.id || !event.type) {
    return Response.json({ error: "invalid event" }, { status: 400 });
  }

  await fetch(`${internalOrigin}/api/webhook-events`, {
    method: "POST",
    headers: {
      authorization: `Bearer ${internalToken}`,
      "content-type": "application/json",
    },
    body: JSON.stringify({
      id: event.id,
      type: event.type,
      receivedAt: new Date().toISOString(),
    }),
  });

  return Response.json({ ok: true });
}

Order बहुत जरूरी है: size limit, raw body read, signature verify, JSON parse, फिर event forward। Payment, email और retry को internal service में रखें क्योंकि वहाँ idempotency संभालना आसान है।

Claude Code review prompt और test

Claude Code को runtime rules साफ लिखें:

Review this Next.js Edge implementation.

Scope:
- middleware.ts
- app/api/webhooks/provider/route.ts
- related tests and environment variable names

Check:
- no Node-only APIs such as fs, net, tls, Buffer, or node:crypto in Edge files
- no direct database connection from Edge Runtime
- country redirect does not loop
- A/B bucket is stable by cookie and not written on every request
- webhook verifies the raw body before JSON parsing
- secrets, signatures, cookies, and authorization headers are not logged
- body size and production-only Vercel headers are documented

Return blockers first, then suggested tests.

Local test helper signature बनाने के लिए Node.js इस्तेमाल कर सकता है, क्योंकि वह Edge के अंदर नहीं चलता।

npm run lint
npm run build
vercel dev

BODY='{"id":"evt_123","type":"checkout.completed"}'
SIG=$(node -e "const crypto=require('crypto'); const body=process.argv[1]; console.log('sha256='+crypto.createHmac('sha256', process.env.WEBHOOK_SECRET).update(body).digest('hex'))" "$BODY")

curl -i http://localhost:3000/api/webhooks/provider \
  -X POST \
  -H "content-type: application/json" \
  -H "x-signature-sha256: $SIG" \
  --data "$BODY"

curl -I http://localhost:3000/beta
curl -I http://localhost:3000/preview

Preview Deployment में country headers, HTTPS cookie, redirect loop, logs और region assumptions भी check करें। vercel dev जरूरी है, लेकिन production जैसा पूरा environment नहीं देता।

आम pitfalls

पहला pitfall Node.js APIs का accidental use है। fs, Buffer, crypto.createHmac, native module और TCP database client Edge files में नहीं होने चाहिए।

दूसरा pitfall Edge से direct database connection है। अगर database एक ही region में है, तो request फिर भी वहीं जाएगी और connection pressure बढ़ सकता है।

तीसरा pitfall cold start और region को गलत समझना है। Edge entry latency घटा सकता है, लेकिन remote data को local नहीं बनाता। preferredRegion को logs और metrics से verify करें।

चौथा pitfall secret logging है। Webhook body, signature, cookie, Authorization header और preview secret को clear text में log न करें।

पांचवां pitfall body size और streaming है। Edge छोटे signed requests के लिए अच्छा है, large upload, CSV, image processing या long LLM stream के लिए नहीं।

छठा pitfall local और production difference है। vercel dev Vercel headers, real region, preview logs और secure cookies को पूरी तरह reproduce नहीं करता।

ClaudeCodeLab CTA

Solo project में ये samples prototype के लिए काफी हैं। Team project में असली काम rules बनाना है: कौन से files Edge Runtime use कर सकते हैं, कौन से APIs banned हैं, environment variables कैसे नामित होंगे और Preview Deployment कौन verify करेगा।

ClaudeCodeLab teams को Claude Code rules, CLAUDE.md, Edge Runtime review prompts, webhook verification receipts और Vercel checks बनाने में मदद करता है। Real repository पर यह लागू करना हो तो Claude Code training and consultation से शुरू करें।

असल में आजमाने के बाद

इस structure को आजमाने पर सबसे बड़ा फायदा speed नहीं, clarity था। Middleware redirect, A/B bucket, headers और light blocking तक सीमित रहा। Edge Route Handler ने छोटा signed webhook verify करके event forward किया। Claude Code prompt ने Buffer, raw body verify से पहले JSON parse, local में missing Vercel headers और overly detailed logs जैसे issues जल्दी पकड़े। Edge Functions magic नहीं हैं, लेकिन request boundary छोटी और testable रखी जाए तो production में बहुत काम आती हैं।

#Claude Code #Vercel #Edge Functions #edge computing #serverless
मुफ़्त

मुफ़्त PDF: Claude Code cheatsheet

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

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

Masa

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

Masa

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