# Add e-signatures and clickwrap with SvelteKit

> Build a signup clickwrap in SvelteKit with esigncomply in +server routes, the key in $app/env/private and the browser SDK in onMount, then seal a test record.

Source: https://esigncomply.com/docs/quickstart/sveltekit

Last updated November 26, 2026

To add e-signatures and clickwrap with SvelteKit, install `esigncomply` and `@esigncomply/browser`. A `+server` route creates the session with the secret key, which only server code can import from `$app/env/private`. The page attaches the browser SDK to your own checkbox and button in `onMount`, and a second route confirms the record. Esign Comply seals each acceptance as an independent record.

Follow the steps and each signature your app records is a valid electronic signature under the ESIGN Act, state UETA laws and New York's ESRA, and your clickwrap is built the way courts require: clear notice of the terms, an unmistakable act of assent, and a sealed record of both.

Paste this prompt into Cursor, Claude Code or another AI coding tool to have it build the same integration:

```text copy="Copy prompt" open="cursor"
Add Esign Comply clickwrap to my SvelteKit app: a signup form where the user accepts the Terms of Service and the Privacy Notice with a checkbox and a button.

Read these first and follow them exactly. If something conflicts with existing code, or you are unsure how to implement a step, stop and ask. Do not invent API methods, packages or legal wording.
- https://esigncomply.com/docs/quickstart/sveltekit.md (the steps and the tested code for SvelteKit)
- https://esigncomply.com/setup.md (the order of API calls)
- https://esigncomply.com/auth.md (how to handle the keys)

SvelteKit facts
- Packages (the only ones that exist): esigncomply (server code, Node.js 20.19 or later) and @esigncomply/browser (the page). There is no Svelte package. This is SvelteKit 3 with Svelte 5 runes: configuration is in vite.config.ts, and the lib alias is #lib.
- Declare ESIGNCOMPLY_API_KEY in src/env.ts with defineEnvVars and never mark it public. Import it only in server code, from $app/env/private, and pass it to new EsignComply(key): under vite dev the values of .env are not in process.env.
- Create the client in src/lib/server/. A file in a server directory cannot be imported by code that runs in the browser: the build stops with server_only_import.
- Server SDK calls return { data, error } and do not throw. Check error every time.
- The script of +page.svelte also runs on the server. Call fetch and EsignComply.attach inside onMount only. After you set the state that feeds the two link addresses, await tick() before presentDocument.
- In production set ORIGIN to the address visitors use (adapter-node), or SvelteKit answers the page's own POST with 403.
- The form is in the server HTML before the page hydrates: render the checkbox disabled and enable it when observeAssent has resolved.

Build
1. Verify the key: GET /v1/usage with ESIGNCOMPLY_API_KEY. Stop if it fails.
2. Register the Terms of Service and the Privacy Notice as documents and publish one version of each from the documents in this project. If the project has none, register short sample documents and say so in your report. Never write or change the wording of the real documents. Create a profile: jurisdictions ["US-FED"], method "checkbox", assurance_level "L1".
3. src/routes/api/ceremony/+server.ts (POST): create the session with esc.sessions.create and an Idempotency-Key, save the signer ID and the pinned version IDs in server-owned state, and return only clientToken, apiUrl and documents.
4. src/routes/legal/[slug]/+page.server.ts and +page.svelte: load the registered version from esc.documents.versions.getContent and render it inside <article data-esc-document> with {@html}, unmodified.
5. src/routes/signup/+page.svelte: in onMount, EsignComply.attach({ clientToken, apiUrl }), presentDocument for each link, observeAssent({ region, checkbox, submit }) with bind:this elements, then ceremony.complete() in the submit handler. The checkbox has no checked attribute and no bind:checked that starts true.
6. src/routes/api/signup/confirm/+server.ts (POST): read the record with esc.records.get and require: status is "recorded", "timestamped" or "anchored"; livemode is as expected; the signer ID and version IDs equal the server-owned state. Only then create the account.

Never
- Never pre-check the box, auto-submit, or call .click() on the user's behalf.
- Never use "By continuing" or "By clicking below" wording. The notice names the button by its label and each document by its registered name.
- Never put the secret key, or any call that uses it, in code that reaches the browser.
- Never show "signed" or "accepted" before the server has confirmed the record.
- Never fall back to an acceptance with no record when a session is refused.

Check before you report success
- Run: npx esigncomply check --url http://localhost:5173/signup --callback http://localhost:5173/api/signup/confirm
  Fix every finding marked "block". List every finding marked "warn".
- Report the files you created or changed, anything you did not implement and why, and the conformance summary.

Then add the rules block to this project's instruction file: https://esigncomply.com/rules.md
```

