Generate an invoice in Next.js
To generate an invoice PDF in Next.js, call DocKiln from an authenticated server route, submit a published template with order data, then poll the returned job ID and download the PDF. Keep the workspace API key on the server.
What do you need?
A DocKiln workspace API key, a published Invoice template, and a Next.js application with server-side authentication. The sample below uses fictional order data; calculate real totals in your order system.
Generate an invoice from an order
- Create an Invoice draft. Set the closing line to
Total due · {{total}}and publish it. Copy its ID from the templates API. - Copy the server helper and the job client into the same directory. Set
DOCKILN_URL,DOCKILN_API_KEY, andINVOICE_TEMPLATE_IDin the server environment. Use the Node.js runtime. - In an App Router route handler, require your app session and load an order belonging to that account. Pass that order to the helper. The following call shows the expected shape using fictional data.
return invoiceResponse({
customer: "Juniper Works",
lines: [{ description: "Print design", quantity: 1, amount: "$150.00" }],
total: "$150.00"
});
The helper queues the PDF, polls for up to 60 seconds and returns a download response. For a shorter hosting request deadline, return the job ID immediately and download from a second authenticated route. Keep totals in the order system and pin a published version if your invoice format must remain stable.
Run the route locally
Copy the App Router endpoint to app/api/sample-invoice/route.js in your Next.js project and put the two helpers beside it. Set a fresh, separate NEXT_TUTORIAL_TOKEN on the Next.js server. This sample route authenticates its caller and uses a fictional fixed order. Start Next.js on port 3001 with DocKiln on 3000.
curl --fail -X POST http://localhost:3001/api/sample-invoice \
-H "Authorization: Bearer $NEXT_TUTORIAL_TOKEN" -o invoice.pdf
For real customer invoices, replace the tutorial token with your application’s normal user authentication and authorize access to the requested order.
Should the route wait for the PDF?
Wait only when your hosting request deadline comfortably exceeds the generation time. For background processing, return the job ID immediately and poll from a second authorized route, or handle a signed webhook. A successful submission is HTTP 202; it does not mean the PDF has finished rendering.
How do you avoid duplicate invoices?
Use a stable idempotency key for the same order and generation request. Retrying the same request should recover the original job; changing the payload under the same key produces a conflict. Authorize the order before sending any data to DocKiln.
Check the result
Verify the recipient, currency, total, long line items and page breaks in the downloaded PDF. Start with the invoice generator, inspect a sample invoice PDF, and use the API reference for the current request contract.