Add e-signatures and clickwrap to Rust
To add e-signatures and clickwrap to Rust, call the REST API with reqwest: there is no crate, because the server SDK exists for Node.js only. One axum handler creates the session with the secret key, a private cookie holds the pinned versions, and another handler confirms the record in a spawned task. 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.
No Esign Comply crate exists: reqwest and serde make the calls
Rust quickstartFree plan: 10 live signatures a month and a full test mode. No card required.
Last updated
// 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() }
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?);
}
}
}// 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) }
How do you integrate Esign Comply with Rust?
In Rust the integration is one src/main.rs on axum and tokio. reqwest makes the calls, serde reads the API's snake_case fields into structs with no rename, and a refused call is the Err side of a Result. A PrivateCookieJar from axum-extra keeps the pinned versions, and include_str! compiles the page into the binary.
The Rust project describes Rust as a language empowering everyone to build reliable and efficient software.
Source: rust-lang.org, read on .- Session handlersrc/main.rs
- The API callsrc/main.rs
- Confirm handlersrc/main.rs
- The four checkssrc/main.rs
Run on 2026-11-26 with Rust 1.100.0 (edition 2024), axum 0.8.9 on tokio 1.54.1, reqwest 0.13.5 with its default rustls backend, serde 1.0.229, serde_json 1.0.154, axum-extra 0.12.6 and uuid 1.29.3, under cargo run and as a release binary (in the official Rust container image, Debian 13), with the browser SDK script build and the conformance check from esigncomply 1.0.4 (run with --timeout 60), against the API in test mode on localhost over plain HTTP.
What prompt adds Esign Comply clickwrap to a Rust 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 Rust, 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. Added to your project's instruction file, it makes every later session build signing and acceptance flows the same way. The prompt generator writes the long version, with your own document and profile IDs.
Pages for each AI toolAdd 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.mdWhat goes wrong when you add e-signatures in Rust?
These are specific to Rust. Each one was seen while the quickstart's code was run, or is in Rust's own documentation.
- 01
A handler is dropped when the browser disconnects
On axum 0.8.9 a handler stops at its next
.awaitwhen its client goes away. In the test a first version of the confirm handler logged one confirmation for the three sealed records of a conformance check, and a request that gave up after 10 milliseconds left no line. The quickstart runs the confirmation intokio::spawn: the same early disconnect was confirmed, and the check logged three of three. - 02
Without a TLS feature, reqwest works on localhost and fails on https
The
Source: docs.rs, reqwest 0.13.5, module tls, read on .reqwestdocumentation saysdefault-tlsis enabled by default and that you must setdefault-features = falseto turn it off. In the test a build with that setting and no TLS feature compiled and calledhttp:/. An/localhost httpsaddress failed at run time, and only the debug form of the error said why:invalid URL, scheme is not http. The quickstart keeps the default features and addsjson. - 03
serde refuses a missing field and a null
The API's snake_case fields read into Rust structs with no rename, and serde is strict about the rest. In the test the error envelope read into the record struct gave
missing field id, and aboolfield met"render_match": nullin a real record and gaveinvalid type: null, expected a boolean. The quickstart checks the status first and names only the fields it reads.
Where are the Rust quickstart and the API reference?
Start with the quickstart: it carries every file this page excerpts, in the order you write them.
- QuickstartRust quickstartStep by step, from install to your first sealed test record, with every file and the output of each step.Open
- ReferenceAPI referenceEvery endpoint, field and error code. Sessions, records and documents are the three this page uses.Open
- GuideServer confirmationThe one place access is granted: what to compare, and the webhook that backs the check up.Open
What does Esign Comply record for a signature in Rust?
The same record on every stack and platform. Your Rust 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.
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, andGET /v1returns it again./records /{id} /receipt 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.
Questions about e-signatures in Rust
Is there an Esign Comply SDK for Rust?
No. The server SDK exists for Node.js only, and there is no crate. A Rust server calls the REST API directly with the secret key, and the quickstart does it with reqwest and serde on axum. The browser side is the same SDK as on every stack.
Where do I create the session in Rust?
In an axum handler, post(ceremony) on /api, with a POST to /v1 that carries the secret key and an Idempotency-Key. The handler puts the pinned versions in a private cookie and returns only the client token, the API URL and the documents.
Why must the Json extractor be the last argument?
Because it reads the request body, which can be read once. The axum documentation says extractors run from left to right and one that consumes the body must be last. In the test, Json before the cookie jar stopped the build with E0277 at the .route line. A body over 2 MB was answered 413.
Does the release binary run in any container image?
No. In the test a binary built on Debian 13 stopped on Debian 12 with GLIBC_2.38 not found, and with an empty /etc it stopped at start with No CA certificates were loaded from the system. The page is compiled in, so it needs no files of its own. It binds 0.0.0.0: bound to 127.0.0.1 behind a published port, connections were reset.
Why not build the API address with Url::join?
Because it drops /v1. In the test Url::join("sessions") on https:/ gave https:/. The quickstart extends the path segments, which keeps /v1 and percent-encodes each segment: a record ID of ../usage?x=1#y became ..%2Fusage%3Fx=1%23y, one segment.
Call the API from the Rust server you already run. Leave the record to us.
Free plan: 10 live signatures a month and a full test mode. No card required.
Rust is a trademark of its owner. Esign Comply is not affiliated with it. What this page says about Rust is from Rust's documentation or from a test run, as marked, on . /rust.md is this page as Markdown.