Platforms
Embed a Ceremony in Svelte and SvelteKit
Embed the signing ceremony in a Svelte or SvelteKit app with a Svelte 5 iframe component, a form action that creates the ceremony and a server status check.
This guide builds a SigningCeremony Svelte component that shows the ceremony in an <iframe> and passes each ceremony event to a callback prop. In SvelteKit, a form action creates the envelope with your API key. In a Svelte app without SvelteKit, any backend can play that role: see the Express routes in the React guide.
The code is written for Svelte 5 (runes) and SvelteKit 2.
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 ashttp://localhost:5173forvite dev. The ceremony loads in an iframe only on the origins you list inembeddable_in. - A signed-in user in
event.locals, set by yourhooks.server.ts. SignatureAPI receives that identity through custom authentication.
The full request flow, with every call and event in order, is in Embedding in a Web Application.
Call SignatureAPI from server code
Code under src/lib/server/ can only be imported by server code, so the API key can’t leak into the browser bundle. 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.
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 form action
The form action creates the ceremony for the signed-in user and returns only its URL. The envelope id stays on the server:
import { fail } from '@sveltejs/kit';
import { SIGNATUREAPI_KEY, APP_ORIGIN } from '$env/static/private';
import { createSigningSession } from '$lib/server/signatureapi';
import { saveEnvelopeId } from '$lib/server/your-app'; // your storage
import type { Actions } from './$types';
export const actions = {
default: async ({ locals }) => {
if (!locals.user) return fail(401, { message: 'Sign in first.' });
const session = await createSigningSession({
apiKey: SIGNATUREAPI_KEY,
origin: APP_ORIGIN,
signer: locals.user,
});
await saveEnvelopeId(locals.user.id, session.envelopeId);
return { url: session.url };
},
} satisfies Actions;A server route answers whether the signed-in user has signed:
import { error, json } from '@sveltejs/kit';
import { SIGNATUREAPI_KEY } from '$env/static/private';
import { hasSigned } from '$lib/server/signatureapi';
import { findEnvelopeId } from '$lib/server/your-app'; // your storage
import type { RequestHandler } from './$types';
export const GET: RequestHandler = async ({ locals }) => {
if (!locals.user) error(401);
const envelopeId = await findEnvelopeId(locals.user.id);
return json({ signed: envelopeId ? await hasSigned({ apiKey: SIGNATUREAPI_KEY, envelopeId }) : false });
};saveEnvelopeId and findEnvelopeId stand for your own database, and locals.user (typed in src/app.d.ts) for your authentication.
Build the signing component
Keep the event types and the URL helper in their own module:
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 listens to window messages with <svelte:window> and accepts a message only when it comes from https://sign.signatureapi.com and from its own iframe:
<script lang="ts">
import { CEREMONY_ORIGIN, embeddedUrl, type CeremonyEvent } from '$lib/ceremony';
interface Props {
url: string;
onceremony: (event: CeremonyEvent) => void;
}
let { url, onceremony }: Props = $props();
let iframe: HTMLIFrameElement | undefined = $state();
function onmessage(event: MessageEvent) {
if (event.origin !== CEREMONY_ORIGIN) return;
if (!iframe || event.source !== iframe.contentWindow) return;
onceremony(event.data as CeremonyEvent);
}
</script>
<svelte:window {onmessage} />
<iframe bind:this={iframe} src={embeddedUrl(url)} title="Sign the document"></iframe>
<style>
iframe {
width: 100%;
height: 80vh;
border: 0;
}
</style>Handle the events and redirect
The page posts the form, shows the ceremony when the action returns a URL and reacts to each event. On ceremony.completed it confirms the result on the server before it navigates:
<script lang="ts">
import { enhance } from '$app/forms';
import { goto } from '$app/navigation';
import SigningCeremony from '$lib/SigningCeremony.svelte';
import type { CeremonyEvent } from '$lib/ceremony';
import type { PageProps } from './$types';
let { form }: PageProps = $props();
let closed = $state(false);
let message = $state<string | null>(null);
let pending = $state(false);
async function onceremony(event: CeremonyEvent) {
switch (event.type) {
case 'ceremony.completed': {
// The message comes from the browser: confirm on the server first.
const { signed } = await (await fetch('/sign/status')).json();
if (signed) await goto('/sign/done');
else message = 'We are still processing your signature.';
break;
}
case 'ceremony.canceled':
closed = true;
break;
case 'ceremony.declined':
await goto('/sign/declined');
break;
case 'ceremony.failed':
console.error('Ceremony failed:', event.error_type, event.error_message);
closed = true;
message = 'This signing link no longer works. Start again to get a new one.';
break;
}
}
</script>
{#if form?.url && !closed}
<SigningCeremony url={form.url} {onceremony} />
{:else}
{#if message ?? form?.message}
<p role="alert">{message ?? form?.message}</p>
{/if}
<form
method="POST"
use:enhance={() => {
pending = true;
closed = false;
message = null;
return async ({ update }) => {
await update();
pending = false;
};
}}
>
<button disabled={pending}>Sign the agreement</button>
</form>
{/if}The ceremony shows its own result page for 3 seconds before it sends ceremony.completed. To navigate right away, set redirect_delay to 0 in the recipient’s ceremony. See Event types.
Test it
- Put a test key in
SIGNATUREAPI_KEYandhttp://localhost:5173inAPP_ORIGINin.env, then runvite dev. - Open
/sign, select Sign the agreement, sign the sample document and select Finish. - After the result page, the app navigates 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.
For work that must happen once, such as storing the signed PDF, use the recipient.completed webhook in a server route rather than the browser event.
Keep learning
- Ceremony Customization: accent color, Cancel button and result page delay.
- Ceremony Events: every event and its
error_typevalues. - Vue and Nuxt and Angular: the same component in other frameworks.