# Add e-signatures and clickwrap to Elixir

> Add e-signatures and clickwrap to plain Elixir with Plug, Bandit and Req: POST /v1/sessions, GET /v1/records and a cookie signed by Plug.Session.

Source: https://esigncomply.com/elixir

Stack · Elixir

To add e-signatures and clickwrap to Elixir, call the REST API with Req: there is no Hex package, because the server SDK exists for Node.js only. One Plug router on Bandit, without Phoenix, creates the session, keeps the pinned versions in a signed cookie and confirms the record. Esign Comply seals each acceptance as an independent record.

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

[Get an API key](https://esigncomply.com/signup) · [Read the docs](https://esigncomply.com/docs/quickstart/elixir)

No Hex package for the API: Req makes the calls. The project lists Bandit, Plug, Req and Jason

[Elixir quickstart](https://esigncomply.com/docs/quickstart/elixir)

Free plan: 10 live signatures a month and a full test mode. No card required.

Last updated November 26, 2026

Run in Elixir before publishing

**The API call**

`lib/quickstart/esign_comply.ex`

```
# 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
```

**Create the session**

lib/quickstart/router.ex (excerpt)

```
# 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
```

**Confirm**

lib/quickstart/router.ex (excerpt)

```
# 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
```

**Signed cookie**

lib/quickstart/router.ex (excerpt)

```
# 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
```

Integrate with Elixir

## How do you integrate Esign Comply with Elixir?

In plain Elixir the integration is three modules: a client with one function that calls Req, a `Plug.Router` with the four routes, and an application that starts Bandit. `config/runtime.exs` reads the key when the app starts, so a release carries no secret. `Plug.Session` signs the cookie that holds the pinned versions, with a key it derives from `SECRET_KEY_BASE`, and the visitor can read that cookie and cannot change it.

Plug's documentation says: Plug allows you to build web applications from small pieces and run them on different web servers.

Source: [Plug documentation, README](https://plug.hexdocs.pm/readme.html), read on November 26, 2026.

[Elixir quickstart](https://esigncomply.com/docs/quickstart/elixir) · [All stacks](https://esigncomply.com/stacks)

Where each part lives in Elixir

- **The API call** · `lib/quickstart/esign_comply.ex`
- **Create the session** · `lib/quickstart/router.ex`
- **Confirm** · `lib/quickstart/router.ex`
- **Signed cookie** · `lib/quickstart/router.ex`

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.

Copy-paste prompt

## What prompt adds Esign Comply clickwrap to a Elixir app?

Paste this into Cursor, Claude Code or the AI coding tool that is open on your project. It names the packages that exist, where the secret key goes in Elixir, what to build and what never to do, and it ends with the rules block for your project.

The rules block lives at [/rules.md](https://esigncomply.com/rules.md). Added to your project's instruction file, it makes every later session build signing and acceptance flows the same way. The [prompt generator](https://esigncomply.com/product/prompt-generator) writes the long version, with your own document and profile IDs.

[Pages for each AI tool](https://esigncomply.com/build)

Prompt: Esign Comply clickwrap in Elixir

```
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
```

3 things to watch

## What goes wrong when you add e-signatures in Elixir?

These are specific to Elixir. Each one was seen while the quickstart's code was run, or is in Elixir's own documentation.

- **A key read in config/config.exs is fixed into the release**

  Mix's documentation says `config/config.exs` is evaluated whenever you compile your code or assemble the release. In a test release built with a variable set to one value and started with another, the value read in `config/config.exs` and the one read in a module attribute were the build machine's, and that value was in the release's `sys.config` file. The quickstart reads the key in `config/runtime.exs`, which runs when the app starts.

  Source: [Mix documentation, mix release](https://mix.hexdocs.pm/Mix.Tasks.Release.html), read on November 26, 2026.

- **Req retries a GET by default and never a POST**

  Req's documentation gives the default: GET and HEAD requests are retried on 408, 429 and 5xx answers and on transport errors, three times. In the test on Req 0.7.5 a `GET` to a server that always answered `500` was sent four times and a `POST` once, and with `Retry-After: 8` Req waited 8 seconds, twice. The quickstart passes a function that retries a `429` only, for both calls, twice, and waits 5 seconds at most.

  Source: [Req documentation, Req.Steps](https://req.hexdocs.pm/Req.Steps.html), read on November 26, 2026.

- **The official slim image cannot call an https API**

  In the test the release ran in the official `-slim` Elixir image over plain http. An https call with Req from the same release raised `RuntimeError: default CA trust store not available`, and `mix local.hex` failed there with `no CA certificates were found on the system`. In the full image the https call was answered `200`. Install `ca-certificates` in the image that runs the release.

## Where are the Elixir quickstart and the API reference?

Start with the quickstart: it carries every file this page excerpts, in the order you write them.

- Quickstart

  **[Elixir quickstart](https://esigncomply.com/docs/quickstart/elixir)**

  Step by step, from install to your first sealed test record, with every file and the output of each step.

- Reference

  **[API reference](https://esigncomply.com/docs/api)**

  Every endpoint, field and error code. Sessions, records and documents are the three this page uses.

- Guide

  **[Server confirmation](https://esigncomply.com/docs/guides/server-confirmation)**

  The one place access is granted: what to compare, and the webhook that backs the check up.

Verifiable

## What does Esign Comply record for a signature in Elixir?

The same record on every stack and platform. Your Elixir code creates the session and confirms the record, and the browser SDK reports what happened on the page. Esign Comply seals the result where your code cannot change it. The record itself is described on [Evidence and verification](https://esigncomply.com/product/evidence).

- **Observed and asserted fields**

  Every field is tagged. Observed is what the browser SDK and the API saw: the box unchecked at load, the tick from a trusted user event, the notice text, the terms version by hash, the server time. Asserted is what your app said, such as the user's email.

- **A signed receipt**

  `complete()` returns a receipt signed with ES256, using keys you do not hold. Your server stores it next to the user, and `GET /v1/records/{id}/receipt` returns it again.

- **An external timestamp**

  An outside authority timestamps the hash of every live record (RFC 3161), so the time on the record does not rest on your clock or on ours.

- **An offline verifier**

  Each record has an evidence report (PDF) and an evidence package (ZIP). Anyone you send the package to checks the acceptance with the open-source `esigncomply-verify`, without an account.

[How sealing and verification work](https://esigncomply.com/product/evidence) · [Observed and asserted, in the docs](https://esigncomply.com/docs/concepts/observed-and-asserted) · [The offline verifier](https://esigncomply.com/docs/sdk/verify)

Record

`rec_Z4m8`

simple · L1

Recorded

Written durably, receipt signed with ES256

Timestamped

External RFC 3161 token over the record hash

Anchored

Public anchor pending

Checkbox changed by a trusted user event · observed

Terms of Service, version dv_3kT9 · observed

Server time 2026-11-21T15:03:20.291Z · observed

Signer email dana@example.org · asserted

record_hash sha256:5be7… · example record

## Questions about e-signatures in Elixir

### Is there an Esign Comply SDK for Elixir?

No. There is no Hex package, because the server SDK exists for Node.js only. An Elixir app calls the REST API directly with the secret key, and the quickstart does it with Req in one function. Its four dependencies are Bandit, Plug, Req and Jason.

### Where do I create the session in Elixir?

In the route for `POST /api/ceremony` of a `Plug.Router`, with a `POST` to `/v1/sessions` that carries the secret key and an `Idempotency-Key`. It puts the pinned versions in the signed session cookie and returns only the client token, the API URL and the documents.

### When should I use Phoenix instead of plain Elixir?

When your app already runs on Phoenix, or needs what it brings: CSRF protection, HEEx templates and the endpoint with its configuration. The Phoenix page shows the same two calls in a controller. Plain Elixir fits a small service where a Plug router and four routes are enough, and both run on Bandit.

### Why does a confirm route written with atom keys refuse every record?

Because Req decodes JSON with Jason, and the keys are strings. In the test `record[:status]` was `nil` for a record whose `record["status"]` was `recorded`, and nothing was raised: the comparison fails and the route answers `409`. `record.status` raised `KeyError`. The quickstart reads every field with a string key.

### What does the sleep before a retry cost on the BEAM?

One process, for the request that waits. Each request runs in a process of its own, so nothing else is held up. 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.

### Other stacks

- [Phoenix](https://esigncomply.com/phoenix)
- [Ruby](https://esigncomply.com/ruby)
- [Go](https://esigncomply.com/go)

### Platforms used with Elixir

- [Fly.io](https://esigncomply.com/fly-io)
- [Render](https://esigncomply.com/render)
- [Railway](https://esigncomply.com/railway)

[All stacks](https://esigncomply.com/stacks) · [All platforms](https://esigncomply.com/platforms) · [Clickwrap API](https://esigncomply.com/clickwrap) · [E-signature API](https://esigncomply.com/sign)

## Call the API from the Elixir app you already run. Leave the record to us.

[Get an API key](https://esigncomply.com/signup) · [Read the docs](https://esigncomply.com/docs/quickstart/elixir)

Free plan: 10 live signatures a month and a full test mode. No card required.

Elixir is a trademark of its owner. Esign Comply is not affiliated with it. What this page says about Elixir is from Elixir's documentation or from a test run, as marked, on November 26, 2026. `/elixir.md` is this page as Markdown.

---

Every page on esigncomply.com has a Markdown version at the same URL plus `.md` (the home page is `https://esigncomply.com/index.md`). https://esigncomply.com/llms.txt lists them.

---

Esign Comply is the e-signature API and clickwrap API for developers who build their own signing flow in their own UI: it supplies the ceremony rules as a generated prompt for AI coding tools, records events in direct browser ceremonies, and seals independent, verifiable evidence.
