# Recipe: custom domains in an Express app

Let the users of an Express app connect their own domain with Cnamio: a session route, the connect window on your settings page, and a webhook route. Uses the Node.js server SDK (`npm i cnamio`, Node.js 18+, ESM, no dependencies). The full guide is https://cnamio.com/agent-onboarding/SKILL.md.

## 1. Install and configure

```bash
npm i cnamio
```

Or vendor the single file instead: `curl -s https://cnamio.com/sdk/cnamio.mjs -o lib/cnamio.mjs` and import from it.
```bash
CNAMIO_APPLICATION_ID=app_…
CNAMIO_SECRET=cnm_sk_…        # server only, never committed
CNAMIO_OWNERSHIP_KEY=…        # any long random secret of yours
CNAMIO_WEBHOOK_SECRET=…
```

No account yet? A coding agent can call the MCP tool `start_signup` (or `POST https://api.cnamio.com/v1/agent/signup`) with your email, and work in the sandbox until you open the verification link.

## 2. Routes: `routes/cnamio.js`

```js
import express from 'express';
import { Cnamio, CnamioError, recordsForUser, verifyWebhook } from 'cnamio';

const cnamio = new Cnamio(); // reads CNAMIO_APPLICATION_ID and CNAMIO_SECRET
const recordsFor = userId => recordsForUser({ target: 'customers.yourapp.com', userId, ownershipKey: process.env.CNAMIO_OWNERSHIP_KEY });
export const router = express.Router();

// The webhook needs the raw body: mount this router BEFORE app.use(express.json()).
router.post('/webhooks/cnamio', express.raw({ type: 'application/json' }), async (req, res) => {
  if (!verifyWebhook(req.body, req.headers, process.env.CNAMIO_WEBHOOK_SECRET)) return res.sendStatus(401);
  const event = JSON.parse(req.body.toString('utf8'));
  if (event.type === 'domain.added') await markDomainConnected(event.user_id, event.domain);       // your code
  if (event.type === 'domain.propagation.timeout') await markDomainFailed(event.user_id, event.domain);
  res.sendStatus(200);
});

router.post('/api/cnamio/session', requireUser, async (req, res) => {
  try {
    res.json(await cnamio.createSession({ userId: req.user.id, dnsRecords: recordsFor(req.user.id) }));
  } catch (error) {
    res.status(error instanceof CnamioError && error.status === 429 ? 429 : 502).json({ error: 'cnamio_unavailable' });
  }
});
```

```js
// app.js
import { router as cnamioRoutes } from './routes/cnamio.js';
app.use(cnamioRoutes);   // first: its webhook reads the raw body
app.use(express.json());
```

## 3. Connect button (any page)

```html
<script src="https://connect.cnamio.com/sdk/v1.js"></script>
<button id="connect-domain">Connect your domain</button>
<script>
  document.getElementById('connect-domain').addEventListener('click', async () => {
    const r = await fetch('/api/cnamio/session', { method: 'POST' });
    if (!r.ok) return alert('Custom domains are unavailable right now.');
    window.cnamio.connectDomain({ ...(await r.json()), applicationName: 'Your App', locale: 'en' });
  });
  window.addEventListener('onCnamioSuccess', e => console.log('pending', e.detail.domain, e.detail.jobId));
</script>
```

## 4. Headless (no UI: CLIs, agents, admin jobs)

```js
const records = recordsFor(user.id);
const check = await cnamio.checkDomain('shop.customer.com', records);        // provider, setupType, connectMethods, conflicts
const job = check.connectMethods.includes('api_token') && providerToken
  ? await cnamio.connectAutomatic('shop.customer.com', records, providerToken, { userId: user.id })
  : await cnamio.connect('shop.customer.com', records, { userId: user.id });  // exact records to show the user
console.log((await cnamio.status(job.job_id)).status);
```

## 5. Check it

With the test application's credentials every domain goes to the sandbox provider: `shop.example.com` connects at once, `conflict.example.com` shows a conflict, `pending.example.com` never propagates. Then `await cnamio.manage.setWebhookUrl('https://yourapp.com/webhooks/cnamio')` and `await cnamio.manage.testWebhook()`.
