# Add e-signatures and clickwrap to Sinatra

> Add e-signatures and clickwrap to Sinatra with four routes and Net::HTTP: POST /v1/sessions, GET /v1/records and the encrypted cookie session. Tested code.

Source: https://esigncomply.com/sinatra

Stack · Sinatra

To add e-signatures and clickwrap to Sinatra, call the REST API from your routes with `Net::HTTP`: there is no gem, because the server SDK exists for Node.js only. One route creates the session with the secret key and keeps the pinned versions in Sinatra's encrypted cookie session, and another confirms the record. Esign Comply seals each acceptance.

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/sinatra)

No gem for the API: Net::HTTP is enough. Sinatra needs rackup and puma to start

[Sinatra quickstart](https://esigncomply.com/docs/quickstart/sinatra)

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

Last updated November 26, 2026

Run in Sinatra before publishing

**Session route**

app.rb (excerpt)

```ruby
# 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 address Rack worked out.
  origin = request.env["HTTP_ORIGIN"] || request.base_url
  status, created = esc(:post, "/sessions",
    idempotency_key: "signup-#{SIGNER[:external_id]}-#{SecureRandom.uuid}",
    body: {
      profile: ENV["ESIGNCOMPLY_PROFILE_ID"],
      signer: SIGNER,
      documents: [
        { document: DOCUMENTS["terms"], version: "current" },
        { document: DOCUMENTS["privacy"], version: "current" }
      ],
      context: { url: "#{origin}/signup", locale: "en-US", purpose: "account_signup" }
    })
  halt json(502, error: created.dig("error", "code") || "unknown") unless status == 201

  session[:signer_id] = SIGNER[:external_id]
  session[:version_ids] = created["documents"].map { |d| d["version_id"] }.sort
  json 200, clientToken: created["client_token"], apiUrl: created["api_url"], documents: created["documents"]
end
```

**The API call**

app.rb (excerpt)

```ruby
# One call to the Esign Comply API. Returns [status, parsed JSON].
def esc(method, path, body: nil, idempotency_key: nil)
  uri = URI("#{API}#{path}")
  request = (method == :post ? Net::HTTP::Post : Net::HTTP::Get).new(uri)
  request["Authorization"] = "Bearer #{ENV['ESIGNCOMPLY_API_KEY']}"
  request["Idempotency-Key"] = idempotency_key if idempotency_key
  if body
    request["Content-Type"] = "application/json"
    request.body = JSON.generate(body)
  end
  response = nil
  3.times do |attempt|
    # Net::HTTP does not raise on 4xx and 5xx: the status is here, and the error envelope is the body.
    response = Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == "https", open_timeout: 5, read_timeout: 10) do |http|
      http.request(request)
    end
    # Over the rate limit: wait for Retry-After (1 to 5 seconds) and try again, twice at most. Nothing else is retried.
    break unless response.code == "429" && attempt < 2
    sleep response["Retry-After"].to_f.clamp(1, 5)
  end
  [response.code.to_i, JSON.parse(response.body)]
end
```

**Confirm route**

app.rb (excerpt)

```ruby
# Step 6: confirm the record with the secret key before the account exists.
post "/api/signup/confirm" do
  body = JSON.parse(request.body.read) rescue {} # an empty or malformed body is refused below
  record_id = body.is_a?(Hash) && body["recordId"].is_a?(String) ? body["recordId"] : "missing"
  status, record = esc(:get, "/records/#{Rack::Utils.escape_path(record_id)}")

  confirmed = status == 200 &&
              SEALED.include?(record["status"]) &&
              record["livemode"] == LIVE &&
              !session[:signer_id].nil? && record.dig("signer", "external_id") == session[:signer_id] &&
              record["documents"].map { |d| d["version_id"] }.sort == session[:version_ids]

  logger.info(confirmed ? "confirmed #{record['id']} (#{record['status']})" : "refused")
  halt json(409, confirmed: false) unless confirmed

  # Only now create the account, and store record["id"] and record["receipt"] with it.
  json 200, confirmed: true, recordId: record["id"]
end
```

**Session**

app.rb (excerpt)

```ruby
# Server-owned state: Sinatra's cookie session. The data travels in the cookie, encrypted with session_secret,
# so the browser carries it and cannot read or change it. Without a fixed secret Sinatra makes a new one at every start.
set :sessions, httponly: true, same_site: :lax, secure: LIVE
set :session_secret, ENV.fetch("SESSION_SECRET")
```

Integrate with Sinatra

## How do you integrate Esign Comply with Sinatra?

In Sinatra the integration is four routes in one `app.rb`. `set :sessions` keeps the versions the server pinned in a cookie that is encrypted with `session_secret`, so nothing sits in memory and a restart loses nothing. The document page is an ERB view, and ERB in Sinatra prints the registered HTML as it is.

Sinatra is a DSL for quickly creating web applications in Ruby with minimal effort.

Source: [Sinatra README](https://github.com/sinatra/sinatra/blob/main/README.md), read on November 26, 2026.

[Sinatra quickstart](https://esigncomply.com/docs/quickstart/sinatra) · [All stacks](https://esigncomply.com/stacks)

Where each part lives in Sinatra

- **Session route** · `app.rb`
- **The API call** · `app.rb`
- **Confirm route** · `app.rb`
- **Session** · `app.rb`

Run on 2026-11-26 with Sinatra 4.2.2, Rack 3.2.9, rack-session 2.1.2, rack-protection 4.2.2, rackup 2.3.1 and Puma 8.1.3 on Ruby 3.4.13 (the official Ruby container image), under ruby app.rb and under Puma with config.ru, with the browser SDK script build and the conformance check from esigncomply 1.0.4, against the API in test mode.

Copy-paste prompt

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

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

Sinatra facts
- There is no Esign Comply gem. Do not install or invent one. The routes call the REST API at https://esigncomply.com/v1 with Net::HTTP, Authorization: Bearer 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. Ruby does not read .env files on its own. Never print the key.
- Sinatra 4 needs the rackup gem and a web server gem such as puma to start.
- Keep the signer ID and the pinned version IDs in session. Set session_secret from the environment, 64 bytes or more: without it Sinatra makes a new secret at every start and every session is lost.
- Rack::Protection does not refuse a POST with the Origin of another site: under Sinatra it empties the session and lets the request through. Never treat reaching a route as proof of where the request came from.
- In the development environment Sinatra answers 403 to a Host it does not know. In production any host is permitted unless host_authorization is set.
- ERB in Sinatra does not escape. Print the document HTML as it is, and escape everything else you print with Rack::Utils.escape_html.
- 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. Route for POST /api/ceremony: call POST /v1/sessions with an Idempotency-Key, save the signer ID and the pinned version IDs in session, and return only clientToken, apiUrl and documents.
4. Route 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. Route 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 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:4567/signup --callback http://localhost:4567/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 Sinatra?

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

- **Rack::Protection empties the session and lets a cross-site POST through**

  Sinatra's README says it uses Rack::Protection to defend your application against common, opportunistic attacks. In the test on Sinatra 4.2.2 a `POST` with a valid session cookie and `Origin: https://evil.example` was not refused: it reached the route with an empty session, because Sinatra sets the reaction to `drop_session`. The confirm route answered `409`, since it had no pinned versions to compare with.

  Source: [Sinatra README, Configuring attack protection](https://github.com/sinatra/sinatra/blob/main/README.md#configuring-attack-protection), read on November 26, 2026.

- **Without session_secret a restart loses every session**

  Sinatra's README says a secret is generated for you by default and changes with every restart of your application. In the test a value saved before a restart was gone after it, and with `SESSION_SECRET` fixed the same cookie confirmed a real record before and after a restart. A 32-character secret stopped the app at start: `invalid secret: 32, must be >=64`.

  Source: [Sinatra README, Session Secret Security](https://github.com/sinatra/sinatra/blob/main/README.md#session-secret-security), read on November 26, 2026.

- **Sinatra answers 403 to an unknown Host in development only**

  Sinatra's README says `permitted_hosts` is set to `.localhost`, `.test` and any IP address in the development environment, and that any hostname is permitted by default in any other. In the test a request with `Host: evil.example` got `403` and `Host not permitted` in development. In production it reached the session route, and the API refused the session with `domain_mismatch`.

  Source: [Sinatra README, Available Settings](https://github.com/sinatra/sinatra/blob/main/README.md#available-settings), read on November 26, 2026.

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

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

- Quickstart

  **[Sinatra quickstart](https://esigncomply.com/docs/quickstart/sinatra)**

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

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

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

No. There is no gem, because the server SDK exists for Node.js only. A Sinatra app calls the REST API directly with the secret key, and the quickstart does it with `Net::HTTP` in one method. The Gemfile lists Sinatra, `rackup` and Puma, and nothing for the API.

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

In the route `post "/api/ceremony"`, with a `POST` to `/v1/sessions` that carries the secret key and an `Idempotency-Key`. The route saves the pinned versions in `session` and returns only the client token, the API URL and the documents as JSON.

### Can the visitor read or change the Sinatra session cookie?

No. In the test on Sinatra 4.2.2 with rack-session 2.1.2 the `rack.session` cookie was encrypted: decoded from base64 it showed neither the signer ID nor a version ID. A cookie with one character changed was treated as empty, and the confirm route answered `409`.

### Which gems does Sinatra need before it starts?

`rackup` and a web server such as Puma, beside `sinatra` itself. In the test an app with only `sinatra` in its Gemfile printed `Sinatra could not start, the required gems weren't found!`, and one with `rackup` and no server stopped with `Couldn't find handler for: puma, falcon, thin, webrick.`

### Why is the session cookie missing when ESIGNCOMPLY_LIVE is true?

Because the cookie is then `Secure`, and Rack sets it only on a request it sees as HTTPS. In the test a request over plain HTTP got no session cookie at all, and the same request with `X-Forwarded-Proto: https` got one. Behind a proxy that terminates TLS, the proxy has to send that header.

### Other stacks

- [Rails](https://esigncomply.com/rails)
- [Flask](https://esigncomply.com/flask)
- [PHP](https://esigncomply.com/php)

### Platforms used with Sinatra

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

[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 four routes to your Sinatra app. Leave the record to us.

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

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

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