Print shipping labels from a Next.js route
Print from a Next.js route handler on the server. Do not call the API from a client component. The key stays in the server environment.
For Next.js apps that buy or render shipping labels
Overview
A Next.js client component runs in the browser. Putting PRINTBASE_API_KEY there publishes it. The route handler or a server action runs on the server, reads the key, and posts the label.
Shipping labels are usually PDF. content_type pdf. If your carrier returns ZPL, switch to raw in that branch only. The App Router and the Pages router differ only in where you put the function.
The local agent port 127.0.0.1:17891 rejects origins that are not localhost or a printbase.cloud host. Your production origin cannot call it. Use the cloud API.
Integration steps
- 01
Create an API key on the server
Use an API key (pb_live_…) in the process environment. Authorization is Bearer. Do not ship the key to browsers or mobile apps.
- 02
Install the agent beside the printer
Windows, macOS, or Linux. GET /v1/printers and keep the numeric code.
- 03
POST /v1/print-jobs
content_type is pdf or raw. Send exactly one of content (standard base64) or content_url.
- 04
Reuse the idempotency key on retry
A new key means a second physical print. HTTP 409 means the same key was reused with a different body.
- 05
Read the job before you tell the user
GET /v1/print-jobs/{id}. Paid plans can also receive print_job.completed and print_job.failed webhooks.
Node.js
// Next.js route handler: shipping-label PDF
const res = await fetch('https://api.printbase.cloud/v1/print-jobs', {
method: 'POST',
headers: {
Authorization: `Bearer ${process.env.PRINTBASE_API_KEY}`,
'Content-Type': 'application/json',
'Idempotency-Key': shipmentId,
},
body: JSON.stringify({
printer_code: Number(process.env.PRINTER_CODE),
content_type: 'pdf',
content: pdf.toString('base64'),
copies: 1,
}),
});
if (!res.ok) throw new Error(`PrintBase ${res.status}: ${await res.text()}`);
const job = await res.json();
// { id: "job_abc", status: "queued" }
Details for this setup
Server only
Read the key from process.env inside the route. Do not prefix it with NEXT_PUBLIC.
Return the job id to the UI
The button can show queued. It should not claim the label printed until a later poll says completed.
Questions
Can I use a server action?
Yes. It is still server code. Same JSON. The call is still POST /v1/print-jobs with a Bearer API key, and HTTP 201 means queued rather than printed.
Edge runtime?
If the edge runtime can do HTTPS, it can POST. Do not assume the local printer is on the edge node.
Where is the printer?
On a computer running the agent, identified by printer_code. Not on the Vercel or Node host.
Duplicate clicks on the button?
Disable the button and send a stable Idempotency-Key from the shipment id.
Free plan: 100 jobs a month on one computer, no card.