How to Integrate DocuSign in a MERN Stack Application

Introduction
In today’s digital world, businesses rely on eSignatures to streamline document signing. DocuSign is a leading electronic signature platform that makes this process seamless. If you’re building a MERN (MongoDB, Express.js, React, Node.js) application and need to integrate DocuSign, this guide will walk you through the process step by step.
Whether you’re creating a contract management system or adding eSignature functionality to an existing app, integrating DocuSign can enhance user experience and security. Let’s dive in!
Step 1: Setting Up a DocuSign Developer Account
To get started, you need a DocuSign Developer Account. Follow these steps:
- Go to DocuSign Developer Center and sign up.
- Once registered, log in to the DocuSign Admin Dashboard.
- Navigate to the Apps and Keys section to generate an Integration Key (API Key).
- Note down your Client ID, Secret Key, and Redirect URI for authentication.
Step 2: Install DocuSign SDK in Your Node.js Backend
Your backend will communicate with DocuSign using the official DocuSign eSignature SDK. Install it using npm:
npm install docusign-esign dotenv
Also, install dotenv to securely store your API keys.
Step 3: Configure Environment Variables
Create a .env
file in your backend and add the following credentials:
DOCUSIGN_CLIENT_ID=your_client_id
DOCUSIGN_CLIENT_SECRET=your_client_secret
DOCUSIGN_USER_ID=your_user_id
DOCUSIGN_REDIRECT_URI=your_redirect_uri
DOCUSIGN_PRIVATE_KEY=your_private_key
DOCUSIGN_BASE_PATH=https://demo.docusign.net/restapi
Ensure that .env
is added to your .gitignore
file to keep credentials secure.
Step 4: Authenticate and Get an Access Token
To interact with DocuSign APIs, your app must authenticate using OAuth 2.0. Here’s how to generate an access token in Node.js:
const docusign = require("docusign-esign");
const fs = require("fs");
require("dotenv").config();
async function getAccessToken() {
const apiClient = new docusign.ApiClient();
apiClient.setBasePath(process.env.DOCUSIGN_BASE_PATH);
apiClient.setOAuthBasePath("account-d.docusign.com");
const jwtToken = await apiClient.requestJWTUserToken(
process.env.DOCUSIGN_CLIENT_ID,
process.env.DOCUSIGN_USER_ID,
["signature"],
fs.readFileSync("private.key"), // Your RSA private key
3600
);
return jwtToken.body.access_token;
}
Once you get the access token, store it and use it for API requests.
Step 5: Send a Document for Signature
To send a document for signing, create an envelope and specify the recipient:
async function sendDocument(accessToken) {
const apiClient = new docusign.ApiClient();
apiClient.setBasePath(process.env.DOCUSIGN_BASE_PATH);
apiClient.addDefaultHeader("Authorization", "Bearer " + accessToken);
const envelopesApi = new docusign.EnvelopesApi(apiClient);
const envelopeDefinition = {
emailSubject: "Please sign this document",
documents: [
{
documentBase64: Buffer.from(fs.readFileSync("contract.pdf")).toString("base64"),
name: "Contract",
fileExtension: "pdf",
documentId: "1",
},
],
recipients: {
signers: [
{
email: "recipient@example.com",
name: "John Doe",
recipientId: "1",
routingOrder: "1",
tabs: {
signHereTabs: [
{
anchorString: "/signature/",
anchorXOffset: "10",
anchorYOffset: "10",
},
],
},
},
],
},
status: "sent",
};
const results = await envelopesApi.createEnvelope(process.env.DOCUSIGN_USER_ID, { envelopeDefinition });
console.log("Envelope sent! Envelope ID:", results.envelopeId);
}
getAccessToken().then(sendDocument);
This script uploads a PDF, adds a signature field, and sends it to the recipient for signing.
Step 6: Handle Webhooks for Real-Time Updates
To track document status (signed, declined, etc.), configure webhooks:
- In the DocuSign Developer Dashboard, go to Apps and Keys > Webhooks.
- Set up a webhook URL where DocuSign will send status updates.
In your Express.js backend, create a webhook endpoint:
const express = require("express");
const app = express();
app.use(express.json());
app.post("/webhook/docusign", (req, res) => {
console.log("Webhook Data:", req.body);
res.status(200).send("Webhook received");
});
app.listen(3000, () => console.log("Server running on port 3000"));
This logs the status updates received from DocuSign.
Step 7: Integrate with Your React Frontend
On the frontend, trigger the signing process by making an API request:
fetch("http://localhost:3000/send-document", {
method: "POST",
headers: { "Content-Type": "application/json" },
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error("Error:", error));
You can also embed the DocuSign signing process within your React app using Embedded Signing.
Integrating DocuSign into a MERN stack application allows businesses to automate document signing securely. From authentication to sending and tracking signed documents, this guide covered all essential steps to streamline the process.
For more tech guides, web development insights, and software solutions, check out CodeHunger.