Skip to content

Platforms

Embed a Ceremony in Next.js

Embed the signing ceremony in a Next.js App Router app: a server action creates the ceremony with your API key and a client component shows it.

In the Next.js App Router, a server action runs on the server, so it can call SignatureAPI with your API key while a client component shows the ceremony in an <iframe>. This guide builds both and confirms the result on the server before it redirects the signer.

The code is written for Next.js 16 with the App Router and React 19. It also works on Next.js 15.

Before you start

  • An API key in SIGNATUREAPI_KEY. Use a test key while you build: test envelopes are free and not legally binding.
  • Your app’s origin in APP_ORIGIN, such as http://localhost:3000 during development. The ceremony loads in an iframe only on the origins you list in embeddable_in.
  • A way to read the signed-in user on the server. SignatureAPI receives that identity through custom authentication.

Keep both variables in .env.local without the NEXT_PUBLIC_ prefix, so Next.js never sends them to the browser.

The full request flow, with every call and event in order, is in Embedding in a Web Application.

Call SignatureAPI from server code

Put the SignatureAPI calls in one server-only 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. The server-only import makes the build fail if a client component ever imports this file; install it with npm install server-only.

lib/signatureapi.ts
import 'server-only';

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';
}

Create the ceremony in a server action

The server actions act for the signed-in user only. startSigning returns just the ceremony URL; the envelope id stays on the server:

app/sign/actions.ts
'use server';

import { createSigningSession, hasSigned } from '@/lib/signatureapi';
import { getCurrentUser, saveEnvelopeId, findEnvelopeId } from '@/lib/your-app'; // your auth and storage

const apiKey = process.env.SIGNATUREAPI_KEY ?? '';
const origin = process.env.APP_ORIGIN ?? 'http://localhost:3000';

export async function startSigning(): Promise<string> {
  const user = await getCurrentUser();
  if (!user) throw new Error('Not signed in');
  const session = await createSigningSession({ apiKey, origin, signer: user });
  await saveEnvelopeId(user.id, session.envelopeId);
  return session.url;
}

export async function confirmSigning(): Promise<boolean> {
  const user = await getCurrentUser();
  if (!user) return false;
  const envelopeId = await findEnvelopeId(user.id);
  return envelopeId ? hasSigned({ apiKey, envelopeId }) : false;
}

getCurrentUser, saveEnvelopeId and findEnvelopeId stand for your own authentication and database. A server action is a public endpoint, so always check the user inside it.

Build the signing component

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

app/sign/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 is a client component. It shows the ceremony and accepts a message only when it comes from https://sign.signatureapi.com and from its own iframe:

app/sign/signing-ceremony.tsx
'use client';

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

export function SigningCeremony({ url, onEvent }: { url: string; onEvent: (event: CeremonyEvent) => void }) {
  const iframeRef = useRef<HTMLIFrameElement>(null);
  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 client component calls the server actions like functions. On ceremony.completed it confirms the result on the server, then redirects with the router:

app/sign/sign-agreement.tsx
'use client';

import { useState } from 'react';
import { useRouter } from 'next/navigation';
import { startSigning, confirmSigning } from './actions';
import { SigningCeremony } from './signing-ceremony';
import type { CeremonyEvent } from './ceremony';

export function SignAgreement() {
  const router = useRouter();
  const [url, setUrl] = useState<string | null>(null);
  const [pending, setPending] = useState(false);
  const [message, setMessage] = useState<string | null>(null);

  async function start() {
    setPending(true);
    setMessage(null);
    try {
      setUrl(await startSigning());
    } catch {
      setMessage('We could not start the signing session.');
    } finally {
      setPending(false);
    }
  }

  async function handleEvent(event: CeremonyEvent) {
    switch (event.type) {
      case 'ceremony.completed':
        // The message comes from the browser: confirm on the server first.
        if (await confirmSigning()) router.push('/sign/done');
        else setMessage('We are still processing your signature.');
        break;
      case 'ceremony.canceled':
        setUrl(null);
        break;
      case 'ceremony.declined':
        router.push('/sign/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} disabled={pending}>
        {pending ? 'Preparing the document...' : 'Sign the agreement'}
      </button>
    </div>
  );
}

Render it from a server component page:

app/sign/page.tsx
import { SignAgreement } from './sign-agreement';

export default function SignPage() {
  return (
    <main>
      <h1>Service Agreement</h1>
      <SignAgreement />
    </main>
  );
}

startSigning takes a few seconds while the envelope is processing, which is why the button shows a pending label. The ceremony then shows its own result page for 3 seconds before it sends ceremony.completed. To redirect right away, set redirect_delay to 0 in the recipient’s ceremony. See Event types.

Use a webhook for server-side work

confirmSigning is enough to choose the next screen. For work that must happen once, such as storing the signed PDF, subscribe to the recipient.completed or envelope.completed webhook in a route handler (app/api/webhooks/route.ts) and verify its signature. See Webhooks.

Test it

  1. Put a test key in SIGNATUREAPI_KEY and http://localhost:3000 in APP_ORIGIN, then run next dev.
  2. Open /sign, select Sign the agreement, sign the sample document and select Finish.
  3. After the result page, the app redirects to /sign/done.

If the iframe stays blank and the console reports a frame-ancestors error, APP_ORIGIN doesn’t match the page’s origin. See Troubleshooting.

Keep learning