---
title: "Embed a Ceremony in React"
description: "Show the signing ceremony in a React app with a reusable iframe component, handle its events, confirm the result on your server and redirect the signer."
canonical: "https://signatureapi.com/docs/embedded/frameworks/react"
source: "https://signatureapi.com/docs/embedded/frameworks/react.md"
last_verified_api_version: "1.18.0"
last_modified: "2026-11-18T12:39:46Z"
---

# Embed a Ceremony in React

Show the signing ceremony in a React app with a reusable iframe component, handle its events, confirm the result on your server and redirect the signer.

_Last verified against API version 1.18.0._

This guide builds a `SigningCeremony` React component that shows the ceremony in an `<iframe>`, passes each [ceremony event](https://signatureapi.com/docs/embedded/ceremony-events) to your code, and lets your page redirect the signer when they finish. A small Node.js server creates the envelope, because the API key must never reach the browser.

The code is written for React 19 with React Router 7 and an Express 5 server. It uses only the `fetch`, `URL` and `postMessage` web APIs, so it also works with React 18 and other routers or servers.

## Before you start

- An [API key](https://signatureapi.com/docs/api/authentication). Use a test key while you build: test envelopes are free and not legally binding.
- A page that knows who the signed-in user is. Your server passes that identity to SignatureAPI with [custom authentication](https://signatureapi.com/docs/api/resources/ceremonies/authentication/custom).
- The origin your React app runs on, such as `http://localhost:5173` during development. The ceremony loads in an iframe only on the origins you list in `embeddable_in`.

The full request flow, with every call and event in order, is in [Embedding in a Web Application](https://signatureapi.com/docs/embedded/web-app).

## Create the ceremony on your server

Put the SignatureAPI calls in one server module. `createSigningSession` creates the envelope, waits until it is `in_progress` (the ceremony doesn't open before that) and returns the signer's ceremony URL. `hasSigned` reads the envelope to confirm the result.

```typescript server/signatureapi.ts
const API = 'https://api.signatureapi.com/v1';

interface Envelope {
  id: string;
  status: 'processing' | 'in_progress' | 'completed' | 'failed' | 'canceled';
  recipients: Array<{ status: string; ceremony: { url: string | null } }>;
}

async function request(apiKey: string, path: string, init: RequestInit = {}): Promise<Envelope> {
  const response = await fetch(`${API}${path}`, {
    ...init,
    headers: { 'X-API-Key': apiKey, 'Content-Type': 'application/json' },
  });
  if (!response.ok) throw new Error(`SignatureAPI ${path} returned ${response.status}`);
  return (await response.json()) as Envelope;
}

/** Creates an envelope for one signer and returns the URL of their ceremony. */
export async function createSigningSession(options: {
  apiKey: string;
  origin: string; // the origin of the page that shows the iframe
  signer: { id: string; name: string; email: string };
}) {
  const { apiKey, origin, signer } = options;
  let envelope = await request(apiKey, '/envelopes', {
    method: 'POST',
    body: JSON.stringify({
      title: 'Service Agreement',
      documents: [
        {
          url: 'https://pub-9cb75390636c4a8a83a6f76da33d7f45.r2.dev/privacy-placeholder.pdf',
          format: 'pdf',
          places: [{ key: 'signer_signs_here', type: 'signature', recipient_key: 'client' }],
        },
      ],
      recipients: [
        {
          type: 'signer',
          key: 'client',
          name: signer.name,
          email: signer.email,
          ceremony: {
            authentication: [{ type: 'custom', provider: 'Acme Portal', data: { user_id: signer.id } }],
            embeddable_in: [origin],
          },
        },
      ],
    }),
  });

  // The ceremony opens only once the envelope leaves `processing`.
  for (let attempt = 0; envelope.status === 'processing' && attempt < 30; attempt++) {
    await new Promise((resolve) => setTimeout(resolve, 1000));
    envelope = await request(apiKey, `/envelopes/${envelope.id}`);
  }
  const url = envelope.recipients[0]?.ceremony.url;
  if (envelope.status !== 'in_progress' || !url) {
    throw new Error(`Envelope ${envelope.id} is ${envelope.status}`);
  }
  return { envelopeId: envelope.id, url };
}

/** Reads the envelope: true when the signer has completed their ceremony. */
export async function hasSigned(options: { apiKey: string; envelopeId: string }) {
  const envelope = await request(options.apiKey, `/envelopes/${options.envelopeId}`);
  return envelope.recipients[0]?.status === 'completed';
}
```

Expose two routes to your React app. Each one acts for the signed-in user only, so a user can never read another user's envelope:

```typescript server/index.ts
import express from 'express';
import { createSigningSession, hasSigned } from './signatureapi';
import { requireUser, saveEnvelopeId, findEnvelopeId } from './your-app'; // your auth and storage

const app = express();
const apiKey = process.env.SIGNATUREAPI_KEY ?? '';
const origin = process.env.APP_ORIGIN ?? 'http://localhost:5173';

// Start a signing session for the signed-in user.
app.post('/api/signing-session', requireUser, async (req, res) => {
  const user = req.user; // set by requireUser
  const session = await createSigningSession({ apiKey, origin, signer: user });
  await saveEnvelopeId(user.id, session.envelopeId);
  res.json({ url: session.url });
});

// Confirm on the server that the signed-in user has signed.
app.get('/api/signing-session/status', requireUser, async (req, res) => {
  const envelopeId = await findEnvelopeId(req.user.id);
  const signed = envelopeId ? await hasSigned({ apiKey, envelopeId }) : false;
  res.json({ signed });
});

app.listen(3001);
```

`requireUser`, `saveEnvelopeId` and `findEnvelopeId` stand for your own authentication middleware and database. Set `SIGNATUREAPI_KEY` and `APP_ORIGIN` in the server's environment, never in the React bundle. During development, forward `/api` from the Vite dev server to this server with Vite's `server.proxy` option.

## Build the signing component

Keep the event types and the URL helper in their own module:

```typescript src/ceremony.ts
export const CEREMONY_ORIGIN = 'https://sign.signatureapi.com';

export interface CeremonyEvent {
  type: 'ceremony.completed' | 'ceremony.canceled' | 'ceremony.declined' | 'ceremony.failed';
  error_type?: string; // only on ceremony.failed
  error_message?: string; // only on ceremony.failed, for your logs
}

/** Adds the query parameters an iframe ceremony needs. */
export function embeddedUrl(url: string): string {
  const embedded = new URL(url);
  embedded.searchParams.set('embedded', 'true');
  embedded.searchParams.set('event_delivery', 'message');
  return embedded.toString();
}
```

`SigningCeremony` shows the ceremony and listens for its messages. It accepts a message only when it comes from `https://sign.signatureapi.com` and from its own iframe:

```tsx src/SigningCeremony.tsx
import { useEffect, useRef } from 'react';
import { CEREMONY_ORIGIN, embeddedUrl, type CeremonyEvent } from './ceremony';

interface SigningCeremonyProps {
  url: string;
  onEvent: (event: CeremonyEvent) => void;
}

export function SigningCeremony({ url, onEvent }: SigningCeremonyProps) {
  const iframeRef = useRef<HTMLIFrameElement>(null);
  // Keep the latest callback without re-adding the listener on every render.
  const onEventRef = useRef(onEvent);
  useEffect(() => {
    onEventRef.current = onEvent;
  });

  useEffect(() => {
    function handleMessage(event: MessageEvent) {
      if (event.origin !== CEREMONY_ORIGIN) return;
      if (event.source !== iframeRef.current?.contentWindow) return;
      onEventRef.current(event.data as CeremonyEvent);
    }
    window.addEventListener('message', handleMessage);
    return () => window.removeEventListener('message', handleMessage);
  }, []);

  return (
    <iframe
      ref={iframeRef}
      src={embeddedUrl(url)}
      title="Sign the document"
      style={{ width: '100%', height: '80vh', border: 0 }}
    />
  );
}
```

## Handle the events and redirect

The page asks your server for a ceremony URL, shows the component and reacts to each event. On `ceremony.completed` it confirms the result with your server before it redirects:

```tsx src/SignAgreementPage.tsx
import { useState } from 'react';
import { useNavigate } from 'react-router';
import { SigningCeremony } from './SigningCeremony';
import type { CeremonyEvent } from './ceremony';

export function SignAgreementPage() {
  const navigate = useNavigate();
  const [url, setUrl] = useState<string | null>(null);
  const [message, setMessage] = useState<string | null>(null);

  async function start() {
    setMessage(null);
    const response = await fetch('/api/signing-session', { method: 'POST' });
    if (!response.ok) return setMessage('We could not start the signing session.');
    const session: { url: string } = await response.json();
    setUrl(session.url);
  }

  async function handleEvent(event: CeremonyEvent) {
    switch (event.type) {
      case 'ceremony.completed': {
        // The message comes from the browser: confirm with your server first.
        const response = await fetch('/api/signing-session/status');
        const { signed }: { signed: boolean } = await response.json();
        if (signed) navigate('/agreements/signed');
        else setMessage('We are still processing your signature.');
        break;
      }
      case 'ceremony.canceled':
        setUrl(null); // back to the Sign button
        break;
      case 'ceremony.declined':
        navigate('/agreements/declined');
        break;
      case 'ceremony.failed':
        console.error('Ceremony failed:', event.error_type, event.error_message);
        setUrl(null);
        setMessage('This signing link no longer works. Start again to get a new one.');
        break;
    }
  }

  if (url) return <SigningCeremony url={url} onEvent={handleEvent} />;
  return (
    <div>
      {message && <p role="alert">{message}</p>}
      <button type="button" onClick={start}>Sign the agreement</button>
    </div>
  );
}
```

The ceremony shows its own result page for 3 seconds before it sends `ceremony.completed`. To redirect right away and show your own confirmation, set `redirect_delay` to `0` in the recipient's `ceremony` on the server. See [Event types](https://signatureapi.com/docs/embedded/ceremony-events#event-types).

The `ceremony.completed` message is a signal for your UI. For anything that matters, such as releasing an order or storing the signed PDF, rely on your server: the `hasSigned` check above, or the [`recipient.completed`](https://signatureapi.com/docs/api/resources/events/recipient-events) webhook.

## Test it

1. Run the server with a test key in `SIGNATUREAPI_KEY` and your dev origin in `APP_ORIGIN`.
2. Open the page, select **Sign the agreement**, sign the sample document and select **Finish**.
3. After the result page, your app redirects to `/agreements/signed`.

If the iframe stays blank and the console reports a `frame-ancestors` error, `APP_ORIGIN` doesn't match the page's origin. See [Troubleshooting](https://signatureapi.com/docs/embedded/web-app#troubleshooting).

## Keep learning

- [Ceremony Customization](https://signatureapi.com/docs/embedded/customization): accent color, Cancel button and result page delay.
- [Next.js](https://signatureapi.com/docs/embedded/frameworks/nextjs): the same flow with a server action.
- [Ceremony Events](https://signatureapi.com/docs/embedded/ceremony-events): every event and its `error_type` values.
