# Recipe: custom domains in a Next.js app (App Router)

Let the users of a Next.js app connect their own domain with Cnamio: a session route on the server, the connect window in a client component, and a webhook route that marks the domain live. Uses the Node.js server SDK (`npm i cnamio`, Node.js 18+, 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-sdk.mjs` (types: `cnamio.d.mts`) and import from it.
```bash
# .env.local (values never committed; add the names without values to .env.example)
CNAMIO_APPLICATION_ID=app_…
CNAMIO_SECRET=cnm_sk_…
CNAMIO_OWNERSHIP_KEY=…        # any long random secret of yours
CNAMIO_WEBHOOK_SECRET=…       # from the dashboard or GET /v1/manage/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. One client for the server: `lib/cnamio.ts`

```ts
import 'server-only';
import { Cnamio, recordsForUser } from 'cnamio';

export const cnamio = new Cnamio(); // reads CNAMIO_APPLICATION_ID and CNAMIO_SECRET

/** A CNAME to your hosting plus a TXT only this user can satisfy. */
export function recordsFor(userId: string) {
  return recordsForUser({ target: 'customers.yourapp.com', userId, ownershipKey: process.env.CNAMIO_OWNERSHIP_KEY! });
}
```

Replace `customers.yourapp.com` with the hostname your hosting gives for custom domains.

## 3. Session route: `app/api/cnamio/session/route.ts`

```ts
import { cnamio, recordsFor } from '@/lib/cnamio';
import { getCurrentUser } from '@/lib/auth'; // your own auth

export async function POST() {
  const user = await getCurrentUser();
  if (!user) return new Response('Unauthorized', { status: 401 });
  try {
    // { token, applicationId, dnsRecords, expiresAt }: hand it to the browser as is.
    return Response.json(await cnamio.createSession({ userId: user.id, dnsRecords: recordsFor(user.id) }));
  } catch {
    return Response.json({ error: 'cnamio_unavailable' }, { status: 502 });
  }
}
```

## 4. Connect button: `app/settings/domain/connect-domain.tsx`

```tsx
'use client';
import Script from 'next/script';

declare global { interface Window { cnamio?: { connectDomain(config: Record<string, unknown>): void } } }

export function ConnectDomain() {
  async function open() {
    const r = await fetch('/api/cnamio/session', { method: 'POST' });
    if (!r.ok) return alert('Custom domains are unavailable right now.');
    const session = await r.json();
    window.cnamio?.connectDomain({ ...session, applicationName: 'Your App', locale: 'en' });
  }
  return (
    <>
      <Script src="https://connect.cnamio.com/sdk/v1.js" strategy="afterInteractive" />
      <button onClick={open}>Connect your domain</button>
    </>
  );
}
```

Listen for `onCnamioSuccess` on `window` to show the domain as "pending"; only the webhook means "connected". With a Content-Security-Policy, allow `https://connect.cnamio.com` in `script-src` and `frame-src`.

## 5. Webhook: `app/api/webhooks/cnamio/route.ts`

```ts
import { verifyWebhook } from 'cnamio';

export async function POST(request: Request) {
  const raw = await request.text(); // the raw body: the signature is over these bytes
  if (!verifyWebhook(raw, request.headers, process.env.CNAMIO_WEBHOOK_SECRET)) return new Response('bad signature', { status: 401 });
  const event = JSON.parse(raw);
  // Idempotent by event.id (retries happen).
  if (event.type === 'domain.added') await markDomainConnected(event.user_id, event.domain);
  if (event.type === 'domain.propagation.timeout') await markDomainFailed(event.user_id, event.domain);
  return new Response('ok');
}
```

Register the URL once: `await cnamio.manage.setWebhookUrl('https://yourapp.com/api/webhooks/cnamio')`, then `await cnamio.manage.testWebhook()` sends a signed `webhook.test`.

## 6. Check it

1. Signed in, `POST /api/cnamio/session` returns a token; `cnm_sk_` appears nowhere in `.next/static`.
2. With the test application's credentials, connect `shop.example.com`: the sandbox connects it at once and the webhook arrives.
3. `cnamio.manage.testWebhook()` returns `{ delivered: true }`.
