Add e-signatures and clickwrap with Elixir
To add e-signatures and clickwrap with Elixir, call the REST API with Req and the secret key: there is no Hex package. One Plug router on Bandit, without Phoenix, creates the session, keeps the pinned versions in a signed cookie, and confirms the record. The browser SDK attaches to your checkbox. 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.
This page is plain Elixir with no Phoenix: Plug for the routes and the session, Bandit as the web server, Req for the calls. Plug's documentation names two web servers, Cowboy and Bandit. This page uses Bandit, which is written in Elixir and is the server a new Phoenix app starts with. For a Phoenix app, use the Phoenix quickstart.
Paste this prompt into Cursor, Claude Code or another AI coding tool to have it build the same integration:
Add Esign Comply clickwrap to my Elixir 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/elixir.md (the steps and the tested code for Elixir)
- https://esigncomply.com/setup.md (the order of API calls)
- https://esigncomply.com/auth.md (how to handle the keys)
Elixir facts
- There is no Esign Comply package on Hex. Do not install or invent one. The server calls the REST API at https://esigncomply.com/v1 with Req, a bearer token and the secret key.
- The browser SDK is a script tag: https://esigncomply.com/sdk/v1/esigncomply.js. It defines the global EsignComply.
- The secret key is in the environment variable ESIGNCOMPLY_API_KEY. Read it in config/runtime.exs with System.fetch_env!. Never read it in config/config.exs or in a module attribute: those run when the code is compiled, and a release would carry the value of the build machine. Elixir does not read .env files. Never print the key.
- Req: by default it sends a GET again up to three times, on 408, 429 and 5xx answers and on connection errors, it waits as long as Retry-After says, and it does not retry a POST. Pass a retry function that returns {:delay, ms} for a 429 only, with the wait from Retry-After held between 1 and 5 seconds, and max_retries: 2. Req does not raise on 4xx and 5xx: read the status and the error envelope. Set receive_timeout.
- Req decodes JSON with Jason, and the keys are strings: record["status"], never record.status or record[:status].
- Keep the signer ID and the pinned version IDs in Plug.Session with the cookie store and a signing salt. That cookie is signed, not encrypted: the visitor can read it, so put nothing secret in it. conn.secret_key_base must be at least 64 bytes. The options of a plug line are fixed when the module is compiled: set up whatever depends on the environment in a function plug.
- Use Plug.ErrorHandler to answer 500 with JSON. Each request runs in a process of its own: an exception ends that request only.
- String interpolation escapes nothing. Print the document HTML as it is, and escape everything else you print with Plug.HTML.html_escape.
- An image without CA certificates cannot call an https API: Req raises. The image that runs the release needs ca-certificates.
- The page is on screen before the script has a session: 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. Server: POST /api/ceremony calls POST /v1/sessions with an Idempotency-Key, saves the signer ID and the pinned version IDs in the session cookie, and returns only clientToken, apiUrl and documents.
4. Server: GET /legal/terms and /legal/privacy render the html from GET /v1/documents/{id}/versions/{version_id}/content inside <article data-esc-document>, unmodified.
5. Browser: EsignComply.attach({ clientToken, apiUrl }), presentDocument for each link, observeAssent({ region, checkbox, submit }), then complete() from the user's real click.
6. Server: POST /api/signup/confirm calls GET /v1/records/{id} and requires: status is "recorded", "timestamped" or "anchored"; livemode is as expected; the signer ID and version IDs equal the ones in the session cookie. 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:4000/signup --callback http://localhost:4000/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 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 withPOST /v1/agent/api-keys: see the agent account API. - Nothing else from Esign Comply. Test mode works on
localhostwith no card and no domain, and the Free plan includes it in full. - Elixir with Erlang/OTP. This page was run on Elixir 1.20.5 and Erlang/OTP 29.
curlandjqfor steps 2 and 3, and Node.js 20.19 or later for the conformance check in step 7.
Step 1. Install
There is no Hex package for the API. The server SDK exists for Node.js only, so an Elixir app calls the REST API directly, and this page does it with Req. To follow along in a new project:
mix new esigncomply_quickstart --sup --module Quickstart
cd esigncomply_quickstart
mkdir config priv
Replace the mix.exs that mix new wrote:
defmodule Quickstart.MixProject do
use Mix.Project
def project do
[
app: :esigncomply_quickstart,
version: "0.1.0",
elixir: "~> 1.20",
start_permanent: Mix.env() == :prod,
deps: deps()
]
end
def application do
[
extra_applications: [:logger],
mod: {Quickstart.Application, []}
]
end
# Nothing here is for the API: Bandit is the web server, Plug the router and the session, Req the HTTP client.
defp deps do
[
{:bandit, "~> 1.15"},
{:plug, "~> 1.20"},
{:req, "~> 0.7.5"},
{:jason, "~> 1.4"}
]
end
end
mix deps.get
Mix resolved fourteen packages, among them Finch and Mint under Req, and Thousand Island under Bandit.
Why these four. Plug's documentation says you need a web server and its bindings for Plug, and names two: Cowboy and Bandit. Bandit's own documentation says it is written entirely in Elixir and has been the default HTTP server for Phoenix since release 1.7.11, so this page and a Phoenix app run on the same server. Req is the HTTP client: it decodes JSON and has a retry of its own, which step 4 narrows. Req brings Jason, and the project lists it because the router calls it for its own answers.
Step 2. Set the key
Put the key in .env in the project folder. Elixir does not read this file: you load it into the shell that starts the app.
# .env (never commit this file)
ESIGNCOMPLY_API_KEY=esc_test_us_...
Step 4 keeps the pinned versions in a session cookie that Plug signs with a key derived from SECRET_KEY_BASE. Add one to the same file. It must be at least 64 bytes long:
printf 'SECRET_KEY_BASE=%s\n' "$(head -c 48 /dev/urandom | base64 | tr -d '\n')" >> .env
The app reads every variable in one place, config/runtime.exs:
import Config
# This file runs each time the app starts, under mix and in a release, so the values come from the machine that runs the app.
# config/config.exs runs when the code is compiled: a key read there is fixed into the release on the build machine.
secret_key_base = System.fetch_env!("SECRET_KEY_BASE")
# Plug's cookie store refuses a shorter secret, but only when the first session is written. Stop at start instead.
if byte_size(secret_key_base) < 64, do: raise("SECRET_KEY_BASE must be at least 64 bytes")
config :esigncomply_quickstart,
api_url: System.get_env("ESIGNCOMPLY_API_URL", "https://esigncomply.com/v1"),
api_key: System.fetch_env!("ESIGNCOMPLY_API_KEY"),
profile_id: System.fetch_env!("ESIGNCOMPLY_PROFILE_ID"),
documents: %{
"terms" => System.fetch_env!("ESIGNCOMPLY_TERMS_ID"),
"privacy" => System.fetch_env!("ESIGNCOMPLY_PRIVACY_ID")
},
# Set ESIGNCOMPLY_LIVE in production only.
live: System.get_env("ESIGNCOMPLY_LIVE") == "true",
secret_key_base: secret_key_base,
port: String.to_integer(System.get_env("PORT", "4000"))
Where the key is read matters in Elixir. In a test project built as a release with a variable set to one value and started with another, a value read in config/config.exs and a value read in a module attribute were both the build machine's, and the build machine's value was in the release's sys.config file. Only config/runtime.exs and a System.get_env call inside a function saw the value of the machine that ran the release.
With .env not loaded, mix run and the release both ended at start with System.EnvError: could not fetch environment variable "SECRET_KEY_BASE" because it is not set. With a secret of 32 characters the release ended with SECRET_KEY_BASE must be at least 64 bytes, the check in this file.
Load the file into your shell for the commands in steps 2, 3 and 7, then check that the key works:
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}'
{
"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. The rules for handling keys are in /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.
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:
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, then load the file into your shell again. 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 checks that it does. With your own documents, publish the text you already have and change the notice to match. See Documents and Profiles.
Step 4. Create a session on the server
The whole client is one module with one function: an HTTPS call with the secret key that returns the status and the decoded JSON, sent again only when the API answers 429.
# lib/quickstart/esign_comply.ex
defmodule Quickstart.EsignComply do
@moduledoc "There is no Hex package for the API: these are plain HTTPS calls with the secret key, made with Req."
@doc """
One call to the Esign Comply API. Returns `{status, body}`.
Req decodes a JSON body with Jason, so the keys are strings: `record["status"]`, never `record.status`.
"""
def request(method, path, opts \\ []) do
config = Application.get_all_env(:esigncomply_quickstart)
# Req does not raise on 4xx and 5xx: the status is in the response, and the error envelope is the body.
response =
[
method: method,
url: config[:api_url] <> path,
auth: {:bearer, config[:api_key]},
receive_timeout: 10_000,
# By default Req sends a GET again up to three times, on 408, 429 and 5xx answers and on connection errors.
# Here it retries a 429 only, twice at most. Nothing else is retried.
retry: &retry/2,
max_retries: 2
]
|> Keyword.merge(opts)
|> Req.request!()
{response.status, response.body}
end
# Over the rate limit: wait for Retry-After, 1 second at least and 5 at most, then try again.
defp retry(_request, %Req.Response{status: 429} = response) do
seconds =
case Integer.parse(List.first(Req.Response.get_header(response, "retry-after")) || "") do
{seconds, ""} -> seconds
_ -> 1
end
{:delay, seconds |> max(1) |> min(5) |> Kernel.*(1000)}
end
defp retry(_request, _response_or_exception), do: false
end
One Plug router carries the integration: the signup page, the two document pages, the route that creates the session, and the route that confirms the record.
# lib/quickstart/router.ex
defmodule Quickstart.Router do
use Plug.Router
use Plug.ErrorHandler
require Logger
alias Quickstart.EsignComply
@sealed ~w(recorded timestamped anchored)
# The signer. In your app this is the signed-in user, or the account you are about to create.
@signer %{
external_id: "user_7c1d",
email: "dana@example.org",
name: "Dana Whitfield",
class: "consumer",
country: "US",
region: "US-CA"
}
plug :session
plug :fetch_session
plug :match
plug :dispatch
get "/signup" do
conn
|> put_resp_content_type("text/html")
|> send_file(200, Application.app_dir(:esigncomply_quickstart, "priv/signup.html"))
end
# The document pages: each one renders a registered version, unmodified.
get "/legal/:slug" do
conn = fetch_query_params(conn)
document = config(:documents)[slug]
v = conn.query_params["v"]
version = if is_binary(v) and v =~ ~r/\A\w+\z/, do: v, else: "current"
case document && EsignComply.request(:get, "/documents/#{document}/versions/#{version}/content") do
{200, %{"version_id" => version_id, "html" => html}} ->
# Interpolation escapes nothing. The version ID goes into an attribute, so it is escaped. The document HTML is printed as it is.
page = ~s(<!doctype html><meta charset="utf-8"><article data-esc-document="#{Plug.HTML.html_escape(version_id)}">#{html}</article>)
conn |> put_resp_content_type("text/html") |> send_resp(200, page)
_ ->
json(conn, 404, %{error: "not_found"})
end
end
# Step 4: create the session with the secret key. The browser gets the client token only.
post "/api/ceremony" do
# The page that runs the ceremony: the origin the browser reports, or the scheme and host of the request.
origin = List.first(get_req_header(conn, "origin")) || "#{conn.scheme}://#{List.first(get_req_header(conn, "host"))}"
answer =
EsignComply.request(:post, "/sessions",
headers: [{"idempotency-key", "signup-#{@signer.external_id}-#{Base.url_encode64(:crypto.strong_rand_bytes(16), padding: false)}"}],
json: %{
profile: config(:profile_id),
signer: @signer,
documents: [
%{document: config(:documents)["terms"], version: "current"},
%{document: config(:documents)["privacy"], version: "current"}
],
context: %{url: origin <> "/signup", locale: "en-US", purpose: "account_signup"}
}
)
case answer do
{201, %{"client_token" => client_token, "api_url" => api_url, "documents" => documents}} ->
pinned = %{"signer_id" => @signer.external_id, "version_ids" => documents |> Enum.map(& &1["version_id"]) |> Enum.sort()}
conn
|> put_session("pinned", pinned)
|> json(200, %{clientToken: client_token, apiUrl: api_url, documents: documents})
{_status, %{"error" => %{"code" => code}}} ->
json(conn, 502, %{error: code})
_ ->
json(conn, 502, %{error: "unknown"})
end
end
# Step 6: confirm the record with the secret key before the account exists.
post "/api/signup/confirm" do
# An empty or malformed body is refused below like a made-up record ID.
record_id =
with {:ok, body, _conn} <- read_body(conn, length: 10_000),
{:ok, %{"recordId" => id}} when is_binary(id) <- Jason.decode(body) do
id
else
_ -> "missing"
end
expected = get_session(conn, "pinned") || %{}
{status, record} = EsignComply.request(:get, "/records/#{URI.encode(record_id, &URI.char_unreserved?/1)}")
confirmed =
status == 200 and is_map(record) and
record["status"] in @sealed and
record["livemode"] == config(:live) and
is_binary(expected["signer_id"]) and record["signer"]["external_id"] == expected["signer_id"] and
record["documents"] |> Enum.map(& &1["version_id"]) |> Enum.sort() == expected["version_ids"]
Logger.info(if confirmed, do: "confirmed #{record["id"]} (#{record["status"]})", else: "refused")
if confirmed do
# Only now create the account, and store record["id"] and record["receipt"] with it.
json(conn, 200, %{confirmed: true, recordId: record["id"]})
else
json(conn, 409, %{confirmed: false})
end
end
match _ do
json(conn, 404, %{error: "not_found"})
end
# Server-owned state: a cookie that Plug.Session signs. With a signing salt and no encryption salt it is signed, not
# encrypted: the visitor can read it and cannot change it. The options of a `plug` line are fixed when the module is
# compiled, so the session is set up here, where the values are read when the request arrives.
defp session(conn, _opts) do
options = Plug.Session.init(store: :cookie, key: "esc_signup", signing_salt: "esc signup", same_site: "Lax", secure: config(:live))
conn
|> Map.put(:secret_key_base, config(:secret_key_base))
|> Plug.Session.call(options)
end
# What a route raises ends here. The request's process ends, and the server and every other request carry on.
@impl Plug.ErrorHandler
def handle_errors(conn, %{reason: _reason}) do
json(conn, conn.status, %{error: "internal_error"})
end
defp config(key), do: Application.fetch_env!(:esigncomply_quickstart, key)
defp json(conn, status, body) do
conn |> put_resp_content_type("application/json") |> send_resp(status, Jason.encode!(body))
end
end
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.
The application starts Bandit with the router. This replaces the lib/quickstart/application.ex that mix new wrote:
# lib/quickstart/application.ex
defmodule Quickstart.Application do
@moduledoc false
use Application
@impl true
def start(_type, _args) do
port = Application.fetch_env!(:esigncomply_quickstart, :port)
# Bandit runs the router. Each connection gets a process of its own.
children = [{Bandit, plug: Quickstart.Router, port: port}]
Supervisor.start_link(children, strategy: :one_for_one, name: Quickstart.Supervisor)
end
end
Seven things here are specific to plain Elixir, and each one was seen in the test run.
The retry is Req's own, with a function in place of its default. With its defaults, Req sent a GET four times to a server that always answered 500, to one that closed the connection, and to one that never answered. A POST to the first two was sent once. So the default would retry the record read and not the session request. It reads Retry-After with no upper limit: with a header of 8 seconds it waited 8 seconds, twice. The function on this page retries a 429 only, for both calls, and waits for the seconds in Retry-After, 1 at least and 5 at most. Against a stand-in that always answers 429, the three calls were 1, 2 and 5 seconds apart for no header, 2 and 30, with the same Idempotency-Key each time. Req logs each retry: retry: got response with status 429, will retry in 1000ms, 2 attempts left.
Req decodes the JSON with Jason, and the keys are strings. For a record whose record["status"] was "recorded", record[:status] was nil and record.status raised KeyError. A confirm route written with record[:status] raises nothing: it refuses every record with 409. Req does not raise on a refusal either: a made-up record ID came back as status 404 with the error envelope as the body.
Each request runs in a process of its own, so the wait before a retry costs that request and nothing else. Sixty-four requests at once to a route that calls Process.sleep(3_000) were all answered after 3.0 seconds, and a page request sent meanwhile took under 0.001 seconds. In the burst test of this page, page requests were answered in about 0.001 seconds while two confirmations waited to retry.
The state is a cookie that Plug.Session signs. The browser got a cookie named esc_signup, 223 characters long, HttpOnly and SameSite=Lax. It is signed, not encrypted. Its value has three parts with dots between them: the first is Base64 for HS256, and the second, decoded from Base64, showed the signer ID and the two version IDs. The visitor can read them and cannot change them. With one character of the signature changed, with the signature cut to 10 characters, with no signature, and with another signer ID in the payload, the confirm route answered 409. With SECRET_KEY_BASE fixed, the same cookie confirmed a real record after a restart. With an encryption_salt beside the signing salt, the cookie store wrote a value that showed nothing.
The session is set up in a function plug, session/2, and not in a plug Plug.Session line. The options of a plug line are part of the module body, which runs when the code is compiled, like the module attribute in step 2. The secure flag depends on ESIGNCOMPLY_LIVE, so it is read when the request arrives. The cookie store takes its secret from conn.secret_key_base: without it the store raised cookie store expects conn.secret_key_base to be set, and with 32 characters cookie store expects conn.secret_key_base to be at least 64 bytes.
What a route raises ends that request's process and nothing else. A router without Plug.ErrorHandler answered 500 with an empty body, and Bandit logged the exception. With the handler on this page, and the API address on a closed port, the session route answered 500 with {"error":"internal_error"}, the log had [error] ** (Req.TransportError) connection refused, and the next request was answered 200.
context.url is built from the Origin header the browser sends with the POST, and from the scheme and the Host header of the request when there is none. All of it comes from the client. A request with Origin: https://evil.example was refused by the API with domain_mismatch, and the route answered 502. So was a request with Host: evil.example and no Origin. Plug does not read X-Forwarded-Proto on its own: with that header set to https and no Origin, the URL the route built still started with http://.
Step 5. Attach the ceremony in the browser
The browser SDK renders nothing. It observes the checkbox, the notice, the links and the button you built, and reports each step from the signer's browser straight to Esign Comply. Save the page as priv/signup.html. The router sends it from the application's priv folder, which a release carries with it:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Create account</title>
<style>
body { font: 16px/1.5 system-ui, sans-serif; max-width: 480px; margin: 48px auto; padding: 0 20px; }
a { color: #0b57d0; text-decoration: underline; }
button { font: inherit; padding: 10px 16px; }
</style>
</head>
<body>
<h1>Create account</h1>
<form id="signup">
<div id="assent">
<!-- The page is on screen before the script has a session, so the box stays disabled until the SDK watches it. -->
<label><input id="agree" type="checkbox" disabled /> 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 id="tos-link" href="/legal/terms">Terms of Service</a> and acknowledge the
<a id="privacy-link" href="/legal/privacy">Privacy Notice</a>.
</p>
<button id="create-account" type="submit" disabled>Create account</button>
</div>
<p id="message" role="alert"></p>
</form>
<script src="https://esigncomply.com/sdk/v1/esigncomply.js"></script>
<script type="module">
const agree = document.querySelector("#agree");
const submit = document.querySelector("#create-account");
const message = document.querySelector("#message");
// Your server creates the session and returns only the client token and the pinned documents.
const response = await fetch("/api/ceremony", { method: "POST" });
const { clientToken, apiUrl, documents } = await response.json();
const ceremony = await EsignComply.attach({ clientToken, apiUrl });
ceremony.on("change", ({ remainingSteps }) => {
submit.disabled = remainingSteps.some((step) => step !== "signature.applied");
});
// Point each link at the exact version this session pinned, then report it.
const links = [document.querySelector("#tos-link"), document.querySelector("#privacy-link")];
for (const [i, link] of links.entries()) {
link.search = "?v=" + documents[i].version_id;
await ceremony.presentDocument({ versionId: documents[i].version_id, mode: "hyperlink", link });
}
await ceremony.observeAssent({
region: document.querySelector("#assent"), // notice, links, checkbox, button
checkbox: agree,
submit,
});
agree.disabled = false; // the SDK watches the box from here on. Only the user ticks it.
document.querySelector("#signup").addEventListener("submit", async (event) => {
event.preventDefault();
try {
const result = await ceremony.complete(); // the signing act, from the signer's own click
// The result came to the browser. Your server 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.textContent = confirmed.ok
? `Account created. Record ${result.recordId}`
: "We could not confirm whether your acceptance was recorded. Please wait while we check.";
} catch (error) {
message.textContent = error.message;
}
});
</script>
</body>
</html>
Start the app from the shell that loaded .env:
mix run --no-halt
[info] Running Quickstart.Router with Bandit 1.15.0 at 0.0.0.0:4000 (http)
That is every interface of the machine: in the test the page answered on the machine's own address too, not only on localhost.
Open http://localhost:4000/signup. The button stays disabled until the box is ticked. Tick it, click Create account, and the page shows:
Account created. Record rec_AQbPNLmCYcu45kJHSQwA
The checkbox starts unchecked and disabled. The page is on screen before the script has a session, and the script enables the box once the SDK observes it: a box ticked before that fails CR-01. In a test with the session request held back, a click on the box did nothing. One page load sent one POST /api/ceremony.
Each link opens a document page on your own server that renders the registered version. The route builds that page with string interpolation, which escapes nothing. The document arrives as it is, which is what this page needs, and the version ID is escaped with Plug.HTML.html_escape because it goes into an attribute. In a test with Plug.HTML.html_escape around the document too, the page showed the tags as text and the SDK reported a finding for CR-08 at Block level: the page behind the link did not match the registered version.
Step 6. Confirm the record on the server
The result of complete() was delivered to the browser, so your server does not trust it. The route for POST /api/signup/confirm 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 in the session cookie; and the document versions are exactly the ones this server pinned there. This step is never optional.
The app logs one line for each confirmation:
[info] confirmed rec_AQbPNLmCYcu45kJHSQwA (recorded)
A record ID that was made up is refused with status 409. So is a real record ID sent without the cookie, a body that is not JSON, an empty body, and a body whose recordId is a number:
curl -s -X POST http://localhost:4000/api/signup/confirm \
-H "Content-Type: application/json" -d '{"recordId":"rec_made_up"}'
{"confirmed":false}
See Server confirmation 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. The checker is a Node.js command line tool, so it needs Node.js 20.19 or later, in a folder of its own:
mkdir -p esc-check && cd esc-check
npm init -y && npm install esigncomply playwright
npx playwright install chromium
npx esigncomply check --url http://localhost:4000/signup --callback http://localhost:4000/api/signup/confirm
The report for this page's code, shortened:
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:4000/api/signup/confirm answered 409.
Ceremonies
390x844 record rec_avuD3F3XBXaxX3uYvjGQ session ses_Sv9KM3KUpDuTtBsGb2Yc, 5 events
768x1024 record rec_Avc3u7wZgoM7jTDgfEYA session ses_subR9CYoLyhXBprWGfen, 5 events
1440x900 record rec_tcTYNKpm6P5Ljq5JexaL session ses_vN6ojbB5RHtJDq52hQa6, 5 events
Summary: 0 block, 0 warn, 27 pass.
The app logged a confirmed line for each of the three records.
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, and every flag of the command is on the CLI page.
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.
- Register your production domain and verify it. See Register a domain.
- Add your organization's legal name, country and address under Go live in the dashboard.
- 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 server over:
- Build a release with
MIX_ENV=prod mix releaseand start it with_build/prod/rel/esigncomply_quickstart/bin/esigncomply_quickstart start. In the test the release was built with none of the variables set. It was 68 MB with the Erlang runtime inside, ran as one process of about 170 MB, and recorded the signature shown in step 5. - The release needs no Mix and no project folder. Started from another folder it answered
/signupwith200, wheremix runended withCannot execute "mix run" without a Mix.Project. - Give the image that runs the release CA certificates. In the official
-slimimage, an https call with Req from the release raisedRuntimeError: default CA trust store not available. In the full image the same call was answered200. Over plain http to the test API, the release worked in both. - Set the live key as
ESIGNCOMPLY_API_KEYand setESIGNCOMPLY_LIVE=truein production only. In the test with that variable set, the confirm route refused a test record with409, and the cookie was markedsecure. The flag follows the variable and does not look at the request: serve the site over HTTPS. - Set
PORTwhen your host gives you one. The app listens on 4000 otherwise. - Keep one
SECRET_KEY_BASEfor every instance and every restart, and store the record ID and the receipt beside the user. In the test, a cookie signed with another secret was refused with409.
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
System.EnvError: could not fetch environment variable "SECRET_KEY_BASE" because it is not setwhen the app starts. The variables are not in the environment of the shell that starts the app. Runset -a; . ./.env; set +ain that shell first. WithESIGNCOMPLY_API_KEYset and empty, the app started and the session route answered502withmissing_api_key.domain_mismatchfrom/api/ceremony.context.urlis built from theOriginorHostheader, and that host is not on the test allowlist. Test keys work onlocalhostand127.0.0.1at any port. Add other hosts under Domains in the dashboard. Seedomain_mismatch.RuntimeError: default CA trust store not availableon the first call over https. The machine or image has no CA certificates. In the test this was the official-slimcontainer image, wheremix local.hexfailed for the same reason. Install theca-certificatespackage there.429when the confirm route reads the record. The retry function waits for the seconds inRetry-After, 1 at least and 5 at most, and Req sends the request again, up to twice. Nothing else is retried. In the test, four confirmations sent at once from the session that signed all answered200, two of them a second later than the others. The API's log showed why: two reads got429and passed on the next attempt. Seerate_limit_exceeded. When the route answers409for a real record, the cause is aSECRET_KEY_BASEthat changed.
Questions about the Elixir quickstart
Is there a Hex package for Esign Comply?
No. The server SDK exists for Node.js only. An Elixir app calls the REST API directly, and this quickstart does it with Req in one function. The four dependencies are the web server, the router, the HTTP client and the JSON library, and none is for the API.
Why Bandit and not Cowboy?
Because it is the server a new Phoenix app starts with, so this page and the Phoenix one run on the same server. Plug's documentation names both Cowboy and Bandit. Bandit's documentation says it is written entirely in Elixir and has been the default HTTP server for Phoenix since release 1.7.11.
Why is the key read in config/runtime.exs?
Because that file runs when the app starts, on the machine that runs it. In the test, a value read in config/config.exs or in a module attribute was the build machine's value after the release was started elsewhere with another one, and it was written into the release's files.
Can the visitor read the session cookie?
Yes, and that is safe. The cookie is signed, not encrypted: decoded from Base64 it showed the signer ID and the two version IDs, and nothing else is in it. The visitor cannot change it. In the test a cookie with a changed signature or a changed payload was refused with status 409.
What does the wait before a retry cost?
One process, and only for the request that waits. Each request runs in a process of its own. In the test, sixty-four requests that each slept 3 seconds were all answered after 3.0 seconds, and a page request sent meanwhile took under 0.001 seconds.
When is the Phoenix quickstart the better start?
When your app already runs on Phoenix. Phoenix brings the CSRF check, HEEx templates and the endpoint with its configuration, and its quickstart uses them: the same two calls sit in a controller. This page is for a service with no Phoenix, where a Plug router and four routes are enough.
Does the Elixir 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 Elixir: what the integration gives you on this stack, with the things to watch for.
- Add e-signatures and clickwrap with Phoenix: the same calls in a controller, with HEEx and the CSRF token.
- Server confirmation: the checks in step 6 and the
record.completedwebhook. - Sessions API and Records API: every field of the two calls this app makes.
- All quickstarts.
Run on 2026-11-26 with Elixir 1.20.5 on Erlang/OTP 29 (the official Elixir container image), Plug 1.20.4, Bandit 1.15.0, Req 0.7.5 with Finch 0.25.0 and Mint 1.11.0, Jason 1.4.5 and plug_crypto 2.2.1, with no Phoenix, under mix run --no-halt and as a release built with MIX_ENV=prod mix release, with the browser SDK script build and the conformance check from esigncomply 1.0.4, against the API in test mode over plain http. Its calls to the API over https were not run.
Last updated · API version 2026-11-21