# API, provision domains from your server

> Provision custom domains from your server.

Source: https://docs.customdomain.ai/docs/getting-started/api

Use the API when **your server** decides which domains get connected. Think of a
platform that provisions a custom domain per customer, a migration script, or an
internal tool. To let customers connect domains in the browser, use the
[widget](/docs/getting-started/widget) instead.

[Open Keys in console](https://app.customdomain.ai/app/keys)

The base URL is `https://api.customdomain.ai`. Send `Authorization: Bearer cd_live_…`.

Every workspace has a default key. Owners can view it at the top of the
console's **API & SDK** page, with no card on file. It acts with admin authority
and cannot create keys. To make another key, press **Create key** there. Only
admins and owners can. A card on file starts the 14 day free trial; without one
the request is refused with `402 billing_required`. Keys created before the
switch to `cd_` start with `sk_` and keep working.

The Node samples use the built-in `fetch` (Node 18 or newer) and read the key from
`CUSTOMDOMAIN_API_KEY`.

### Pre-flight, and read what it says

```bash
curl -X POST https://api.customdomain.ai/v1/domains:check \
  -H "Authorization: Bearer cd_live_..." -H "Content-Type: application/json" \
  -d '{"domain":"shop.acme.com"}'
```

```js
const res = await fetch("https://api.customdomain.ai/v1/domains:check", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.CUSTOMDOMAIN_API_KEY}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({ domain: "shop.acme.com" }),
});
const check = await res.json();
console.log(check.recommended_rail, check.end_user_automatic, check.blocked_reason);
```

Branch on &#x2A;*`rails`*&#x2A; and &#x2A;*`recommended_rail`**, not on `setup_type`:
`automatic` only means an adapter exists (for GoDaddy that is a Personal Access
Token the user has to create at GoDaddy). `end_user_automatic: true` is the only field that means
"nobody has to type anything". A `blocked_reason` (`unregistered`,
`platform_subdomain`) means stop and tell the user why. `dashboard_url` is
where to send them for manual records. If you supply your own `records`, pass
them here too so conflicts are computed against the real set.

### Create

```bash
curl -X POST https://api.customdomain.ai/v1/connections \
  -H "Authorization: Bearer cd_live_..." -H "Content-Type: application/json" \
  -d '{"domain":"shop.acme.com","application_url":"https://tenant-42.yourapp.com"}'
```

```js
const res = await fetch("https://api.customdomain.ai/v1/connections", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.CUSTOMDOMAIN_API_KEY}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    domain: "shop.acme.com",
    application_url: "https://tenant-42.yourapp.com",
  }),
});
const connection = await res.json(); // 201 when new, 200 when it already existed
console.log(res.status, connection.id, connection.records);
```

`application_url` makes the CustomDomain™ edge serve the domain from that
origin, which needs the Growth plan or above (`402 plan_upgrade_required`
otherwise). Leave it out when your own servers serve the domain.

`201` with the connection and its desired `records`. Re-posting the same
domain returns the existing connection with `200`; if the only existing one is
`failed`, it is revived and returned. Idempotent by design: call it on every
"connect" click.

For records only you know (SES DKIM, verification `TXT`), follow with
`PUT /v1/connections/{id}/records` (see [Bring your own records](/docs/dns/bring-your-own-records)).

### Apply, optional

If you hold a provider credential for the zone, write the records yourself.
The body takes `credential` as an object with the scoped `token`, used once and
never stored, and `records`, the set to write: send the `records` from step 2.

```bash
curl -X POST https://api.customdomain.ai/v1/connections/<ID>/apply \
  -H "Authorization: Bearer cd_live_..." -H "Content-Type: application/json" \
  -d '{
    "provider": "cloudflare",
    "credential": { "token": "<scoped token>" },
    "records": [ { "type": "CNAME", "host": "shop", "value": "edge.customdomain.ai", "ttl": 3600 } ]
  }'
```

```js
const res = await fetch(`https://api.customdomain.ai/v1/connections/${connection.id}/apply`, {
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.CUSTOMDOMAIN_API_KEY}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    provider: "cloudflare",
    credential: { token: process.env.CLOUDFLARE_TOKEN },
    // The records from step 2, in the fields apply accepts (it refuses unknown ones).
    records: connection.records.map(({ type, host, value, ttl, priority }) => ({ type, host, value, ttl, priority })),
  }),
});
if (!res.ok) console.error(res.status, await res.json()); // { code, title, details }
```

A rejected credential is `422 ProviderAuthenticationError`; any other
provider refusal is `422 dns_write_failed` with the provider's reason.
Route 53 temporary (`ASIA…`) keys also need the session token. Otherwise, show
the records from `GET /v1/connections/{id}/records` and let the user add them.

### Verify and react

Subscribe to webhooks (`connection.live`, `connection.failed`; both carry
`error_code` / `error_message` when there is one) and poll
`GET /v1/connections/{id}` as the fallback. `pending` never fails on its own;
`propagating` fails after 24 hours; `POST /v1/connections/{id}:recheck`
revives a failed connection.

## Mistakes we see

> * **Promising "automatic" from `setup_type`.** Use `rails`.
> * **Telling users "unregistered" on a resolver hiccup.** Only act on
>   `registered === false` when the field is *present*; a transient failure
>   omits it and sets `detection_error: resolver`.
> * **Sending your API key from a browser.** Mint a widget JWT server-side and
>   use that in the page. With an API key that is `POST /v1/tokens` with the key
>   as the bearer; see
>   [Widget tokens](/docs/authentication/widget-tokens).
> * **Putting an API key in `client_secret`.** `POST /v1/tokens` takes the
>   application's client secret, a different credential, and answers `401` to
>   anything else.
> * **Treating `connection.applied` as verified.** Applied means written; only
>   `live` means resolving and served.
> * **Inventing the edge CNAME for an email-only connection.** A connection
>   whose records have no edge record is never served and gets no certificate,
>   by design.
