# Add e-signatures and clickwrap to Phoenix

> Add e-signatures and clickwrap to Phoenix with one controller and Req: POST /v1/sessions, GET /v1/records, HEEx, the session cookie and the CSRF token.

Source: https://esigncomply.com/phoenix

Stack · Phoenix

To add e-signatures and clickwrap to Phoenix, call the REST API from a controller with Req: there is no Hex package, because the server SDK exists for Node.js only. One action creates the session with the secret key and keeps the pinned versions in the Phoenix session, another 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/phoenix)

No Hex package for the API: add Req to the generated app, and nothing else

[Phoenix quickstart](https://esigncomply.com/docs/quickstart/phoenix)

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

Last updated November 26, 2026

Run in Phoenix before publishing

**Session action**

lib/quickstart_web/controllers/signup_controller.ex (excerpt)

```
# Step 4: create the session with the secret key. The browser gets the client token only.
def ceremony(conn, _params) do
  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"}
        ],
        # The page that runs the ceremony. url/1 builds it from the endpoint's :url settings, not from the request.
        context: %{url: url(~p"/signup"), locale: "en-US", purpose: "account_signup"}
      }
    )

  case answer do
    {201, %{"client_token" => client_token, "api_url" => api_url, "documents" => documents}} ->
      # Server-owned state: the Phoenix session, a cookie that is signed and not encrypted. The visitor can read it and cannot change it.
      pinned = %{"signer_id" => @signer.external_id, "version_ids" => documents |> Enum.map(& &1["version_id"]) |> Enum.sort()}

      conn
      |> put_session(:pinned, pinned)
      |> json(%{clientToken: client_token, apiUrl: api_url, documents: documents})

    {_status, %{"error" => %{"code" => code}}} ->
      conn |> put_status(502) |> json(%{error: code})

    _ ->
      conn |> put_status(502) |> json(%{error: "unknown"})
  end
end
```

**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.fetch_env!(:quickstart, :esigncomply)

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

**Confirm action**

lib/quickstart_web/controllers/signup_controller.ex (excerpt)

```
# Step 6: confirm the record with the secret key before the account exists.
def confirm(conn, params) do
  # Plug.Parsers has decoded the JSON body into params. A body that is not JSON never gets here: Phoenix answers 400.
  record_id = if is_binary(params["recordId"]), do: params["recordId"], else: "missing"
  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, %{confirmed: true, recordId: record["id"]})
  else
    conn |> put_status(409) |> json(%{confirmed: false})
  end
end
```

**Pipeline and routes**

lib/quickstart_web/router.ex (excerpt)

```
# For the two JSON routes the signup page calls. They need what :browser has and :api has not:
# the session, which holds the pinned versions, and the CSRF check. They answer in JSON.
pipeline :browser_json do
  plug :accepts, ["json"]
  plug :fetch_session
  plug :protect_from_forgery
  plug :put_secure_browser_headers
end

scope "/", QuickstartWeb do
  pipe_through :browser

  get "/", PageController, :home
  get "/signup", SignupController, :show
  get "/legal/:slug", SignupController, :legal
end

scope "/api", QuickstartWeb do
  pipe_through :browser_json

  post "/ceremony", SignupController, :ceremony
  post "/signup/confirm", SignupController, :confirm
end
```

Integrate with Phoenix

## How do you integrate Esign Comply with Phoenix?

In Phoenix the integration is one controller, two HEEx templates and a pipeline for the two JSON routes. The page sends the token from `get_csrf_token()` with each POST, the document template prints the registered HTML with `raw/1`, and `url(~p"/signup")` takes `context.url` from the endpoint's settings. `config/runtime.exs` reads the key when the app starts, under `mix phx.server` and in a release.

Phoenix's documentation says: Phoenix is a web development framework written in Elixir which implements the server-side Model View Controller (MVC) pattern.

Source: [Phoenix documentation, Overview](https://phoenix.hexdocs.pm/overview.html), read on November 26, 2026.

[Phoenix quickstart](https://esigncomply.com/docs/quickstart/phoenix) · [All stacks](https://esigncomply.com/stacks)

Where each part lives in Phoenix

- **Session action** · `lib/quickstart_web/controllers/signup_controller.ex`
- **The API call** · `lib/quickstart/esign_comply.ex`
- **Confirm action** · `lib/quickstart_web/controllers/signup_controller.ex`
- **Pipeline and routes** · `lib/quickstart_web/router.ex`

Run on 2026-11-26 with Phoenix 1.8.17 (from mix phx.new with --no-ecto, --no-mailer, --no-dashboard, --no-gettext and --no-assets), Phoenix LiveView 1.2.15 for HEEx, Plug 1.20.4, Bandit 1.15.0, Req 0.7.5 and Jason 1.4.5 on Elixir 1.20.5 and Erlang/OTP 29 (the official Elixir container image), under mix phx.server in development 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, a LiveView form and the default asset pipeline were not run.

Copy-paste prompt

## What prompt adds Esign Comply clickwrap to a Phoenix 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 Phoenix, 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 Phoenix

```
Add Esign Comply clickwrap to my Phoenix 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/phoenix.md (the steps and the tested code for Phoenix)
- https://esigncomply.com/setup.md (the order of API calls)
- https://esigncomply.com/auth.md (how to handle the keys)

Phoenix facts
- There is no Esign Comply package on Hex. Do not install or invent one. A small module 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 in config/config.exs: that file is evaluated when the code is compiled, and a release would carry the value of the build machine. Phoenix does not read .env files. Never print the key.
- The two JSON routes need the session and the CSRF check. The generated :api pipeline has neither, and :browser accepts html only. Give them a pipeline with accepts ["json"], fetch_session and protect_from_forgery.
- Every POST from the page carries the token from the csrf-token meta tag in the x-csrf-token header, or Phoenix answers 403.
- Build context.url with url(~p"/signup"). It comes from the endpoint's :url configuration, which is PHX_HOST in production, not from the request.
- Keep the pinned version IDs in the session with put_session. The Phoenix session cookie is signed, not encrypted, unless the endpoint sets an encryption_salt: the visitor can read it, so put nothing secret in it.
- HEEx escapes what it prints. Render the registered document HTML with raw/1, and nothing else.
- 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 held between 1 and 5 seconds, and max_retries: 2. Req decodes JSON with Jason: the keys are strings.
- A release listens only with PHX_SERVER=true, and needs SECRET_KEY_BASE and PHX_HOST.
- 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. Action for POST /api/ceremony: call POST /v1/sessions with an Idempotency-Key, save the signer ID and the pinned version IDs in the session, and return only clientToken, apiUrl and documents.
4. Action for GET /legal/:slug: 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. Action for POST /api/signup/confirm: call GET /v1/records/{id} and require: status is "recorded", "timestamped" or "anchored"; livemode is as expected; the signer ID and version IDs equal the ones in the session. 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 Phoenix?

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

- **Neither generated pipeline fits the two JSON routes**

  In the test on Phoenix 1.8.17, the session action behind `:api` was reached with no CSRF token and raised `ArgumentError: session not fetched, call fetch_session/2`. Behind `:browser` it answered `406` to a request with `Accept: application/json`, because that pipeline accepts html. The quickstart gives the routes a pipeline with `accepts ["json"]`, `fetch_session` and `protect_from_forgery`.

- **check_origin guards sockets, not your POST routes**

  Phoenix's documentation describes `:check_origin` as a check of the `origin` header by the socket transports, against the host in the endpoint's `:url`. In the test release, a WebSocket handshake with `Origin: https://evil.example` was answered `403`, and a `POST` to the session route with the same header, the CSRF token and the cookie was answered `200`. The JSON routes rely on the CSRF token.

  Source: [Phoenix documentation, Phoenix.Endpoint](https://phoenix.hexdocs.pm/Phoenix.Endpoint.html), read on November 26, 2026.

- **Without PHX_HOST the release asks for sessions on example.com**

  `url(~p"/signup")` builds `context.url` from the endpoint's `:url` settings, and the generated `config/runtime.exs` sets the host from `PHX_HOST` with `example.com` as the default. In the test release with the variable not set, the API refused the session with `domain_mismatch` and the action answered `502`. Request headers play no part: `Host` and `X-Forwarded-Host` did not change the URL.

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

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

- Quickstart

  **[Phoenix quickstart](https://esigncomply.com/docs/quickstart/phoenix)**

  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 Phoenix?

The same record on every stack and platform. Your Phoenix 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 Phoenix

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

No. There is no Hex package, because the server SDK exists for Node.js only. A Phoenix app calls the REST API directly with the secret key, and the quickstart does it with Req in one function. Req is the only dependency it adds to the generated app.

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

In a controller action behind `POST /api/ceremony`, with a call to `POST /v1/sessions` that carries the secret key and an `Idempotency-Key`. The action puts the pinned versions in the session and renders only the client token, the API URL and the documents as JSON.

### Why is the signup page a controller page and not a LiveView?

Because that is what was tested. The browser SDK observes the checkbox, the links and the button it is given, and the page's script enables the checkbox itself. A LiveView form was not run, so the quickstart keeps the form in a controller template and claims nothing about LiveView.

### Does HEEx escape the registered document HTML?

Yes, unless the template calls `raw/1`. In the test with `{@html}` in the document template, the page showed every tag as text and the SDK reported a finding for CR-08 at Block level. With `{raw(@html)}` the registered HTML arrives unmodified, which is what the page has to show.

### Do a script tag and an inline script fit Phoenix's default security headers?

Yes. `put_secure_browser_headers` sent `content-security-policy: base-uri 'self'; frame-ancestors 'self';`, which names no script source. The SDK's script tag and the page's inline module script both ran, and the conformance check passed with those headers on every answer. HEEx left the curly braces of the inline script alone.

### Other stacks

- [Elixir](https://esigncomply.com/elixir)
- [Rails](https://esigncomply.com/rails)
- [Spring Boot](https://esigncomply.com/spring-boot)

### Platforms used with Phoenix

- [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)

## Add one controller to your Phoenix app. Leave the record to us.

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

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

Phoenix is a trademark of its owner. Esign Comply is not affiliated with it. What this page says about Phoenix is from Phoenix's documentation or from a test run, as marked, on November 26, 2026. `/phoenix.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.
