# Add e-signatures and clickwrap with Rust

> Build a signup clickwrap in Rust with axum, reqwest, serde and a private cookie from axum-extra, calling the Esign Comply REST API. No crate for the API.

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

Last updated November 26, 2026

To add e-signatures and clickwrap with Rust, call the REST API with `reqwest` and the secret key: there is no crate. One axum handler creates the session and keeps the pinned versions in a private cookie, another confirms the record, and 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.

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

```text copy="Copy prompt" open="cursor"
Add Esign Comply clickwrap to my Rust 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/rust.md (the steps and the tested code for Rust)
- https://esigncomply.com/setup.md (the order of API calls)
- https://esigncomply.com/auth.md (how to handle the keys)

Rust facts
- There is no Esign Comply crate for Rust. Do not install or invent one. The server calls the REST API at https://esigncomply.com/v1 with Authorization: Bearer and the secret key, using reqwest or the HTTP client the project already has.
- 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. Cargo does not read .env files. std::env::var returns Ok("") for a variable that is set and empty: treat it as missing and stop at startup. Never print the key.
- reqwest: enable the json feature and keep a TLS feature. With default-features = false and no TLS feature, http://localhost works and every https address fails at run time. Set a timeout on the Client (the default is none) and build one Client for the whole server.
- reqwest does not turn 4xx and 5xx into errors. Check the status, then read the error envelope: { "error": { "code": ... } }.
- The API's JSON is snake_case, as Rust fields are: derive Deserialize with no rename, and name only the fields you read. A missing field, or a null in a field that is not an Option, is an error. The browser reads clientToken and apiUrl: put rename_all = "camelCase" on that one struct, and send the documents as the API sent them.
- Do not build API addresses with Url::join: it drops /v1. Use path_segments_mut().extend(), which also percent-encodes a record ID that came from the browser.
- axum: the extractor that reads the body (Json) is the last argument of a handler. A cookie jar must be returned as part of the response, or no cookie is set. A path capture is written {slug}.
- Keep the signer ID and the pinned version IDs in server-owned state: a PrivateCookieJar from axum-extra with a key from the environment, or the store the project already has.
- A handler is dropped when the client disconnects. Run the confirmation in tokio::spawn, so the account is still created.
- Send the document HTML unescaped, as text/html. If the project renders with a template engine that escapes, mark the document as safe HTML.
- Bind 0.0.0.0, not 127.0.0.1, when the server runs in a container.
- 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. Handler for POST /api/ceremony: call POST /v1/sessions with an Idempotency-Key, save the signer ID and the pinned version IDs in server-owned state, and return only clientToken, apiUrl and documents.
4. Handler 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. Handler 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 server-owned state. Only then create the account.

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

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

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

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

## Before you start

- A test API key. [Create an account](https://esigncomply.com/signup) with your email, no card, then choose **Create test key** in the dashboard. The key is shown once and starts with `esc_test_`. An AI agent with an agent token creates it with `POST /v1/agent/api-keys`: see the [agent account API](https://esigncomply.com/docs/api/agent.md).
- Nothing else from Esign Comply. Test mode works on `localhost` with no card and no domain, and the Free plan includes it in full.
- Rust 1.89 or later, with Cargo: that is the highest minimum version a dependency of this page declares (`uuid` 1.29.3). This page was run on Rust 1.100.0.
- A C compiler, which the official Rust container image has. The default TLS backend of `reqwest` compiles `aws-lc-sys`. In the test it built in the slim image with `gcc` alone: no CMake, no OpenSSL headers.
- `curl` and `jq` for steps 2 and 3, and Node.js 20.19 or later for the conformance check in step 7.

## Step 1. Install

No package from Esign Comply. The server SDK exists for Node.js only, so a Rust server calls the REST API directly. This page uses axum on tokio for the routes, `reqwest` for the calls and serde for the JSON: the crates most Rust web services are built on today. The page loads the browser SDK from a script tag.

```bash
cargo new esigncomply-quickstart
cd esigncomply-quickstart
cargo add axum@0.8
cargo add tokio@1 --features rt-multi-thread,macros,net,time
cargo add reqwest@0.13 --features json
cargo add serde@1 --features derive
cargo add serde_json@1
cargo add axum-extra@0.12 --features cookie-private,cookie-key-expansion
cargo add uuid@1 --features v4
mkdir public
```

Those commands wrote this manifest in the test run, and a `Cargo.lock` that pins 219 packages:

```toml file="Cargo.toml"
[package]
name = "esigncomply-quickstart"
version = "0.1.0"
edition = "2024"

