domain
Getting started

React integration

Open Domain0 Connect from a React component without exposing your API key.

Create the connection and browser token on your server. Your React component requests that short-lived session only when the customer starts setup.

ConnectDomainButton.tsx
'use client'

import { useState } from 'react'
import {
  ConnectionIdSchema,
  IssueConnectionTokenResponseSchema,
  createDomain0Client,
  domain0,
} from 'domain0'

const DomainSessionSchema = IssueConnectionTokenResponseSchema.extend({
  connectionId: ConnectionIdSchema,
})

export function ConnectDomainButton({ domain }: { domain: string }) {
  const [opening, setOpening] = useState(false)
  const [error, setError] = useState<string>()

  async function connect() {
    setOpening(true)
    setError(undefined)

    try {
      const response = await fetch('/api/domain-session', {
        method: 'POST',
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify({ domain }),
      })
      if (!response.ok) throw new Error('Could not start domain setup')

      const session = DomainSessionSchema.parse(await response.json())
      const client = createDomain0Client({
        baseUrl: '/api/domain0/',
        token: session.accessToken,
      })

      await domain0.connectDomain({
        client,
        connectionId: session.connectionId,
        applicationName: 'Your product',
        onSuccess: ({ connection }) => {
          console.info(`${connection.intent.domain} is connected`)
        },
      })
    } catch (cause) {
      setError(cause instanceof Error ? cause.message : 'Domain setup failed')
    } finally {
      setOpening(false)
    }
  }

  return (
    <div>
      <button type="button" disabled={opening} onClick={connect}>
        {opening ? 'Opening…' : 'Connect domain'}
      </button>
      {error && <p role="alert">{error}</p>}
    </div>
  )
}

The example expects the authenticated session endpoint and same-origin bridge from the quickstart. Keep the connection ID in your product database so the customer can resume setup later.

Authorize the session request

Before returning a token, verify that the signed-in user owns the product resource and Domain0 connection. Never accept arbitrary DNS records from the component.

Refresh product data

Use onSuccess for the immediate UI response and a webhook for durable server state. If your application uses a query cache, invalidate the domain query instead of reloading the browser document.

On this page