The rest of this page is the same integration by hand, in eight steps.

## Before you start

- A test API key. [Create an account](https://esigncomply.com/signup) with your email, no card, then choose **Create test key** in the dashboard. The key is shown once and starts with `esc_test_`. An AI agent with an agent token creates it with `POST /v1/agent/api-keys`: see the [agent account API](https://esigncomply.com/docs/api/agent.md).
- Nothing else from Esign Comply. Test mode works on `localhost` with no card and no domain, and the Free plan includes it in full.
- A SvelteKit app. To start one: `npx sv create my-app`. This page was run on SvelteKit 3.4.0 with Svelte 5.59.1, in a project made from the minimal template with TypeScript.
- Node.js 22.17 or later, which SvelteKit 3.4.0 declares in its `engines` field. The `esigncomply` package needs 20.19 or later. This page was run on Node.js 24.22.1.
- `curl` and `jq` for steps 2 and 3.

## Step 1. Install

Install the server package for the routes and the browser SDK for the page:

```bash
npm install esigncomply @esigncomply/browser
```

There is no Svelte package to add. The browser SDK is headless: you write the markup, and it observes it.

## Step 2. Set the key

Put the key in `.env` in the project folder. SvelteKit reads this file in development and at build time.

```bash
# .env (never commit this file)
ESIGNCOMPLY_API_KEY=esc_test_us_...
```

Then declare each variable in `src/env.ts`. A variable is private unless it is marked `public`, and a private one can be imported only by server code, from `$app/env/private`:

```ts file="src/env.ts"
// src/env.ts
import { defineEnvVars } from '@sveltejs/kit/env';

// Every variable is private unless it is marked public: only server code can import it,
// from $app/env/private. A variable with no schema must be set, or the app does not start.
export const variables = defineEnvVars({
	ESIGNCOMPLY_API_KEY: { description: 'The secret API key. Never public.' },
	ESIGNCOMPLY_PROFILE_ID: {},
	ESIGNCOMPLY_TERMS_ID: {},
	ESIGNCOMPLY_PRIVACY_ID: {},
	// Optional: the SDK picks the API host from the key when this is not set.
	ESIGNCOMPLY_API_URL: { schema: (value) => value },
	// "true" in production only.
	ESIGNCOMPLY_LIVE: { schema: (value) => value === 'true' }
});
```

The four variables with no schema are required. With none of them set, SvelteKit answered the page and the route with `500` and `env_invalid` when this was tried, and named each missing variable. The three IDs come from step 3.

Load the file into your shell for the commands in steps 2, 3 and 7, then check that the key works:

```bash
set -a; . ./.env; set +a
curl -s ${ESIGNCOMPLY_API_URL:-https://esigncomply.com/v1}/usage \
  -H "Authorization: Bearer $ESIGNCOMPLY_API_KEY" | jq '{plan_name, test_events}'
```

```json
{
  "plan_name": "Free",
  "test_events": {
    "used_this_month": 0,
    "quota_per_month": 500
  }
}
```

A `401` means the key is wrong or revoked: see [`invalid_api_key`](https://esigncomply.com/docs/api/errors.md#invalid_api_key). The rules for handling keys are in [/auth.md](https://esigncomply.com/auth.md).

## Step 3. Register a document version

Every record pins the exact version of each document by hash, so the documents are registered first. This block registers a Terms of Service and a Privacy Notice with one version each, and creates a profile: the Federal pack, a checkbox with a button, level L1. It is the same for every stack and needs `curl` and `jq`.

```bash
ESC=${ESIGNCOMPLY_API_URL:-https://esigncomply.com/v1}
KEY="Authorization: Bearer $ESIGNCOMPLY_API_KEY"
JSON="Content-Type: application/json"

# Two sample documents, one version each.
TERMS=$(curl -s $ESC/documents -H "$KEY" -H "$JSON" \
  -d '{"name":"Terms of Service","type":"terms"}' | jq -r .id); sleep 1
curl -s $ESC/documents/$TERMS/versions -H "$KEY" -H "$JSON" \
  -d '{"version_label":"1","language":"en","content":{"format":"markdown","text":"# Terms of Service\n\nThese are sample terms for a test."},"material_change":true}' \
  | jq -r .id; sleep 1
PRIVACY=$(curl -s $ESC/documents -H "$KEY" -H "$JSON" \
  -d '{"name":"Privacy Notice","type":"privacy_notice"}' | jq -r .id); sleep 1
curl -s $ESC/documents/$PRIVACY/versions -H "$KEY" -H "$JSON" \
  -d '{"version_label":"1","language":"en","content":{"format":"markdown","text":"# Privacy Notice\n\nThis is a sample privacy notice for a test."}}' \
  | jq -r .id; sleep 1

# A profile: Federal pack, checkbox plus button, L1.
PROFILE=$(curl -s $ESC/profiles -H "$KEY" -H "$JSON" \
  -d '{"name":"Signup","jurisdictions":["US-FED"],"method":"checkbox","assurance_level":"L1"}' | jq -r .id)

printf 'ESIGNCOMPLY_PROFILE_ID=%s\nESIGNCOMPLY_TERMS_ID=%s\nESIGNCOMPLY_PRIVACY_ID=%s\n' "$PROFILE" "$TERMS" "$PRIVACY"
```

It prints the two version IDs, then three lines with your own IDs:

```text
dv_YiWs9cmWoVSGp7ALPeZS
dv_bAYeA7QigKUH0iLhPpV7
ESIGNCOMPLY_PROFILE_ID=prof_SPVEgBT8a8Ror3mJ8M99
ESIGNCOMPLY_TERMS_ID=doc_bDgYFndAoC8tkeYibAVy
ESIGNCOMPLY_PRIVACY_ID=doc_mb2hnWKS0Qa7SKtucDW9
```

Add the three lines to `.env`. The pauses keep the script under the Free plan's 2 requests per second. Keep the names `Terms of Service` and `Privacy Notice`: the notice on your page names each document by its registered name, and rule [CR-02](https://esigncomply.com/docs/conformance.md#cr-02) checks that it does. With your own documents, publish the text you already have and change the notice to match. See [Documents](https://esigncomply.com/docs/api/documents.md) and [Profiles](https://esigncomply.com/docs/api/profiles.md).

## Step 4. Create a session on the server

One module holds the client, the test signer and the state the confirmation compares against. It sits in `src/lib/server`, and SvelteKit does not let code that runs in the browser import a file from a `server` directory:

```ts file="src/lib/server/esigncomply.ts"
// src/lib/server/esigncomply.ts
import { EsignComply } from 'esigncomply';
import {
	ESIGNCOMPLY_API_KEY,
	ESIGNCOMPLY_API_URL,
	ESIGNCOMPLY_LIVE,
	ESIGNCOMPLY_PRIVACY_ID,
	ESIGNCOMPLY_TERMS_ID
} from '$app/env/private';

// A file in a server directory: SvelteKit refuses to send it to the browser.
// The key comes from $app/env/private, the private environment module.
export const esc = new EsignComply(ESIGNCOMPLY_API_KEY, { baseUrl: ESIGNCOMPLY_API_URL });

// The signer. In your app this is the signed-in user, or the account you are about to create.
export const signer = {
	external_id: 'user_7c1d',
	email: 'dana@example.org',
	name: 'Dana Whitfield',
	class: 'consumer',
	country: 'US',
	region: 'US-CA'
} as const;

export const DOCUMENTS: Record<string, string | undefined> = {
	terms: ESIGNCOMPLY_TERMS_ID,
	privacy: ESIGNCOMPLY_PRIVACY_ID
};
export const SEALED = ['recorded', 'timestamped', 'anchored'];
// Test records in development, live records where ESIGNCOMPLY_LIVE is "true": production only.
export const LIVE = ESIGNCOMPLY_LIVE;

// Signer ID -> the version IDs this server pinned. Use a table in your database in production.
export const pinned = new Map<string, string[]>();
```

Two things here are specific to SvelteKit. The client gets the key as an argument: under `vite dev` the values of `.env` are not in `process.env`, and a client created with no argument answered `missing_api_key` when this was tried. And the `pinned` Map is plain server memory, not a cookie: the `cookies` helper of SvelteKit sends the value you give it as it is, and a test cookie arrived as `probe=plain-value`. Replace the Map with a table in your database before you run more than one process.

A `+server.ts` file is a route. This one creates the session and returns three values to the browser: the client token, the API URL and the pinned documents.

```ts file="src/routes/api/ceremony/+server.ts"
// src/routes/api/ceremony/+server.ts
import { json } from '@sveltejs/kit';
import { ESIGNCOMPLY_PROFILE_ID } from '$app/env/private';
import { DOCUMENTS, esc, pinned, signer } from '#lib/server/esigncomply.js';
import type { RequestHandler } from './$types';

// Step 4: create the session with the secret key. The browser gets the client token only.
export const POST: RequestHandler = async ({ request, url }) => {
	// The page that runs the ceremony: the origin the browser reports, plus its path.
	const origin = request.headers.get('origin') ?? url.origin;

	const { data: session, error } = await esc.sessions.create(
		{
			profile: ESIGNCOMPLY_PROFILE_ID,
			signer,
			documents: [
				{ document: DOCUMENTS.terms!, version: 'current' },
				{ document: DOCUMENTS.privacy!, version: 'current' }
			],
			context: { url: `${origin}/signup`, locale: 'en-US', purpose: 'account_signup' }
		},
		{ idempotencyKey: `signup-${signer.external_id}-${crypto.randomUUID()}` }
	);
	if (error) return json({ error: error.code }, { status: 502 });

	pinned.set(
		signer.external_id,
		session.documents.map((d) => d.version_id)
	);
	return json({ clientToken: session.client_token, apiUrl: session.api_url, documents: session.documents });
};
```

The `#lib` alias is the one `sv create` declares in the `imports` field of `package.json`. The signer is a fixed test person here. In your app it is the signed-in user or the account you are about to create.

## Step 5. Attach the ceremony in the browser

The browser SDK renders nothing. It observes the checkbox, the notice, the links and the button of your own markup, and reports each step from the signer's browser straight to Esign Comply. The page is `src/routes/signup/+page.svelte`:

```svelte file="src/routes/signup/+page.svelte"
<!-- src/routes/signup/+page.svelte -->
<script lang="ts">
	import { onMount, tick } from 'svelte';
	import { EsignComply, type Ceremony } from '@esigncomply/browser';

	// This script also runs on the server while the page is rendered.
	// Everything that needs the browser sits in onMount, which never runs there.
	let assent: HTMLDivElement;
	let checkbox: HTMLInputElement;
	let submit: HTMLButtonElement;
	let termsLink: HTMLAnchorElement;
	let privacyLink: HTMLAnchorElement;

	let versions = $state<string[]>([]); // the version IDs this session pinned, for the two links
	let ready = $state(false); // true once the SDK observes the checkbox
	let canComplete = $state(false);
	let message = $state('');
	let ceremony: Ceremony | undefined;

	// One session per page load.
	onMount(() => {
		start();
		return () => ceremony?.destroy();
	});

	async function start() {
		try {
			// Your +server route creates the session and returns { clientToken, apiUrl, documents }. Never the secret key.
			const response = await fetch('/api/ceremony', { method: 'POST' });
			if (!response.ok) throw new Error('We could not start the signup. Reload the page to try again.');
			const session = await response.json();

			ceremony = await EsignComply.attach({ clientToken: session.clientToken, apiUrl: session.apiUrl });
			ceremony.on('change', ({ remainingSteps }) => {
				canComplete = !remainingSteps.some((step) => step !== 'signature.applied');
			});

			// Point each link at the exact version this session pinned, wait for Svelte to update the DOM, then report it.
			versions = session.documents.map((document: { version_id: string }) => document.version_id);
			await tick();
			await ceremony.presentDocument({ versionId: versions[0], mode: 'hyperlink', link: termsLink });
			await ceremony.presentDocument({ versionId: versions[1], mode: 'hyperlink', link: privacyLink });
			await ceremony.observeAssent({ region: assent, checkbox, submit }); // region: notice, links, checkbox, button
			ready = true; // the SDK watches the box from here on
		} catch (error) {
			message = error instanceof Error ? error.message : 'Something went wrong.';
		}
	}

	async function onSubmit(event: SubmitEvent) {
		event.preventDefault();
		if (!ceremony) return;
		try {
			const result = await ceremony.complete(); // the signing act, from the signer's own click
			// The result came to the browser. Your +server route confirms the record before anything is granted.
			const confirmed = await fetch('/api/signup/confirm', {
				method: 'POST',
				headers: { 'Content-Type': 'application/json' },
				body: JSON.stringify({ recordId: result.recordId })
			});
			message = confirmed.ok
				? `Account created. Record ${result.recordId}`
				: 'We could not confirm whether your acceptance was recorded. Please wait while we check.';
		} catch (error) {
			message = error instanceof Error ? error.message : 'Something went wrong.';
		}
	}
</script>

<svelte:head>
	<title>Create account</title>
</svelte:head>

<form class="signup" onsubmit={onSubmit}>
	<h1>Create account</h1>
	<div bind:this={assent}>
		<!-- The box is in the server HTML, so it stays disabled until the SDK watches it. -->
		<!-- No bind:checked and no checked attribute: only the user changes the box. -->
		<label><input bind:this={checkbox} type="checkbox" disabled={!ready} /> I agree to the Terms of Service and Privacy Notice</label>
		<p>
			By checking the box and clicking Create account, you agree to the
			<a bind:this={termsLink} href="/legal/terms?v={versions[0] ?? ''}">Terms of Service</a> and acknowledge the
			<a bind:this={privacyLink} href="/legal/privacy?v={versions[1] ?? ''}">Privacy Notice</a>.
		</p>
		<button bind:this={submit} type="submit" disabled={!canComplete}>Create account</button>
	</div>
	<p role="alert">{message}</p>
</form>

<style>
	.signup { font: 16px/1.5 system-ui, sans-serif; max-width: 480px; margin: 48px auto; padding: 0 20px; }
	/* Document links are underlined and differ from the text around them by at least 3 to 1 (rule CR-05). */
	a { color: #0b57d0; text-decoration: underline; }
	button { font: inherit; padding: 10px 16px; }
</style>
```

Each link opens a document page on your own origin. A `+page.server.ts` file loads the registered version on the server:

```ts file="src/routes/legal/[slug]/+page.server.ts"
// src/routes/legal/[slug]/+page.server.ts
import { error } from '@sveltejs/kit';
import { DOCUMENTS, esc } from '#lib/server/esigncomply.js';
import type { PageServerLoad } from './$types';

// /legal/terms?v=dv_... loads one registered version. A +page.server file runs on the server only.
export const load: PageServerLoad = async ({ params, url }) => {
	const documentId = DOCUMENTS[params.slug];
	if (!documentId) error(404, 'Not found');

	const { data, error: failed } = await esc.documents.versions.getContent(
		documentId,
		url.searchParams.get('v') || 'current'
	);
	if (failed || !data.html) error(404, 'Not found');

	return { versionId: data.version_id, html: data.html };
};
```

And the page beside it renders that HTML, unmodified:

```svelte file="src/routes/legal/[slug]/+page.svelte"
<!-- src/routes/legal/[slug]/+page.svelte -->
<script lang="ts">
	import type { PageProps } from './$types';

	let { data }: PageProps = $props();
</script>

<!-- The registered version, unmodified. -->
<article data-esc-document={data.versionId}>{@html data.html}</article>
```

Start the app and open [http://localhost:5173/signup](http://localhost:5173/signup):

```bash
npm run dev
```

The button stays disabled until the box is ticked. Tick it, click **Create account**, and the page shows:

```text
Account created. Record rec_jPggfWa3G5SQ545GNawF
```

Three details matter. Everything sits in `onMount`, because the script of a page also runs on the server while SvelteKit renders it: `EsignComply.attach` rejects there with `invalid_request`, and a `fetch` at the top of the script stopped the render with `ssr_fetch_relative_url` when it was tried. The code waits for `tick()` after it sets `versions`, because Svelte applies a state change to the DOM later: without the wait, the SDK requested the first link as `/legal/terms?v=`, with no version ID. And the checkbox is disabled until the SDK observes it. SvelteKit sends the form as HTML before the script loads, and Svelte keeps the same elements when it hydrates: a box ticked before the SDK watches it fails [CR-01](https://esigncomply.com/docs/conformance.md#cr-01). In a test with the page's scripts held back, under `vite dev` and on the built server, the box was disabled in the server HTML and a click on it did nothing. The box has no `checked` attribute and no `bind:checked`: only the user changes it.

## Step 6. Confirm the record on the server

The result of `ceremony.complete()` was delivered to the browser, so your server does not trust it. A second `+server.ts` route reads the record with the secret key and grants access only when four things hold: the status is `recorded`, `timestamped` or `anchored`; `livemode` is what this deployment expects; the signer is the one this server created the session for; and the document versions are exactly the ones it pinned. This step is never optional.

```ts file="src/routes/api/signup/confirm/+server.ts"
// src/routes/api/signup/confirm/+server.ts
import { json } from '@sveltejs/kit';
import { LIVE, SEALED, esc, pinned, signer } from '#lib/server/esigncomply.js';
import type { RequestHandler } from './$types';

// Step 6: confirm the record with the secret key before the account exists.
export const POST: RequestHandler = async ({ request }) => {
	const body = await request.json().catch(() => ({})); // an empty or malformed body is refused below
	const { data: record, error } = await esc.records.get(String(body.recordId));

	const expected = [...(pinned.get(signer.external_id) ?? [])].sort();
	const confirmed =
		!error &&
		SEALED.includes(record.status) &&
		record.livemode === LIVE &&
		record.signer.external_id === signer.external_id &&
		JSON.stringify(record.documents.map((d) => d.version_id).sort()) === JSON.stringify(expected);

	console.log(confirmed ? `confirmed ${record.id} (${record.status})` : 'refused');
	if (!confirmed) return json({ confirmed: false }, { status: 409 });
	// Only now create the account, and store record.id and record.receipt with it.
	return json({ confirmed: true, recordId: record.id });
};
```

The server prints one line for each confirmation:

```text
confirmed rec_jPggfWa3G5SQ545GNawF (recorded)
```

A record ID that was made up is refused with status `409`:

```bash
curl -s -X POST http://localhost:5173/api/signup/confirm \
  -H "Content-Type: application/json" -d '{"recordId":"rec_made_up"}'
```

```json
{"confirmed":false}
```

See [Server confirmation](https://esigncomply.com/docs/guides/server-confirmation.md) for the webhook that backs this route up when the browser closes early.

## Step 7. Check the result

Open the dashboard and choose **Records**. The test record is there with what was observed, what was asserted, and its evidence report, watermarked TEST.

Then run the conformance check against the page. It opens the page in headless Chromium at three window sizes, signs as a visitor would, and tries four things that must be refused. One of them posts a made-up record ID to your confirm route.

```bash
npm install --save-dev playwright
npx playwright install chromium
npx esigncomply check --url http://localhost:5173/signup --callback http://localhost:5173/api/signup/confirm
```

The report for this page's code, shortened:

```text
Violations that must be refused
  REFUSED   Submit with the checkbox untouched      No record was made.
  REFUSED   Completion from another origin          The API answered 403 domain_mismatch.
  REFUSED   Programmatic click                      No record was made.
  REFUSED   Forged success posted to your callback  http://localhost:5173/api/signup/confirm answered 409.

Ceremonies
  390x844    record rec_vW4qQ10roihfUcSgijrC  session ses_pDwqw5Uh7V62SxPHrAqW, 5 events
  768x1024   record rec_iW6wab6CPPx62DDZqNqA  session ses_wU3YnV1Hr40PicWx8SP5, 5 events
  1440x900   record rec_YQwBi5DNj146wceCj5xC  session ses_NFHTTJvwp20wArwaS4YF, 5 events

Summary: 0 block, 0 warn, 27 pass.
```

Fix every finding marked `block` and read every finding marked `warn`. Each one names the rule the screen missed, the measurement and the fix. In test mode a finding never stops a record from being sealed, so read the report. The rules are on [Conformance rules](https://esigncomply.com/docs/conformance.md), and every flag of the command is on the [CLI page](https://esigncomply.com/docs/sdk/cli.md).

## Step 8. Go live

Going live takes three steps on the Esign Comply side. There is no plan to choose and no checkout: the Free plan records 10 live signatures a month.

1. Register your production domain and verify it. See [Register a domain](https://esigncomply.com/docs/guides/domains.md).
2. Add your organization's legal name, country and address under **Go live** in the dashboard.
3. Create a live key. It is shown once and starts with `esc_live_`.

Test and live share nothing, so create the documents and the profile again with the live key, or copy them to live from the dashboard, and use the live IDs in production.

Then switch the app over. This page was built for a Node.js server with adapter-node, set in `vite.config.ts`:

```ts file="vite.config.ts"
// vite.config.ts
import adapter from '@sveltejs/adapter-node';
import { sveltekit } from '@sveltejs/kit/vite';
import { defineConfig } from 'vite';

export default defineConfig({
	plugins: [
		sveltekit({
			compilerOptions: {
				// Force runes mode for the project, except for libraries. Can be removed in svelte 6.
				runes: ({ filename }) =>
					filename.split(/[/\\]/).includes('node_modules') ? undefined : true
			},

			// adapter-node builds a Node.js server into build/. See https://svelte.dev/docs/kit/adapters for other hosts.
			adapter: adapter()
		})
	]
});
```

- Set the live key as `ESIGNCOMPLY_API_KEY` and set `ESIGNCOMPLY_LIVE=true` in production only. From then on the confirm route refuses every test record there.
- Give the built server its variables. Started with `node build` and none, it stopped with `env_invalid`. Started with `node --env-file=.env build`, it ran.
- Set `ORIGIN` to the address visitors use. On the built server SvelteKit compares the `Origin` header of the page's session request with its own origin. Run on `http://localhost` without `ORIGIN`, it answered that request with `403`. With `ORIGIN=http://localhost:3000` it sealed a record.
- Replace the `pinned` Map with a table in your database, and store `record.id` and `record.receipt` beside the user.

In live mode `context.url` must be inside your registered domain, and browser calls are accepted only from it. By default a live signature with a finding at Block level is recorded and you are told at once which rule failed. Turn on blocking, on the dashboard's Conformance page, and it is refused before it is sealed. Run the check from step 7 until no finding is at Block level before you switch keys.

## Troubleshooting

- **`env_invalid` and the app answers `500`.** A variable declared in `src/env.ts` is not set where the app runs. SvelteKit names it in the message. This check comes before the SDK's own [`missing_api_key`](https://esigncomply.com/docs/api/errors.md#missing_api_key), which is what a client created with no argument answers under `vite dev`.
- **`403` with `Cross-site POST form submissions are forbidden`.** The built server does not know its own origin, so the page's session request looks like a request from another site. Set `ORIGIN`, as in step 8. `vite dev` makes no such check, so this shows up only after the build.
- **`domain_mismatch` when the page loads.** The page was opened from a host that is not on the test allowlist, for example your machine's LAN address from `vite dev --host`. Test keys work on `localhost` and `127.0.0.1` at any port. Add other hosts under Domains in the dashboard. See [`domain_mismatch`](https://esigncomply.com/docs/api/errors.md#domain_mismatch).
- **`429` when the confirm route reads the record.** The route needs no retry loop: the `esigncomply` package waits for the time in `Retry-After` and tries again, up to twice. In the test, four confirmations sent at once for one record all answered `200`, two of them a second later than the others: the API had answered those two reads with `429`. See [`rate_limit_exceeded`](https://esigncomply.com/docs/api/errors.md#rate_limit_exceeded) and [Retries and timeouts](https://esigncomply.com/docs/sdk/node.md#retries-and-timeouts).

## Questions about the SvelteKit quickstart

### Why does the client get the key as an argument?

Because the SDK's default is `process.env`, and under `vite dev` the values of `.env` are not there. When this was tested, the key was in `$app/env/private` and not in `process.env`, and a client created with no argument answered `missing_api_key`. In the built server both held it.

### Why is the session requested in onMount and not in a load function?

Because `onMount` runs in the browser only, which is where `EsignComply.attach` has to run anyway. A universal `load` that posted to the session route was also tried: it ran on the server once for each page load, and the browser sent no request of its own.

### What does SvelteKit do when a page imports the server module?

It stops the build. `vite build` ended with `server_only_import` and the import chain when a page imported `src/lib/server/esigncomply.ts` or `$app/env/private`. Under `vite dev` the browser's request for that module was refused with the same error and the page stayed blank.

### Does the Map keep its entries while vite dev runs?

Yes, until the file that holds it changes. When this was tested, a second route read the entry the session route had set. After an edit to `src/lib/server/esigncomply.ts` the Map was empty, and after an edit to a route file it was not.

### Does the SvelteKit quickstart need a domain or a card?

No. Test mode works on `localhost` with a test key, no card and no domain. You register and verify a domain only when you go live, and the Free plan then records 10 live signatures a month.

## Next steps

- [E-signatures and clickwrap for SvelteKit](https://esigncomply.com/sveltekit): what the integration gives you on this stack, with the things to watch for.
- [Browser SDK](https://esigncomply.com/docs/sdk/browser.md): every method the page calls, and what each one records.
- [Server confirmation](https://esigncomply.com/docs/guides/server-confirmation.md): the checks in step 6 and the `record.completed` webhook.
- [Node SDK](https://esigncomply.com/docs/sdk/node.md): every method the routes call, the endpoint behind it, and the errors.
- [All quickstarts](https://esigncomply.com/docs/quickstart.md#quickstarts-by-stack-and-platform).