[dependencies]
axum = "0.8"
axum-extra = { version = "0.12", features = ["cookie-private", "cookie-key-expansion"] }
reqwest = { version = "0.13", features = ["json"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
tokio = { version = "1", features = ["rt-multi-thread", "macros", "net", "time"] }
uuid = { version = "1", features = ["v4"] }
```

Two features of `reqwest` decide whether this server can call the API at all, and each case was built in the test run.

`json` is not a default feature. Without it the build stopped with `error[E0599]: no method named json found for struct reqwest::Response`.

TLS is a feature too. The default features of `reqwest` 0.13.5 include `default-tls`, which is rustls today, and the first build took 50 seconds. With the `native-tls` feature the same image could not build: `openssl-sys` stopped with `Could not find directory of OpenSSL installation`. With `default-features = false` and no TLS feature, everything compiled and a call to `http://localhost` worked. A call to an `https` address failed at run time, and only the debug form of the error said why: `invalid URL, scheme is not http`. Such a build passes every local test and fails in production.

## Step 2. Set the key

Put the key in `.env` in the project folder. Cargo does not read this file: you load it into the shell that runs `cargo run`, and `main.rs` reads the variables with `std::env::var`.

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

`cargo new` wrote a `.gitignore` with `/target` in it. Add `.env` to it.

The server keeps what it pinned in an encrypted cookie, and the cookie needs a key of its own. Add one to `.env`, 32 bytes or more:

```bash
printf 'COOKIE_KEY=%s\n' "$(openssl rand -hex 64)" >> .env
```

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

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

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

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

## Step 3. Register a document version

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

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

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

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

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

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

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

Add the three lines to `.env`, 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](https://esigncomply.com/docs/conformance.md#cr-02) checks that it does. With your own documents, publish the text you already have and change the notice to match. See [Documents](https://esigncomply.com/docs/api/documents.md) and [Profiles](https://esigncomply.com/docs/api/profiles.md).

## Step 4. Create a session on the server

`src/main.rs` is the whole server: the signup page, the two document pages, the handler that creates the session, and the handler that confirms the record. The `call` method is the entire client: one HTTPS call with the secret key that returns the resource, or the reason there is none, sent again only when the API answers `429`. This replaces the `main.rs` that `cargo new` wrote:

```rust file="src/main.rs"
// src/main.rs
use std::{env, sync::Arc, time::Duration};

use axum::{
    Json, Router,
    extract::{FromRef, Path, Query, State},
    http::{HeaderMap, StatusCode, header},
    response::{Html, IntoResponse, Response},
    routing::{get, post},
};
use axum_extra::extract::cookie::{Cookie, Key, PrivateCookieJar, SameSite};
use reqwest::{Method, Url};
use serde::{Deserialize, Serialize, de::DeserializeOwned};
use serde_json::{Value, json};
use uuid::Uuid;

// The signup page is compiled into the binary.
const SIGNUP_PAGE: &str = include_str!("../public/signup.html");
const SEALED: [&str; 3] = ["recorded", "timestamped", "anchored"];
const PINNED_COOKIE: &str = "esc_pinned";

// The signer. In your app this is the signed-in user, or the account you are about to create.
// The field names are the API's own: serde writes a Rust field as it is spelled.
#[derive(Serialize)]
struct Signer {
    external_id: &'static str,
    email: &'static str,
    name: &'static str,
    class: &'static str,
    country: &'static str,
    region: &'static str,
}

const SIGNER: Signer = Signer {
    external_id: "user_7c1d",
    email: "dana@example.org",
    name: "Dana Whitfield",
    class: "consumer",
    country: "US",
    region: "US-CA",
};

// What the API answers. Fields this code does not name are ignored; a named field that is missing is an error.
#[derive(Deserialize)]
struct Session {
    client_token: String,
    api_url: String,
    documents: Vec<Document>,
}

#[derive(Deserialize, Serialize)]
struct Document {
    document_id: String,
    version_id: String,
}

#[derive(Deserialize)]
struct Record {
    id: String,
    status: String,
    livemode: bool,
    signer: RecordSigner,
    documents: Vec<Document>,
}

#[derive(Deserialize)]
struct RecordSigner {
    external_id: String,
}

#[derive(Deserialize)]
struct Content {
    version_id: String,
    html: String,
}

#[derive(Deserialize)]
struct ErrorEnvelope {
    error: ApiError,
}

#[derive(Deserialize)]
struct ApiError {
    code: String,
}

// What the browser sends and gets is camelCase. rename_all changes the fields of this struct only:
// the documents inside keep version_id, as the API sent them.
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct Ceremony {
    client_token: String,
    api_url: String,
    documents: Vec<Document>,
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct Claim {
    record_id: String,
}

#[derive(Deserialize)]
struct LegalQuery {
    v: Option<String>,
}

// Server-owned state: the signer ID and the version IDs this server pinned, in an encrypted cookie.
#[derive(Deserialize, Serialize)]
struct Pinned {
    signer: String,
    versions: Vec<String>,
}

/// Why a call did not return the resource. The Node.js SDK resolves to `{ data, error }`; here that is a `Result`.
#[derive(Debug)]
enum EscError {
    /// The API answered with an error envelope: the status and `error.code`.
    Refused(StatusCode, String),
    /// No answer, or an answer that is not the JSON this code expects.
    Failed(reqwest::Error),
}

impl From<reqwest::Error> for EscError {
    fn from(error: reqwest::Error) -> Self {
        EscError::Failed(error)
    }
}

/// There is no Rust crate: these are plain HTTPS calls with the secret key.
struct EsignComply {
    http: reqwest::Client,
    api: Url,
    key: String,
}

impl EsignComply {
    /// One call to the Esign Comply API. `Ok` holds the resource, `Err` says why there is none.
    async fn call<T: DeserializeOwned>(
        &self,
        method: Method,
        segments: &[&str],
        body: Option<Value>,
        idempotency_key: Option<String>,
    ) -> Result<T, EscError> {
        // Each segment is percent-encoded, so an ID from the browser cannot change the path.
        let mut url = self.api.clone();
        url.path_segments_mut()
            .expect("an http address")
            .pop_if_empty()
            .extend(segments);
        let mut attempt = 1;
        loop {
            let mut request = self
                .http
                .request(method.clone(), url.clone())
                .bearer_auth(&self.key);
            if let Some(body) = &body {
                request = request.json(body);
            }
            if let Some(key) = &idempotency_key {
                request = request.header("Idempotency-Key", key);
            }
            let response = request.send().await?;
            let status = response.status();
            if status == StatusCode::TOO_MANY_REQUESTS && attempt < 3 {
                // Rate limited: wait for the seconds in Retry-After, 1 at least and 5 at most, and send it again, twice at most.
                let seconds = response
                    .headers()
                    .get(header::RETRY_AFTER)
                    .and_then(|value| value.to_str().ok())
                    .and_then(|value| value.parse::<u64>().ok())
                    .unwrap_or(1);
                tokio::time::sleep(Duration::from_secs(seconds.clamp(1, 5))).await;
                attempt += 1;
                continue;
            }
            if !status.is_success() {
                // reqwest does not turn 4xx and 5xx into errors. Read the envelope: { "error": { "code": ... } }.
                let envelope: ErrorEnvelope = response.json().await?;
                return Err(EscError::Refused(status, envelope.error.code));
            }
            return Ok(response.json::<T>().await?);
        }
    }
}

#[derive(Clone)]
struct App {
    esc: Arc<EsignComply>,
    cookie_key: Key,
    profile: String,
    terms: String,
    privacy: String,
    live: bool,
}

// PrivateCookieJar takes its key from the router's state through this.
impl FromRef<App> for Key {
    fn from_ref(app: &App) -> Self {
        app.cookie_key.clone()
    }
}

/// A variable that must be set. An empty value counts as missing: env::var returns Ok("") for it.
fn required(name: &str) -> String {
    match env::var(name) {
        Ok(value) if !value.is_empty() => value,
        _ => panic!("{name} is not set"),
    }
}

fn version_ids(documents: &[Document]) -> Vec<String> {
    let mut ids: Vec<String> = documents
        .iter()
        .map(|document| document.version_id.clone())
        .collect();
    ids.sort();
    ids
}

async fn signup() -> Html<&'static str> {
    Html(SIGNUP_PAGE)
}

// The document pages: each one renders a registered version, unmodified.
async fn legal(
    State(app): State<App>,
    Path(slug): Path<String>,
    Query(query): Query<LegalQuery>,
) -> Response {
    let document_id = match slug.as_str() {
        "terms" => &app.terms,
        "privacy" => &app.privacy,
        _ => return StatusCode::NOT_FOUND.into_response(),
    };
    let version = query.v.unwrap_or_else(|| "current".to_owned());
    match app
        .esc
        .call::<Content>(
            Method::GET,
            &["documents", document_id, "versions", &version, "content"],
            None,
            None,
        )
        .await
    {
        // format! escapes nothing, so the document's HTML goes out as the API sent it.
        Ok(page) => Html(format!(
            r#"<!doctype html><meta charset="utf-8"><article data-esc-document="{}">{}</article>"#,
            page.version_id, page.html
        ))
        .into_response(),
        Err(_) => StatusCode::NOT_FOUND.into_response(),
    }
}

// Step 4: create the session with the secret key. The browser gets the client token only.
async fn ceremony(State(app): State<App>, jar: PrivateCookieJar, headers: HeaderMap) -> Response {
    let header_text = |name| headers.get(name).and_then(|value| value.to_str().ok());
    let origin = match header_text(header::ORIGIN) {
        Some(origin) => origin.to_owned(),
        None => format!(
            "http://{}",
            header_text(header::HOST).unwrap_or("localhost")
        ),
    };
    let body = json!({
        "profile": app.profile,
        "signer": SIGNER,
        "documents": [
            { "document": app.terms, "version": "current" },
            { "document": app.privacy, "version": "current" },
        ],
        "context": { "url": format!("{origin}/signup"), "locale": "en-US", "purpose": "account_signup" },
    });
    let idempotency_key = format!("signup-{}-{}", SIGNER.external_id, Uuid::new_v4());
    let created: Session = match app
        .esc
        .call(
            Method::POST,
            &["sessions"],
            Some(body),
            Some(idempotency_key),
        )
        .await
    {
        Ok(session) => session,
        Err(EscError::Refused(_, code)) => {
            return (StatusCode::BAD_GATEWAY, Json(json!({ "error": code }))).into_response();
        }
        Err(EscError::Failed(error)) => {
            eprintln!("session not created: {error:?}");
            return (
                StatusCode::BAD_GATEWAY,
                Json(json!({ "error": "api_unreachable" })),
            )
                .into_response();
        }
    };
    let pinned = Pinned {
        signer: SIGNER.external_id.to_owned(),
        versions: version_ids(&created.documents),
    };
    let cookie = Cookie::build((
        PINNED_COOKIE,
        serde_json::to_string(&pinned).expect("plain strings"),
    ))
    .path("/")
    .http_only(true)
    .same_site(SameSite::Lax)
    .secure(app.live);
    // The jar must be part of the response, or no Set-Cookie header is sent.
    (
        jar.add(cookie),
        Json(Ceremony {
            client_token: created.client_token,
            api_url: created.api_url,
            documents: created.documents,
        }),
    )
        .into_response()
}

// Step 6: confirm the record with the secret key before the account exists.
// The Json extractor reads the body, so it is the last argument.
async fn confirm(
    State(app): State<App>,
    jar: PrivateCookieJar,
    Json(claim): Json<Claim>,
) -> Response {
    // A cookie that this server's key did not encrypt is not in the jar at all.
    let pinned: Option<Pinned> = jar
        .get(PINNED_COOKIE)
        .and_then(|cookie| serde_json::from_str(cookie.value()).ok());
    // When the browser goes away, this handler is dropped at its next await. A spawned task runs to its end.
    let task = tokio::spawn(confirm_record(app, pinned, claim.record_id));
    match task.await {
        Ok(Some(record_id)) => {
            Json(json!({ "confirmed": true, "recordId": record_id })).into_response()
        }
        _ => (StatusCode::CONFLICT, Json(json!({ "confirmed": false }))).into_response(),
    }
}

/// Reads the record and makes the four checks. Returns the record ID when the account may be created.
async fn confirm_record(app: App, pinned: Option<Pinned>, record_id: String) -> Option<String> {
    let Some(pinned) = pinned else {
        println!("refused: no pinned versions");
        return None;
    };
    let record = match app
        .esc
        .call::<Record>(Method::GET, &["records", &record_id], None, None)
        .await
    {
        Ok(record) => record,
        Err(EscError::Refused(status, code)) => {
            println!("refused: the API answered {status} {code}");
            return None;
        }
        Err(EscError::Failed(error)) => {
            println!("refused: {error:?}");
            return None;
        }
    };
    let confirmed = SEALED.contains(&record.status.as_str())
        && record.livemode == app.live
        && record.signer.external_id == pinned.signer
        && pinned.signer == SIGNER.external_id
        && !pinned.versions.is_empty()
        && version_ids(&record.documents) == pinned.versions;
    if !confirmed {
        println!("refused {}", record.id);
        return None;
    }
    println!("confirmed {} ({})", record.id, record.status);
    // Only now create the account, and store the record ID and the receipt with it.
    Some(record.id)
}

#[tokio::main]
async fn main() {
    let api =
        env::var("ESIGNCOMPLY_API_URL").unwrap_or_else(|_| "https://esigncomply.com/v1".to_owned());
    let app = App {
        esc: Arc::new(EsignComply {
            // reqwest's default is no timeout. One client for the whole server: it keeps the connection pool.
            http: reqwest::Client::builder()
                .timeout(Duration::from_secs(10))
                .build()
                .expect("a TLS backend"),
            // "localhost:3000/v1" parses too, with localhost as the scheme: require an address that has a path.
            api: Url::parse(&api)
                .ok()
                .filter(|url| !url.cannot_be_a_base())
                .expect("ESIGNCOMPLY_API_URL is an http address"),
            key: required("ESIGNCOMPLY_API_KEY"),
        }),
        // 32 bytes or more, the same for every instance and every restart.
        cookie_key: Key::derive_from(required("COOKIE_KEY").as_bytes()),
        profile: required("ESIGNCOMPLY_PROFILE_ID"),
        terms: required("ESIGNCOMPLY_TERMS_ID"),
        privacy: required("ESIGNCOMPLY_PRIVACY_ID"),
        live: env::var("ESIGNCOMPLY_LIVE").is_ok_and(|value| value == "true"), // set it in production only
    };

    let router = Router::new()
        .route("/signup", get(signup))
        .route("/legal/{slug}", get(legal))
        .route("/api/ceremony", post(ceremony))
        .route("/api/signup/confirm", post(confirm))
        .with_state(app);

    // 0.0.0.0 and not 127.0.0.1: in a container, loopback is the container's own.
    let port = env::var("PORT").unwrap_or_else(|_| "3000".to_owned());
    let listener = tokio::net::TcpListener::bind(format!("0.0.0.0:{port}"))
        .await
        .expect("the port is free");
    println!("http://localhost:{port}/signup");
    axum::serve(listener, router)
        .await
        .expect("the server runs");
}
```

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.

Six things here are specific to Rust, and each one was seen in the test run.

The structs carry no rename. The API's fields are `client_token`, `api_url` and `version_id`, which is how Rust fields are spelled, so `#[derive(Deserialize)]` reads them as they are. serde is strict about the rest. The error envelope read into `Record` gave `missing field id`, where the Go quickstart got an empty record and no error. A document of a real record carried `"render_match": null`, and a `bool` field of that name gave `invalid type: null, expected a boolean`: a field that can be `null` is an `Option`. So the structs name only the fields this code reads. `rename_all = "camelCase"` is on the two structs that face the browser, and it does not reach into the documents: the page got `clientToken`, `apiUrl` and `version_id`.

A refused call is the `Err` side of a `Result`. `reqwest` does not turn `4xx` and `5xx` into errors, so `call` checks the status and reads the envelope. A made-up record ID came back as `Refused` with `404 Not Found` and `not_found`. A wrong key came back with `invalid_api_key`, and the session route answered `502`.

The address is built from path segments. `Url::join("sessions")` on `https://esigncomply.com/v1` gave `https://esigncomply.com/sessions`: it replaces the last segment. `path_segments_mut()` with `pop_if_empty()` and `extend()` kept `/v1`, with or without a slash at the end of the base. It also percent-encodes. A record ID of `../usage?x=1#y` became `..%2Fusage%3Fx=1%23y`, where `format!` built an address that parsed as `/v1/usage?x=1`.

The client has a timeout and is built once. The documentation of `reqwest` says of `timeout`: default is no timeout. With the API address pointed at a server that accepted the connection and never answered, the session route answered `502` after 10.0 seconds, with `TimedOut` in the log. An error prints its cause only in the debug form: `{error}` gave `error sending request for url (...)`, and `{error:?}` added `ConnectionRefused`.

The pinned versions are in a private cookie, `PrivateCookieJar` from `axum-extra`, the crate of extras kept in the axum repository. The browser got a cookie named `esc_pinned` with 162 characters of ciphertext, marked `HttpOnly` and `SameSite=Lax`. A cookie with one character changed, and a cookie from a server with another `COOKIE_KEY`, were both answered `409`: the jar does not hold a cookie its key did not encrypt. The same cookie confirmed a record before and after a restart, because the state is in the browser and the key is in the environment. The jar has to be part of the response. With `jar.add(cookie);` on a line of its own the compiler warned `unused PrivateCookieJar that must be used`, and the route answered `200` with no `Set-Cookie` header.

The body extractor is the last argument. With `Json` before the jar in `confirm`, the build stopped with `error[E0277]: the trait bound ... Handler<_, _> is not satisfied`, pointing at the `.route` line. With `#[axum::debug_handler]` on the function, which needs the `macros` feature of axum, the message was: `Json<_>` consumes the request body and thus must be the last argument to the handler function.

When the API answers `429`, `call` waits for the seconds in `Retry-After`, 1 at least and 5 at most, and sends the request again, up to twice. The wait is `tokio::time::sleep`, which is why tokio carries the `time` feature in the manifest. It holds no thread: in the test, page requests sent while two confirmations waited were answered in under 0.01 seconds.

`context.url` is built from the `Origin` header the browser sends with the `POST`, and from the `Host` header when there is none. Both come 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 no `Origin` and `Host: evil.example`.

Start the server from the shell that loaded `.env`:

```bash
cargo run
```

The first run compiles every dependency, 50 seconds in the test. Then it prints:

```text
     Running `target/debug/esigncomply-quickstart`
http://localhost:3000/signup
```

Without the key the server does not start. With `ESIGNCOMPLY_API_KEY` missing, and with the variable set to an empty value, it stopped with exit code 101:

```text
thread 'main' (1) panicked at src/main.rs:209:14:
ESIGNCOMPLY_API_KEY is not set
```

## 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 `public/signup.html`:

```html file="public/signup.html"
<!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>
```

`include_str!` in `main.rs` compiles this file into the binary. After an edit of the page alone, `cargo run` compiled the crate again before it started.

Open [http://localhost:3000/signup](http://localhost:3000/signup). The button stays disabled until the box is ticked. Tick it, click **Create account**, and the page shows:

```text
Account created. Record rec_6EcZJQqp2R0qsFytfAFq
```

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. In a test without `disabled` and with the session request held back, a box ticked in that time stayed ticked, and the SDK reported a finding for [CR-01](https://esigncomply.com/docs/conformance.md#cr-01) at Block level: the control had already been used when the SDK started watching it. With `disabled`, the same early click 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. `format!` escapes nothing, so the `legal` handler sends the document's HTML as the API sent it, and the SDK recorded both documents as presented.

## Step 6. Confirm the record on the server

The result of `complete()` was delivered to the browser, so your server does not trust it. `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 cookie this server encrypted; and the document versions are exactly the ones it pinned there. This step is never optional.

The server prints one line for each confirmation:

```text
confirmed rec_6EcZJQqp2R0qsFytfAFq (recorded)
```

The confirmation runs in `tokio::spawn`, and the reason is specific to Rust. hyper drops a handler when its client disconnects: the function stops at its next `.await` and never runs again. In a first version `confirm` read the record itself, and in a run of the conformance check that server logged one `confirmed` line for three sealed records. A request that gave up after 10 milliseconds left no line at all. A spawned task runs to its end: with the code on this page the same early disconnect still logged `confirmed`, and the check logged three lines for three records.

A record ID that was made up is refused with status `409`. So is a real record ID sent without the cookie:

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

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

A request the `Json` extractor cannot read never reaches the handler. axum answered `415` to a body with no JSON content type, `400` to JSON cut short, `422` to JSON with no `recordId`, and `413` to a body of 3 MB: the extractor stops at 2 MB by default. A `GET` to a `POST` route was answered `405`.

See [Server confirmation](https://esigncomply.com/docs/guides/server-confirmation.md) for the webhook that backs this handler 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:

```bash
mkdir -p esc-check && cd esc-check
npm init -y && npm install esigncomply playwright
npx playwright install chromium
npx esigncomply check --url http://localhost:3000/signup --callback http://localhost:3000/api/signup/confirm
```

The report for this page's code, shortened:

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

Ceremonies
  390x844    record rec_jiotVnQwvBeyE3aBKWrF  session ses_rZ7snXFp850Sw4Ri8hbN, 5 events
  768x1024   record rec_pA662ESDKGLEaANm6QTA  session ses_wwGLBsmjHwqiKEYf1sAu, 5 events
  1440x900   record rec_JeAXRiWfJPNBxaZstk3v  session ses_16Kb5CV3oAPu3qaU0Gd9, 5 events

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

The server 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](https://esigncomply.com/docs/conformance.md), and every flag of the command is on the [CLI page](https://esigncomply.com/docs/sdk/cli.md).

## Step 8. Go live

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

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

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

Then switch the server over:

- Set the live key as `ESIGNCOMPLY_API_KEY` and set `ESIGNCOMPLY_LIVE=true` in production only. From then on the confirm handler refuses every test record there, and the cookie is marked `Secure`.
- Build with `cargo build --release --locked` and run `target/release/esigncomply-quickstart`. In the test the release build took 90 seconds, and the binary was 10 MB where the debug one was 85 MB. The page is inside it: started from another folder, it served `/signup` and recorded the signature shown in step 5.
- Run the binary on the distribution it was built on. It links the C library of the build image: built on Debian 13 and started in a Debian 12 image, it stopped with `version GLIBC_2.38 not found`.
- Give the runtime image its CA certificates. With an empty `/etc/ssl` the server did not start: `No CA certificates were loaded from the system`, from the TLS backend of `reqwest`, though the API address in that test was plain HTTP. Against a local TLS server with a certificate from a private CA, the call failed with `InvalidCertificate(UnknownIssuer)` until `SSL_CERT_FILE` named that CA. The public API was not called over TLS in this run.
- The server binds `0.0.0.0`. A build that bound `127.0.0.1` behind a published container port was answered `Connection reset by peer` from outside the container.
- The server does not handle `SIGTERM`. As the first process of a container, `docker stop` waited 10 seconds and killed it, with exit code 137. In a test server with `with_graceful_shutdown` of `axum::serve` waiting on `SIGTERM`, the stop took half a second, the exit code was 0, and a request that was open finished first.
- Keep one `COOKIE_KEY` for every instance and every restart, and store the record ID and the receipt beside the user.
- Behind a proxy that terminates TLS, the handler takes the page's address from the `Origin` header the browser sends, so `context.url` keeps the `https` scheme.

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

- **The server stops at start with `ESIGNCOMPLY_API_KEY is not set`.** The variables are not in the environment of the shell that ran `cargo run`: Cargo does not read `.env`. Run `set -a; . ./.env; set +a` first. A key that is set and wrong lets the server start, and the session route then answers `502` with the code the API gave. See [`invalid_api_key`](https://esigncomply.com/docs/api/errors.md#invalid_api_key).
- **`domain_mismatch` from `/api/ceremony`.** `context.url` is built from the `Origin` or `Host` header, and that host is not on the test allowlist. Test keys work on `localhost` and `127.0.0.1` at any port. Add other hosts under Domains in the dashboard. See [`domain_mismatch`](https://esigncomply.com/docs/api/errors.md#domain_mismatch).
- **`429` when the confirm handler reads the record.** `call` waits for the seconds in `Retry-After`, 1 at least and 5 at most, and sends the request again, up to twice. Nothing else is retried. In the test, four confirmations sent at once with the cookie of the session that signed all answered `200`, two of them a second later than the others. The API's log showed why: two reads got `429` and passed on the next attempt. Four session requests sent at once went the same way. See [`rate_limit_exceeded`](https://esigncomply.com/docs/api/errors.md#rate_limit_exceeded). When the handler answers `409` for a real record and the log says `refused: no pinned versions`, the cookie is missing or was encrypted with another `COOKIE_KEY`.

## Questions about the Rust quickstart

### Is there a crate for Esign Comply?

No. The server SDK exists for Node.js only. A Rust server calls the REST API directly, and this quickstart does it with `reqwest` and serde. Every crate in `Cargo.toml` is a general one: axum, tokio, `reqwest`, serde, `axum-extra` and `uuid`.

### Does cargo run read the .env file?

No. In the test, with `.env` in the project folder and the key missing from the environment, `cargo run` built the server and it stopped at once with the message that the key is not set, exit code 101. Load the file into the shell first.

### Does the release binary need the public folder?

No. The page is compiled into the binary with `include_str!`. In the test the release binary was started from another folder, served the signup page and recorded a signature. It does need the environment variables, the C library of the image it was built on, and CA certificates.

### Why does the conformance check need Node.js?

The checker is the `esigncomply` command line tool, which is a Node.js package. It drives a headless browser against your page, whatever language serves it. Install it in a folder of its own, as step 7 shows, and your Rust project stays free of Node.js files.

### Does the Rust 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 Rust](https://esigncomply.com/rust): what the integration gives you on this stack, with the things to watch for.
- [Server confirmation](https://esigncomply.com/docs/guides/server-confirmation.md): the checks in step 6 and the `record.completed` webhook.
- [Sessions API](https://esigncomply.com/docs/api/sessions.md) and [Records API](https://esigncomply.com/docs/api/records.md): every field of the two calls this server makes.
- [Add e-signatures and clickwrap with Node.js](https://esigncomply.com/docs/quickstart/nodejs.md): the same flow with the server SDK.
- [All quickstarts](https://esigncomply.com/docs/quickstart.md#quickstarts-by-stack-and-platform).
