# Add e-signatures and clickwrap to Kotlin

> Add e-signatures and clickwrap to Kotlin with Ktor: POST /v1/sessions and GET /v1/records with the Ktor client, kotlinx.serialization and a signed cookie.

Source: https://esigncomply.com/kotlin

Stack · Kotlin

To add e-signatures and clickwrap to Kotlin, call the REST API from a Ktor server with its client: there is no package, because the server SDK exists for Node.js only. One file creates the session with the secret key, keeps the pinned versions in a signed cookie, and confirms the record. Esign Comply seals each acceptance as an independent record.

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

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

No artifact for the API: the Ktor client makes the calls. The build lists Ktor's own artifacts and Logback

[Kotlin quickstart](https://esigncomply.com/docs/quickstart/kotlin)

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

Last updated November 26, 2026

Run in Kotlin before publishing

**The API call**

src/main/kotlin/Application.kt (excerpt)

```kotlin
// There is no Kotlin package for the API: these are plain HTTPS calls with the secret key, made with the Ktor client.
class EsignComply(private val api: String, private val apiKey: String) {
    // CIO is Ktor's own coroutine engine. It speaks HTTP/1.1 only, so it never asks a server to upgrade to HTTP/2.
    private val http = HttpClient(CIO) {
        // Installed with no settings, HttpRequestRetry sends a request again up to three times after a 5xx answer or an exception.
        // Here it retries a 429 only, twice at most, and waits for Retry-After (1 to 5 seconds). Nothing else is retried.
        install(HttpRequestRetry) {
            retryIf(maxRetries = 2) { _, response -> response.status == HttpStatusCode.TooManyRequests }
            retryOnExceptionIf { _, _ -> false }
            delayMillis(respectRetryAfterHeader = false) {
                (response?.headers?.get(HttpHeaders.RetryAfter)?.toLongOrNull() ?: 1L).coerceIn(1L, 5L) * 1000
            }
        }
        install(HttpTimeout) {
            connectTimeoutMillis = 5_000
            requestTimeoutMillis = 10_000
        }
        install(ClientContentNegotiation) { json(JSON) }
    }

    /** One call to the Esign Comply API. The client does not throw on 4xx and 5xx: read status, and the error envelope is the body. */
    suspend fun request(method: HttpMethod, path: String, body: JsonObject? = null, idempotencyKey: String? = null): HttpResponse =
        http.request(api + path) {
            this.method = method
            bearerAuth(apiKey)
            if (idempotencyKey != null) header("Idempotency-Key", idempotencyKey)
            if (body != null) {
                contentType(ContentType.Application.Json)
                setBody(body)
            }
        }
}
```

**Create the session**

src/main/kotlin/Application.kt (excerpt)

```kotlin
// Step 4: create the session with the secret key. The browser gets the client token only.
post("/api/ceremony") {
    // The page that runs the ceremony: the origin the browser reports, or the scheme and host of the request.
    val origin = call.request.headers[HttpHeaders.Origin]
        ?: "${call.request.origin.scheme}://${call.request.headers[HttpHeaders.Host]}"
    val created = esc.request(
        HttpMethod.Post, "/sessions",
        idempotencyKey = "signup-$SIGNER_ID-${UUID.randomUUID()}",
        body = buildJsonObject {
            put("profile", profile)
            put("signer", SIGNER)
            putJsonArray("documents") {
                addJsonObject { put("document", documents.getValue("terms")); put("version", "current") }
                addJsonObject { put("document", documents.getValue("privacy")); put("version", "current") }
            }
            putJsonObject("context") {
                put("url", "$origin/signup")
                put("locale", "en-US")
                put("purpose", "account_signup")
            }
        },
    )
    val session = created.body<Session>()
    if (created.status != HttpStatusCode.Created || session.clientToken == null || session.apiUrl == null) {
        return@post call.respond(HttpStatusCode.BadGateway, mapOf("error" to (session.error?.code ?: "unknown")))
    }

    call.sessions.set(Pinned(SIGNER_ID, session.documents.map { it.versionId }.sorted()))
    call.respond(Ceremony(session.clientToken, session.apiUrl, session.documents))
}
```

**Confirm**

src/main/kotlin/Application.kt (excerpt)

```kotlin
// Step 6: confirm the record with the secret key before the account exists.
post("/api/signup/confirm") {
    // An empty or malformed body is refused below like a made-up record ID.
    val recordId = try { JSON.decodeFromString<Confirm>(call.receiveText()).recordId } catch (malformed: SerializationException) { "missing" }
    val expected = call.sessions.get<Pinned>()
    val answer = esc.request(HttpMethod.Get, "/records/${recordId.encodeURLPathPart()}")
    val record = answer.body<SignedRecord>()

    val confirmed = answer.status == HttpStatusCode.OK &&
        record.status in SEALED &&
        record.livemode == live &&
        expected != null && record.signer?.externalId == expected.signerId &&
        record.documents.map { it.versionId }.sorted() == expected.versionIds

    log.info(if (confirmed) "confirmed ${record.id} (${record.status})" else "refused")
    if (!confirmed) return@post call.respond(HttpStatusCode.Conflict, mapOf("confirmed" to false))

    // Only now create the account, and store record.id and the receipt with it.
    call.respond(buildJsonObject { put("confirmed", true); put("recordId", record.id) })
}
```

**The JSON**

src/main/kotlin/Application.kt (excerpt)

```json
// What this app reads from the API. The API's JSON is snake_case, so those fields carry @SerialName.
// Every field has a default: one the API did not send is null or empty, never false, and never stops the decoding.
@Serializable data class Doc(@SerialName("version_id") val versionId: String = "")
@Serializable data class ApiError(val code: String = "unknown")
@Serializable data class Session(@SerialName("client_token") val clientToken: String? = null, @SerialName("api_url") val apiUrl: String? = null, val documents: List<Doc> = emptyList(), val error: ApiError? = null)
@Serializable data class Content(@SerialName("version_id") val versionId: String = "", val html: String = "")
@Serializable data class Signer(@SerialName("external_id") val externalId: String? = null)
@Serializable data class SignedRecord(val id: String? = null, val status: String? = null, val livemode: Boolean? = null, val signer: Signer? = null, val documents: List<Doc> = emptyList())
```

Integrate with Kotlin

## How do you integrate Esign Comply with Kotlin?

In Kotlin the integration is one `Application.kt` on Ktor. The client is Ktor's own with the CIO engine, kotlinx.serialization reads the API's snake_case JSON into data classes, and the `Sessions` plugin signs the cookie that holds the pinned versions. The visitor can read that cookie and cannot change it. `application.yaml` takes the key from the environment, and a missing key stops the server at start.

Kotlin's documentation says: Ktor is a JetBrains framework for creating web applications in Kotlin.

Source: [Kotlin docs, Kotlin for server side](https://kotlinlang.org/docs/server-overview.html), read on November 26, 2026.

[Kotlin quickstart](https://esigncomply.com/docs/quickstart/kotlin) · [All stacks](https://esigncomply.com/stacks)

Where each part lives in Kotlin

- **The API call** · `src/main/kotlin/Application.kt`
- **Create the session** · `src/main/kotlin/Application.kt`
- **Confirm** · `src/main/kotlin/Application.kt`
- **The JSON** · `src/main/kotlin/Application.kt`

Run on 2026-11-26 with Kotlin 2.4.21 and Ktor 3.6.2 (the Netty server engine with Netty 4.2.20, the CIO client engine, the Sessions, StatusPages and ContentNegotiation plugins, kotlinx.serialization 1.11.0, kotlinx.coroutines 1.11.0 and Logback 1.5.38), built with Gradle 9.9.2 on Java 25.0.5.1 (Eclipse Temurin, in the official Maven container image, used for its JDK only), from the fat jar with java -jar and under gradle run, 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 over https were not run.

Copy-paste prompt

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

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

Kotlin facts
- There is no Esign Comply package for Kotlin or the JVM. Do not install or invent one. The server calls the REST API at https://esigncomply.com/v1 with the Ktor client, 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. Ktor does not read .env files. Take it from the environment in application.yaml ($ESIGNCOMPLY_API_KEY, no default) so that a missing key stops the server at start. Never print the key.
- Ktor client: use the engine the project already has. The CIO engine speaks HTTP/1.1 only. The Java engine asks a plain-http server to upgrade to HTTP/2 unless protocolVersion is HTTP_1_1. Install HttpTimeout. The client does not throw on 4xx and 5xx unless expectSuccess is set: read status and the error envelope.
- HttpRequestRetry with no settings retries 5xx answers and exceptions three times. Configure it to retry a 429 only, twice, with retryOnExceptionIf returning false, and compute the delay from Retry-After yourself, 1 to 5 seconds: respectRetryAfterHeader has no upper limit.
- kotlinx.serialization: build Json with ignoreUnknownKeys = true, name the API's snake_case fields with @SerialName, and give every field you read a default. Declare livemode as Boolean? with the default null: a Boolean with the default false reads a missing field as false. A Map<String, Any> has no serializer: use data classes or buildJsonObject.
- Never block a thread in a route: wait with delay, not Thread.sleep.
- Keep the signer ID and the pinned version IDs in a Sessions cookie with SessionTransportTransformerMessageAuthentication. The visitor can read a signed cookie: put nothing secret in it.
- Install StatusPages with a handler for Throwable: without it Ktor answers 500 with the exception's message as the body.
- A string template escapes nothing. Print the document HTML as it is, and escape everything else you print.
- The page is on screen before the script has a session: render the checkbox disabled and enable it when observeAssent has resolved.

Build
1. Verify the key: GET /v1/usage with ESIGNCOMPLY_API_KEY. Stop if it fails.
2. Register the Terms of Service and the Privacy Notice as documents and publish one version of each from the documents in this project. If the project has none, register short sample documents and say so in your report. Never write or change the wording of the real documents. Create a profile: jurisdictions ["US-FED"], method "checkbox", assurance_level "L1".
3. Server: POST /api/ceremony calls POST /v1/sessions with an Idempotency-Key, saves the signer ID and the pinned version IDs in the signed session cookie, and returns only clientToken, apiUrl and documents.
4. Server: GET /legal/terms and /legal/privacy render the html from GET /v1/documents/{id}/versions/{version_id}/content inside <article data-esc-document>, unmodified.
5. Browser: EsignComply.attach({ clientToken, apiUrl }), presentDocument for each link, observeAssent({ region, checkbox, submit }), then complete() from the user's real click.
6. Server: POST /api/signup/confirm calls GET /v1/records/{id} and requires: status is "recorded", "timestamped" or "anchored"; livemode is as expected; the signer ID and version IDs equal the ones in the session cookie. Only then create the account.

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

Check before you report success
- Run: npx esigncomply check --url http://localhost:8080/signup --callback http://localhost:8080/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 Kotlin?

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

- **kotlinx.serialization refuses a key your class does not declare**

  Kotlin's documentation says unknown keys result in an error during deserialization by default. In the test on kotlinx.serialization 1.11.0, a session answer read with the default `Json` threw `JsonDecodingException: Encountered an unknown key 'id'`, and an error envelope read into a class with required fields threw `MissingFieldException`. The quickstart sets `ignoreUnknownKeys = true`, gives every field a default and declares `livemode` as `Boolean?`.

  Source: [Kotlin docs, Customize the Json instance](https://kotlinlang.org/docs/serialization-json-configuration.html), read on November 26, 2026.

- **HttpRequestRetry retries 5xx answers and exceptions until you tell it not to**

  In the test on Ktor 3.6.2, the plugin installed with no settings sent a `GET` four times to a server that always answered `500`, and a `POST` four times to a server that closed the connection. Its own reading of `Retry-After` has no upper limit: with a header of 8 seconds it waited 8 seconds, twice. The quickstart retries a `429` only, twice, turns the retry on exceptions off and waits 5 seconds at most.

- **Ktor answers 500 with the exception's message as the body**

  In the test on Ktor 3.6.2 without the `StatusPages` plugin, a session route whose API call failed answered `500` with the body `Connection refused (connect failed)`. A call that timed out put the API address and a document ID there, and nothing was logged at the `INFO` level. The quickstart installs `StatusPages` with a handler that logs the exception and answers `internal_error`.

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

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

- Quickstart

  **[Kotlin quickstart](https://esigncomply.com/docs/quickstart/kotlin)**

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

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

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

No. The server SDK exists for Node.js only. A Kotlin server calls the REST API directly with the secret key, and the quickstart does it with the Ktor client in one small class. The build lists Ktor's own artifacts and Logback, and nothing for the API.

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

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

### When should I use the Java or Spring Boot page instead of Kotlin with Ktor?

Use the Spring Boot page when your app runs on Spring Boot, in Kotlin or in Java: it shows the same two calls with `RestClient` and the `HttpSession`. Use the Java page for a service with no framework. This page is for Ktor, the framework JetBrains builds for Kotlin.

### Does the wait before a retry block other requests in Ktor?

No. The retry waits with a coroutine `delay`, which suspends the request and holds no thread. In the test, page requests sent while two confirmations waited to retry were answered in under 0.01 seconds. With `Thread.sleep` in a route, sixteen slow requests made a page request wait 11.5 seconds on four cores.

### Which Ktor client engine does the quickstart use over plain http?

CIO, Ktor's own engine, which speaks HTTP/1.1 only. In the test, Ktor's Java engine with its defaults asked the plain-http test API to upgrade to HTTP/2 and failed with `IOException: HTTP/1.1 header parser received no bytes`. With `protocolVersion` set to `HTTP_1_1` it was answered. Calls over https were not run.

### Other stacks

- [Java](https://esigncomply.com/java)
- [Spring Boot](https://esigncomply.com/spring-boot)
- [Go](https://esigncomply.com/go)

### Platforms used with Kotlin

- [Railway](https://esigncomply.com/railway)
- [Render](https://esigncomply.com/render)
- [Google Cloud Run](https://esigncomply.com/google-cloud-run)

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

## Call the API from the Ktor server you already run. Leave the record to us.

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

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

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