# Add e-signatures to a React app (/docs/guides/e-signatures-react)

Your server creates a signature request and a signing session, a React component shows the
signing page with `mountSigning` from `coss/sign`, and a webhook says when the sealed PDF is
ready. The server code uses Next.js route handlers; any server works. For the overview, see
[e-signatures](/solutions/e-signatures).

## Allow your app to embed the signing page [#allow-your-app-to-embed-the-signing-page]

Install the SDK (`npm install coss`) and add your app's origin to the Sign settings, here or in
the dashboard. Sandbox environments also accept `http://localhost:3000` while you develop.

```ts twoslash
import { Coss } from "coss";
const coss = new Coss(); // reads COSS_API_KEY
// ---cut---
await coss.sign.settings.update({ allowed_origins: ["https://app.example.com"] });
```

## Create a signature request on the server [#create-a-signature-request-on-the-server]

Ask your signed-in user to sign a PDF, inline as base64 or uploaded first with
`coss.sign.documents.upload()`. `delivery: "embedded"` means they sign in your app instead of from
an emailed link, and `client_ref` (your user id) goes into the audit trail. Anchors like
`{{signature:signer_1}}` in the PDF place fields without coordinates
([fields and anchors](/docs/sign/fields-and-anchors)).

```ts twoslash
import { Coss } from "coss";
const coss = new Coss();
declare const pdfBase64: string;
declare const user: { id: string; name: string; email: string };
// ---cut---
const { data: request, error } = await coss.sign.requests.create({
  title: "Services agreement",
  documents: [{ filename: "agreement.pdf", content: pdfBase64 }],
  signers: [
    {
      name: user.name,
      email: user.email,
      delivery: "embedded",
      client_ref: user.id,
      fields: [{ type: "signature", anchor: "{{signature:signer_1}}" }],
    },
  ],
  metadata: { contract_id: "ctr_123" }, // comes back in every sign_request.* webhook
});
// Keep request.id and request.signers[0].id with your contract.
```

## Create a signing session for the embedded signer [#create-a-signing-session-for-the-embedded-signer]

Your app vouches for who the signer is, so create a session only for that signed-in user, when
they open the page. Each call makes a new session, valid for an hour by default and at most 24.
Sessions are refused for email signers, for requests that aren't `sent` and for signers who
already signed or declined.

```ts twoslash
declare function requireUser(): Promise<{ id: string }>;
declare function findContract(id: string, userId: string): Promise<{ requestId: string; signerId: string } | null>;
// ---cut---
// app/api/contracts/[id]/session/route.ts
import { Coss } from "coss";

const coss = new Coss();

export async function POST(_request: Request, ctx: { params: Promise<{ id: string }> }) {
  const user = await requireUser();
  const contract = await findContract((await ctx.params).id, user.id);
  if (!contract) return new Response(null, { status: 404 });

  const { requestId, signerId } = contract;
  const { data: session, error } = await coss.sign.sessions.create(requestId, signerId);
  if (error) return Response.json({ error: error.message }, { status: 409 });
  // The token is in the URL's fragment: never log it.
  return Response.json({ url: session.url });
}
```

## Embed the signing page in a React component [#embed-the-signing-page-in-a-react-component]

`mountSigning` returns an embed whose `destroy()` removes the iframe and stops listening, which is
the effect's cleanup. The iframe grows with its content, up to the window's height.

```tsx twoslash
"use client";
import { useEffect, useRef, useState } from "react";
import { mountSigning, type SigningEvent } from "coss/sign";

export function SignContract({ contractId }: { contractId: string }) {
  const container = useRef<HTMLDivElement>(null);
  const [done, setDone] = useState<string | null>(null);
  useEffect(() => {
    let signing: { destroy(): void } | undefined;
    let cancelled = false;
    const onEvent = (event: SigningEvent) => {
      if (event.type === "signed") setDone("Thanks, you signed.");
      if (event.type === "declined") setDone("You declined to sign.");
      if (event.type === "error") setDone(`This link can't be used (${event.code}).`);
    };
    fetch(`/api/contracts/${contractId}/session`, { method: "POST" })
      .then((res) => res.json() as Promise<{ url: string }>)
      .then(({ url }) => {
        if (cancelled || !container.current) return;
        signing = mountSigning({ url, container: container.current, onEvent });
      });
    return () => {
      cancelled = true;
      signing?.destroy();
    };
  }, [contractId]);

  return done ? <p>{done}</p> : <div ref={container} />;
}
```

Events arrive in order: `ready`, `viewed`, then `signed` or `declined`, plus `error` when the link
is invalid or expired. `signed` carries `request_status`, `completed` when this signer was the
last. They are UI hints: keep your records from webhooks.

## Get the sealed PDF from the sign_request.completed webhook [#get-the-sealed-pdf-from-the-sign_requestcompleted-webhook]

When the last signer signs, coss.com seals the document and sends `sign_request.completed`. Download
the sealed PDF then. An event can arrive more than once, so deduplicate by its `id`.

```ts twoslash
declare function saveSignedPdf(contractId: string, pdf: Uint8Array): Promise<void>;
// ---cut---
// app/api/webhooks/coss/route.ts
import { Coss, verifyWebhook } from "coss";

const coss = new Coss();

export async function POST(request: Request) {
  const secret = process.env.COSS_WEBHOOK_SECRET!;
  const event = await verifyWebhook(await request.text(), request.headers, secret);
  if (event.type === "sign_request.completed") {
    const { sign_request_id, metadata } = event.data;
    const { data: pdf } = await coss.sign.requests.signedDocument(sign_request_id);
    if (pdf) await saveSignedPdf(metadata.contract_id!, pdf);
  }
  return new Response(null);
}
```

`viewed`, `signer_signed`, `declined`, `canceled` and `expired` events show progress too. See
[completion and the audit trail](/docs/sign/completion-and-audit-trail).

## Use templates for repeat documents [#use-templates-for-repeat-documents]

For a contract you send again and again, make a [template](/docs/sign/templates) once, with a role
per party (`client`, `company`) and merge fields filled from your data. Then replace
`coss.sign.requests.create()` with `coss.sign.templates.createRequest(templateId, { signers,
merge_fields })`, giving each signer a `role` and `delivery: "embedded"`. Everything after it
(sessions, the component, the webhook) stays the same.

## Test with a sandbox key [#test-with-a-sandbox-key]

With a `coss_test_…` key, requests work end to end on the real signing page: it says the signing
has no legal effect, the PDF gets a test seal, no emails reach anyone and nothing is billed.
`coss listen` forwards webhooks to your local server and `coss trigger sign_request.completed`
sends a sample one. See [testing Sign](/docs/sign/testing).

## Next steps [#next-steps]

- [Embedded signing](/docs/sign/embedded-signing): sessions, events and settings.
- [Templates](/docs/sign/templates): roles, merge fields and the embedded template builder.
- [Email signing](/docs/sign/email-signing): signers who sign from an emailed link.
- [Sign](/products/sign): what's included and pricing.
