Prepare an invoice template
You’ll need a Bitavu workspace with render credits and a supported Node.js LTS release. @bitavu/client includes TypeScript declarations and supports Node.js 22.13 and later in the Node.js 22, 24, and 26 release lines. It has no runtime dependencies and uses the MIT license.
Open the starter invoice
In Bitavu Studio, open Studio invoice or use your own invoice template. Preview it with example data and save a version.
Copy the template ID and revision
Under Integrations → Prepare a template request, choose the saved revision and open Use in your app. Copy the
templateIdand numericrevision.Create an API key for this template
Under Integrations → API keys, create a key with access to the invoice template and Generate PDFs permission. Copy the key when Studio displays it.
Generate a PDF with Node.js
Install the SDK in your project.
npm install @bitavu/clientAdd these settings to an ignored .env.local file at the project root. Replace the placeholders with the values from Studio. For a deployed app, set the API key through your hosting provider’s secret store.
BITAVU_API_KEY=<your Bitavu API key>
BITAVU_TEMPLATE_ID=<your template ID>
BITAVU_TEMPLATE_REVISION=<your saved revision number>Save this fictional invoice as invoice-data.json. If you use your own template, match the JSON property names and types to your template bindings.
{
"invoice": { "number": "INV-1001", "date": "2026-11-01", "due": "2026-11-15" },
"client": { "name": "Example Customer", "address": "100 Example Street" },
"items": [
{ "description": "Design consultation", "quantity": 1, "unitPrice": 240 },
{ "description": "Layout review", "quantity": 2, "unitPrice": 90 }
],
"notes": "Fictional invoice for testing the integration."
}Save the script below as render.mjs. The client preserves the property names in your JSON. It returns the PDF bytes as a Uint8Array and includes the rendered revision, page count, and request ID when the API supplies them.
import { randomUUID } from 'node:crypto';
import { readFile, writeFile } from 'node:fs/promises';
import { BitavuClient } from '@bitavu/client';
const apiKey = process.env.BITAVU_API_KEY;
const templateId = process.env.BITAVU_TEMPLATE_ID;
const revision = Number(process.env.BITAVU_TEMPLATE_REVISION);
if (!apiKey || !templateId || !Number.isSafeInteger(revision) || revision < 1) {
throw new Error('Configure the Bitavu API key, template ID and saved revision.');
}
const client = new BitavuClient({ apiKey });
const data = JSON.parse(await readFile(new URL('./invoice-data.json', import.meta.url), 'utf8'));
const pdf = await client.renderPdf({
templateId,
revision,
data,
idempotencyKey: randomUUID(),
});
await writeFile('invoice.pdf', pdf.bytes);
console.log('Rendered revision', pdf.revision);node --env-file=.env.local render.mjsOpen invoice.pdf to see invoice INV-1001 with two line items.
Choose a template revision
A numeric revision pins the saved layout you tested. To follow the current publication, replace the render call in render.mjs with the one below. baseRevision tells Bitavu which tested revision to use for the compatibility check. If you omit it, Bitavu uses the first published revision.
const pdf = await client.renderPdf({
templateId,
revision: 'latest-published',
baseRevision: revision,
data,
idempotencyKey: randomUUID(),
}, { signal: AbortSignal.timeout(120_000) });An incompatible publication returns HTTP 409 with JSON_COMPATIBILITY. A template without a publication returns HTTP 404 with NOT_PUBLISHED. Either mode accepts mappingId for a data mapping saved in Studio.
Read templates and save examples
| Method | What it does |
|---|---|
checkCredentials() | Completes if the API key is valid. |
listTemplates() | Returns the accessible templates, with each folder path, latest saved revision, and Studio link. |
getTemplateVersions(templateId, { page, pageSize, revision }) | Returns a page of saved revision summaries, the latest revision, and the selected revision if you requested one and it exists. |
getTemplate(templateId, revision) | Returns the saved revision’s Studio link, data bindings, example JSON, and input review. |
saveTemplateExample({ templateId, expectedRevision, exampleJson }) | Saves example data as a new revision and returns that revision with the updated input review. |
Template reads require Read templates. Saving examples requires Save template examples. Use the latest saved revision as expectedRevision. If there’s a conflict, fetch the latest revision and check its bindings before saving again.
The SDK types the fixed response fields. Use your own TypeScript interface for template data. The type argument to getTemplate<InvoiceData>() describes the JSON shape you expect. Validate the example in your application if its shape is uncertain.
interface InvoiceData {
invoice: { number: string; date: string; due: string };
client: { name: string; address: string };
items: { description: string; quantity: number; unitPrice: number }[];
notes: string;
}
const { exampleJson, inputReview, studioUrl } =
await client.getTemplate<InvoiceData>(templateId, revision);inputReview.missing lists bindings absent from the saved example, and inputReview.unused lists paths the template does not use. Both exampleJson and inputReview are null when the revision has no saved example.
Handle errors and retries
BitavuApiError exposes status, code, requestId, and retryAfterMs when available. BitavuTransportError identifies timeouts and network failures. Pass an AbortSignal to cancel a request.
Requests have a two-minute deadline by default. Your application controls retries. Reuse the operation ID with the same template, revision selection, and data when retrying a render. Respect retryAfterMs when returned. Use a new operation ID for a different render.
Add a PDF download in Next.js
In a TypeScript project using the App Router, install the packages below. Put the same .env.local and invoice-data.json files at the project root. The paths here assume your app directory is at the root.
npm install @bitavu/client server-onlyCreate lib/invoice.ts. The server-only module reads the API key and reuses the SDK client. Keep the key out of NEXT_PUBLIC_ variables.
import 'server-only';
import { BitavuClient } from '@bitavu/client';
import invoice from '../invoice-data.json';
interface InvoiceData {
invoice: { number: string; date: string; due: string };
client: { name: string; address: string };
items: { description: string; quantity: number; unitPrice: number }[];
notes: string;
}
let client: BitavuClient | undefined;
export function renderInvoice(operationId: string, signal: AbortSignal) {
const apiKey = process.env.BITAVU_API_KEY;
const templateId = process.env.BITAVU_TEMPLATE_ID;
const revision = Number(process.env.BITAVU_TEMPLATE_REVISION);
if (!apiKey || !templateId || !Number.isSafeInteger(revision) || revision < 1) {
throw new Error('Configure the Bitavu API key, template ID and saved revision.');
}
client ??= new BitavuClient({ apiKey });
return client.renderPdf<InvoiceData>({
templateId, revision, data: invoice, idempotencyKey: operationId,
}, { signal });
}Create app/api/invoices/[operationId]/route.ts. The handler sends the operation ID and cancellation signal to Bitavu, then returns the invoice as a download.
import { BitavuApiError, BitavuTransportError } from '@bitavu/client';
import { renderInvoice } from '../../../../lib/invoice';
export const runtime = 'nodejs';
export async function POST(
request: Request, { params }: { params: Promise<{ operationId: string }> },
) {
const noStore = { 'Cache-Control': 'no-store' };
const host = request.headers.get('host') ?? '';
const origin = request.headers.get('origin');
if (!/^(?:127\.0\.0\.1|localhost)(?::\d+)?$/.test(host)
|| (origin !== null && origin !== 'http://' + host)) {
return Response.json({ error: 'This sample is for local use.' }, { status: 403, headers: noStore });
}
const { operationId } = await params;
if (!/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(operationId)) {
return Response.json({ error: 'Use a UUID for the operation ID.' }, { status: 400, headers: noStore });
}
try {
const pdf = await renderInvoice(operationId, request.signal);
return new Response(pdf.bytes, {
headers: {
...noStore,
'Content-Type': 'application/pdf',
'Content-Disposition': 'attachment; filename="invoice.pdf"',
'X-Content-Type-Options': 'nosniff',
},
});
} catch (error) {
if (error instanceof BitavuApiError) {
console.warn('Bitavu render failed', { status: error.status, code: error.code, requestId: error.requestId });
} else if (error instanceof BitavuTransportError) {
console.warn('Bitavu transport failed', { code: error.code });
}
return Response.json({ error: 'Could not generate the invoice.' }, { status: 502, headers: noStore });
}
}Run the app locally and make a POST request from a second terminal. On Windows, use curl.exe if curl is a PowerShell alias.
npm run dev -- --hostname 127.0.0.1 --port 3000curl --fail --output invoice.pdf -X POST http://127.0.0.1:3000/api/invoices/37f27493-e462-479c-b5f1-495508ce629aUse your own operation ID. Reuse it when retrying the same render with the same input. A different invoice or template revision needs a new operation ID.
For a deployed app, adapt the local route to your authentication and request forgery protections. Check that the signed-in user can access the invoice, then load its data on the server.
Troubleshooting
If the request fails, look at the server’s HTTP status and Bitavu error code. HTTP 401 can indicate an invalid or expired key. HTTP 403 can mean the key lacks Generate PDFs or access to the template.
If the PDF is missing values, compare the input with the template bindings. Check the spelling, nesting and types of the line-item fields. If you contact Bitavu Support, share the error code and request ID when available.