Porkbun Integration Guide
What is Porkbun?
Header auth, GET reads, scoped keys. Check `warnings` on every write, because a SUCCESS can be a no-op.
Send X-API-Key and X-Secret-API-Key to api.porkbun.com/api/json/v3, plus an Idempotency-Key on every POST. Run step 0 first: zone-check.mts or GET /domain/getNs. If the nameservers aren't *.porkbun.com, edit in Cloudflare instead. To converge a record, call retrieveByNameType, then editByNameType or create (/dns/edit has been partial since v3.48). Handle DUPLICATE_RECORD (adopt existingId), RECORD_CONFLICT and SPF_CONFLICT. Undo with /dns/history and /dns/restore. Rate limits: checkDomain 10/10 s, bulk 25 names per call, registrations 1/s. Each order is capped at $100 and API spend at $100/month by default. The official MCP (@porkbunllc/mcp-server 0.52.0, or the hosted mcp.porkbun.com/mcp) exposes the whole API. Give it a 'Manage, but no purchases' key.
Five Porkbun primitives
Registrar first, DNS host only sometimes. Find out which before you write.
██████╗ ██████╗ ██████╗ ██╗ ██╗██████╗ ██╗ ██╗███╗ ██╗
██╔══██╗██╔═══██╗██╔══██╗██║ ██╔╝██╔══██╗██║ ██║████╗ ██║
██████╔╝██║ ██║██████╔╝█████╔╝ ██████╔╝██║ ██║██╔██╗ ██║
██╔═══╝ ██║ ██║██╔══██╗██╔═██╗ ██╔══██╗██║ ██║██║╚██╗██║
██║ ╚██████╔╝██║ ██║██║ ██╗██████╔╝╚██████╔╝██║ ╚████║
╚═╝ ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚═════╝ ╚═════╝ ╚═╝ ╚═══╝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).
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:
- Headers (preferred for GET):
X-API-Key+X-Secret-API-Key. Header auth applies only when the body carries no credentials. - JSON body:
apikey+secretapikey. The field issecretapikey, notsecretkey. A misspelt field givesMISSING_SECRETAPIKEY, which looks like a bad key.
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 600DNSSEC
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 .statusSSL 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.
- For Vercel, Cloudflare or Netlify hosting, the host issues its own certificate. You don't need this bundle.
- Use it only for self-managed servers on a Porkbun-served zone. The response contains a private key, so never log it, and write it to a file with
0600permissions.
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 .statusgetNsreads live from the registry. The set comes back in any order, so compare it as a set.- To return a domain to Porkbun DNS, set Porkbun's nameservers (for example
maceio,curitiba,salvador,fortaleza.ns.porkbun.com). The Porkbun zone you kept editing is what starts serving. - To move a domain into your own Cloudflare account without hand-copying records, use the connector. A human authorizes once at
porkbun.com/account/connectCloudflare. Then callGET /cloudflare/inventory→POST /cloudflare/connect(supportsdryRun) → poll/cloudflare/getQueue, or subscribe to thecloudflare.connect.completedwebhook.POST /cloudflare/rollback/{domain}undoes a move. - Glue (vanity nameservers on a subdomain):
getGlue,createGlue/{domain}/{sub},updateGlue,deleteGlue, each with anipsarray.
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 .pricingLive 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}"
}
}
}
}- The read tools include
ping,check_domain,get_pricing,list_domains,get_nameservers,list_dns_records,scan_dns_records,list_dnssec_records,list_url_forwards,get_ssl_bundleandget_api_settings.search_docs,read_docandlist_doc_topicswork without keys, which is handy for API research. Write tools cover the rest of the API, and every write attaches anIdempotency-Keyautomatically. - Money parameters end in
_cents(cost_cents: 1108= $11.08). - codeAmani defaults: give the MCP a key scoped to Manage, but no purchases and to the specific domains it manages, or use the
/mcp/no-purchaseshosted endpoint. Do not setPORKBUN_X402_PRIVATE_KEY, which lets the server sign USDC payments by itself. The MCP's DNS tools have the same Cloudflare blind spot as the API: checkwarningsand run step 0 first.
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 keyNon-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/nullWorkflow 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
- Registrar vs DNS host. Porkbun is the registrar for the codeAmani portfolio. DNS for
codeamanilabs.organd 23 other account domains is served by Cloudflare (2026-10-20 audit).thumbs.is an R2 custom domain (so the zone must stay on Cloudflare), andtech-stack.is an A record to Vercel76.76.21.21. Edit those in Cloudflare. Use the Porkbun API for registrar tasks (nameservers, DS records, auto-renew, locks, contacts) and for the zones Porkbun actually serves. Portfolio strategy, renewal budgeting and the monthlyportfolio-audit.mtslive in the domain-portfolio guide. Keep both guides consistent. - Secrets stay server-side. Both keys are secrets. Agents get a dedicated key with Manage, but no purchases, a domain allowlist and, where the egress IP is known, an IP allowlist. Never paste keys into chat or commit them. Run gitleaks before pushing.
- Purchases need a human. Registrations, renewals, closeouts and top-ups are
requiresConfirmationoperations. Always dry-run, show thecost, and get approval. Keep the $100/month default spend limit unless a human raises it. - Payments for products: Stripe is the default rail for codeAmani apps. M-Pesa/Daraja applies only to Kenya-targeted projects. Porkbun's own
payWith: "card"/"usdc"options pay Porkbun for domains. They are not a payment rail for codeAmani customers. - AI routing: Claude drives DNS/registrar automation (reasoning and code). Use the official Porkbun MCP rather than hand-written tool wrappers, and ground answers with its credential-free
search_docstool or this guide. - Kenya-targeted projects: Porkbun does not sell
.ke/.co.ke. Register those through a KeNIC-accredited registrar and track them indomain-portfolio/examples/portfolio.json. Porkbun DNS can still serve the zone if you delegate it there. - Mail: the local-only Porkbun webmail client is
packages/mail(IMAPimap.porkbun.com:993, SMTPsmtp.porkbun.com). It must never be deployed to Vercel. See that package for details. This guide does not cover it.