# E-sign with JavaScript

Request e-signatures programmatically with the Anvil API in JavaScript. Collect legally binding signatures from any device.

## Quick reference

- Package: `@anvilco/anvil` ([source on GitHub](https://github.com/anvilco/node-anvil))
- Install: `npm install @anvilco/anvil`
- Version: `4.2.0` (latest GitHub release), requires Node.js 20 or later
- API key: every REST and GraphQL request authenticates with your Anvil API key. Find it under Organization settings > API keys ([open in Anvil](https://app.useanvil.com/deep-link?page=api)). Each organization has a development and a production key.
- The examples read the key from the `ANVIL_API_KEY` environment variable. Keep it on your server, never in browser code.
- Test mode: free, unlimited, and never billed. Fill and generate requests made with the development key return watermarked PDFs. E-sign packets created with the development key, or with `isTest: true`, are test packets: their documents carry a watermark and red signatures.
- Rate limits: development keys allow 4 requests per second. Production keys allow 4 per second on Free and Pay-as-you-go plans, and 40 per second on subscriptions. Test requests count toward the same limits.
- PDF template ID: e-sign packets reference one with a file's `castEid`. Find it on the template's page in Anvil, in the URL (`/org/<your-org-slug>/pdf/<pdf-template-id>`) or behind the `PDF Template ID / Cast EID` copy button. The examples use a sample template any account can use; to make your own, see [Set up a PDF template](https://www.useanvil.com/help/tutorials/set-up-a-pdf-template/).
- More on keys, test mode, and rate limits: [Getting started](/docs/api/getting-started.md)

### Authenticate with the JavaScript SDK

```javascript
import Anvil from '@anvilco/anvil'

// One line to authenticate every request.
const anvil = new Anvil({ apiKey: process.env.ANVIL_API_KEY })

const { statusCode, data } = await anvil.requestGraphQL({ query: '{ currentUser { eid } }' })
```

## JavaScript Code Example

```javascript
// Create an Etch e-sign packet via the Anvil API and send it to a signer.
// Docs: https://www.useanvil.com/docs/api/e-signatures
//
// Run it from a project with @anvilco/anvil installed:
//   ANVIL_API_KEY=yourKey node sign.js your.real.email@example.com
//
// A signature request email is sent to the address you pass, so use your real
// email address. The new packet also appears in your dashboard's e-sign area.

import Anvil from '@anvilco/anvil'

// Your API key from your Anvil organization settings
const apiKey = process.env.ANVIL_API_KEY ?? ''

// A sample PDF template available to any account. See
// https://www.useanvil.com/help/tutorials/set-up-a-pdf-template
// to set up your own
const pdfTemplateID = '05xXsZko33JIO6aq5Pnr'

const signerName = 'Testy Signer'
const signerEmail = process.argv[2] ?? ''

if (!signerEmail) {
  console.log('Enter your email address as the script\'s 1st argument')
  process.exit(1)
}

async function createEtchPacket () {
  const anvilClient = new Anvil({ apiKey })

  const { statusCode, data, errors } = await anvilClient.createEtchPacket({
    variables: {
      // The packet is ready to send: an email goes to the first signer.
      // Use isDraft: true to review it in the dashboard first
      isDraft: false,

      // Test packets use development signatures and do not count toward
      // your billed packets
      isTest: true,

      // Set to true for interactive signing, where signers fill fields as
      // they sign. Over the API that needs the Product pack or Enterprise
      // plan
      allowUpdates: false,

      name: `Test Docs - ${signerName}`,
      signatureEmailSubject: 'Custom email subject',
      signatureEmailBody: 'Custom please sign these documents....',

      files: [
        {
          // Your own ID for referencing this file in `data` and
          // `signers` below
          id: 'sampleTemplate',
          castEid: pdfTemplateID,
        },
      ],

      data: {
        // This data fills the PDF before it is sent to any signers. IDs
        // here match the fields configured on the PDF template
        payloads: {
          sampleTemplate: {
            data: {
              name: signerName,
              email: signerEmail,
            },
          },
        },
      },

      signers: [
        // Signers sign in the order they are specified in this array
        {
          id: 'signer1',
          name: signerName,
          email: signerEmail,
          signerType: 'email',

          // The fields this signer clicks through, in this order
          fields: [
            {
              fileId: 'sampleTemplate',
              fieldId: 'signature',
            },
          ],
        },
      ],
    },
  })

  if (errors) {
    // GraphQL can return a 200 status code even when there are errors
    console.log(
      'There were errors:', statusCode, JSON.stringify(errors, null, 2)
    )
  } else {
    const packetDetails = data?.data?.createEtchPacket
    console.log(
      'Visit the new packet on your dashboard:', packetDetails?.detailsURL
    )
  }
}

createEtchPacket().catch((error) => {
  console.error(error)
  process.exit(1)
})
```

Full runnable example: https://github.com/anvilco/node-anvil/blob/main/examples/sign.js

## Responses

Every method resolves with `{ statusCode, data, errors }`, and only rejects when the request cannot be made at all, like a network failure (`fetch failed`). An API error sets `errors` instead. GraphQL errors can arrive with a `200`, so check `errors`, not the status code.

```javascript
import Anvil from '@anvilco/anvil'

const anvil = new Anvil({ apiKey: process.env.ANVIL_API_KEY })

const { statusCode, data, errors } = await anvil.createEtchPacket({
  variables: {
    isTest: true,
    files: [{ id: 'sampleTemplate', castEid: '05xXsZko33JIO6aq5Pnr' }],
    signers: [{
      id: 'signer1',
      name: 'Sally Jones',
      email: 'sally@example.com',
      fields: [{ fileId: 'sampleTemplate', fieldId: 'signature' }],
    }],
  },
})

// GraphQL errors can arrive with a 200, so check `errors`, not the status.
if (errors) throw new Error(`${statusCode}: ${JSON.stringify(errors)}`)

// GraphQL results sit under `data.data`. By default the packet carries eid,
// name, status, isTest, detailsURL, numberRemainingSigners, its timestamps,
// and documentGroup.signers, each with eid, name, email, status and
// routingOrder.
const packet = data?.data?.createEtchPacket
console.log(packet.eid, packet.detailsURL, packet.documentGroup.signers[0].eid)
```

## Uploading files

Anywhere the API takes a file, such as each `file` in an e-sign packet's `files`, it accepts one of three upload formats. E-sign packets take PDF and Word (`.docx`) files, and a `.docx` is converted to PDF on upload. Shapes and limits: [Object Shapes](/docs/api/object-references.md).

### Multipart upload

A file from disk, a stream, or bytes, sent as a multipart request. Use it for files too big for a base64 upload.

```javascript
import Anvil from '@anvilco/anvil'

const anvil = new Anvil({ apiKey: process.env.ANVIL_API_KEY })

// A path or file stream is streamed up as a multi-part upload, never read
// into memory, and sent again in full if the request has to be retried.
const { data, errors } = await anvil.createEtchPacket({
  variables: {
    files: [{
      id: 'lease',
      title: 'Lease',
      file: Anvil.prepareGraphQLFile('./lease.pdf'),
      fields: [{ id: 'sig', type: 'signature', pageNum: 0, rect: { x: 100, y: 100, width: 150, height: 30 } }],
    }],
  },
})
```

### Base64 upload

`{ data, filename, mimetype }`, all three required, sent as plain JSON. The whole request body is limited to 1MB, and base64 makes a file about a third bigger, so use a multipart upload for larger files.

```javascript
import { readFileSync } from 'fs'
import Anvil from '@anvilco/anvil'

const anvil = new Anvil({ apiKey: process.env.ANVIL_API_KEY })

const file = {
  data: readFileSync('./lease.pdf').toString('base64'),
  filename: 'lease.pdf',
  mimetype: 'application/pdf',
}

const { data, errors } = await anvil.createEtchPacket({
  variables: {
    files: [{
      id: 'lease',
      title: 'Lease',
      file,
      fields: [{ id: 'sig', type: 'signature', pageNum: 0, rect: { x: 100, y: 100, width: 150, height: 30 } }],
    }],
  },
})
```

### URL upload

`{ url, filename }`: Anvil downloads the file from a publicly accessible URL. `filename` is optional; without it, the name comes from the URL or the server's `Content-Disposition` header.

```javascript
import Anvil from '@anvilco/anvil'

const anvil = new Anvil({ apiKey: process.env.ANVIL_API_KEY })

// Anvil downloads the file, so the URL must be publicly accessible.
const file = { url: 'https://example.com/lease.pdf', filename: 'lease.pdf' }

const { data, errors } = await anvil.createEtchPacket({
  variables: {
    files: [{
      id: 'lease',
      title: 'Lease',
      file,
      fields: [{ id: 'sig', type: 'signature', pageNum: 0, rect: { x: 100, y: 100, width: 150, height: 30 } }],
    }],
  },
})
```

## Embedded signing

By default Anvil emails each signer a link. Set a signer's `signerType` to `embedded` and Anvil sends no email: your app shows them the signing page instead.

1. Create the packet with `isDraft: false`. A packet has to be sent before anyone can sign it, embedded signers included.
2. Take the signer's `eid` from the `createEtchPacket` response.
3. When the user is ready to sign, generate a signing URL with the `generateEtchSignURL` mutation, passing your own ID for the user as `clientUserId`. The URL expires after 2 hours by default, so generate it at that moment rather than emailing it.
4. Redirect the user to the URL, or show it in an iframe. An iframe needs embedding enabled and your domain allowlisted in your API settings. The signer's `redirectURL` brings them back to your app when they finish.

Find out when signing is done with [Webhooks](/docs/api/webhooks.md).

```javascript
import Anvil from '@anvilco/anvil'

const anvil = new Anvil({ apiKey: process.env.ANVIL_API_KEY })

// 1. Create and send the packet with an embedded signer. Anvil emails them
// nothing; your app shows them the signing page.
const created = await anvil.createEtchPacket({
  variables: {
    isTest: true,
    isDraft: false,
    files: [{ id: 'sampleTemplate', castEid: '05xXsZko33JIO6aq5Pnr' }],
    signers: [{
      id: 'signer1',
      name: 'Sally Jones',
      email: 'sally@example.com',
      signerType: 'embedded',
      // Where Anvil sends the signer when they finish
      redirectURL: 'https://yourapp.com/signed',
      fields: [{ fileId: 'sampleTemplate', fieldId: 'signature' }],
    }],
  },
})
if (created.errors) throw new Error(JSON.stringify(created.errors))

// 2. The signer's eid is in the createEtchPacket response.
const signerEid = created.data?.data?.createEtchPacket.documentGroup.signers[0].eid

// 3. When the user is ready to sign, generate a fresh URL. It expires after
// 2 hours by default. The method is generateEtchSignUrl, with a lowercase rl.
const { url, errors } = await anvil.generateEtchSignUrl({
  variables: {
    signerEid,
    // Your own ID for the user who is signing
    clientUserId: 'user-123',
  },
})
if (errors) throw new Error(JSON.stringify(errors))

// 4. Redirect the user to `url`, or show it in an iframe.
console.log(url)
```

## Installation

The [@anvilco/anvil](https://github.com/anvilco/node-anvil) package is MIT-licensed and maintained in the open on GitHub.

```sh
npm install @anvilco/anvil
yarn add @anvilco/anvil
pnpm add @anvilco/anvil
bun add @anvilco/anvil
```

## Set-up with Claude

Let Claude build your integration

```sh
/plugin marketplace add anvilco/anvil-plugins
/plugin install anvil-document-sdk@anvil-plugins
```

No API key setup needed. The plugin connects to your Anvil account with OAuth and logs you in automatically. The plugin's sign-in covers Claude only: the code your app runs authenticates with an API key (see Quick reference).

## Why Anvil

### We're fast

Send documents for e-signature in a single API call – one signer or thousands of signature packets.

### Flexibility

Request signatures on existing templates, uploaded PDFs, or documents you generate on the fly. Use Anvil's signing pages or embed signing directly in your product.

### Easy-to-use

Integrate e-signatures into your app with just a few lines of code. Create a packet, add signers, and send. Anvil handles notifications and signing order.

### Compliant

SOC 2 Type 2 certified, HIPAA-eligible with a BAA, and GDPR-ready. Signatures are legally binding and backed by industry-standard PKI digital certificates.

## Next Steps

- [Open in Github](https://github.com/anvilco/node-anvil/blob/main/examples/sign.js)
- [JavaScript SDK](https://github.com/anvilco/node-anvil)
- [API Documentation](/docs/api/e-signatures.md)

## Related Resources
- [The Anvil SDK for JavaScript](/products/javascript.md): Build document workflows in JavaScript with the Anvil SDK. Generate PDFs, fill templates, and collect e-signatures from one package.
- [Generate PDFs with JavaScript](/products/javascript/generate.md): Automate your PDF generation process by using the Anvil PDF API in JavaScript. Quickly scale your PDF-based process.
- [Fill PDFs with JavaScript](/products/javascript/fill.md): Fill existing PDF templates programmatically with the Anvil API in JavaScript. Automate document workflows at scale.
- [E-sign with C# & .NET](/products/csharp-dotnet/esign.md): Request e-signatures programmatically with the Anvil API in C#. Collect legally binding signatures from any device.
- [E-sign with Python](/products/python/esign.md): Request e-signatures programmatically with the Anvil API in Python. Collect legally binding signatures from any device.
- [E-sign with TypeScript](/products/typescript/esign.md): Request e-signatures programmatically with the Anvil API in TypeScript. Collect legally binding signatures from any device.
- [Getting Started](/docs/api/getting-started.md): Authentication, terminology, and first steps with the Anvil API.
- [GraphQL Guide](/docs/api/graphql.md): Anvil's GraphQL API: query and update workflows, e-sign packets, and the other objects your account owns.
- [Object Shapes](/docs/api/object-references.md): The JSON object shapes the API accepts and returns.
- [Webhooks](/docs/api/webhooks.md): Anvil POSTs to your URL when something happens, like a signer finishing (`signerComplete`) or a packet completing (`etchPacketComplete`).
