Next.js Printing: Send PDFs to Local Printers by API
Send PDFs from Next.js to a physical printer without a browser print dialog. Build a server-side printing route, protect your API key, and handle retries without duplicate output.
By the PrintScaler team · · 10 min read
Next.js printing to a physical printer requires more than generating a PDF: your deployed application needs a secure path to the computer connected to that printer. With PrintScaler, a Next.js server-side function sends an HTTPS request, and a local agent delivers the job to the printer. This guide builds an authenticated App Router endpoint for internal automation, then explains how to adapt the same printing function for a signed-in user interface.
How Next.js printing works outside the browser
There are three separate jobs in an automated document workflow:
- Generate the document. Your application creates an invoice, packing slip, ticket, or label.
- Submit the print request. Server-side code selects a printer and sends the document to a printing API.
- Deliver it locally. Software near the physical printer receives the job and submits it to the local printing system.
Next.js handles the application logic. PrintScaler provides the API and the local connection.
The request path looks like this:
Trusted workflow or authenticated user action
|
v
Next.js server-side code
|
v
PrintScaler API
|
v
Agent on a local computer
|
v
Physical printer
A PDF viewer or window.print() solves a different problem: asking a person to print from their browser. It does not give a hosted application unattended access to a warehouse printer. If that distinction is your main concern, see the guide to silent printing from a browser.
Which Next.js component should submit the request?
| Next.js feature | Appropriate role |
|---|---|
| Client Component | Show a print button and display application status |
| Server Action | Authenticate a user action and invoke server-side printing logic |
| Route Handler | Accept authenticated requests from an application or internal workflow |
| Server Component rendering | Display data; avoid submitting print jobs as a rendering side effect |
Keep printing inside an explicit action or workflow. Rendering a page should not produce physical output: rendering can happen again for reasons unrelated to a new business event.
1. Connect the printer before writing application code
Start with a printer that already works from its connected computer. Print a local test page first so you are not debugging a driver problem and an application integration simultaneously.
Then:
- Install the PrintScaler agent on that Windows, macOS, Linux, or Raspberry Pi computer.
- Enter the dashboard pairing code in the agent to link the computer.
- Find the printer in the dashboard and use its test-page button.
- Record the printer ID for your application configuration.
The agent runs in the background, starts after reboots, updates itself, and reports printers and their status. It connects outbound over WebSocket, so the agent-based setup does not require opening an inbound port or giving your Next.js hosting environment access to your local network.
The connected computer must remain available for immediate printing. When it is offline, jobs queue and can print after it reconnects, subject to their configured expiration time.
2. Configure server-only environment variables
This tutorial uses a Route Handler called by a trusted backend workflow. It is deliberately not a public browser endpoint: it requires a separate internal bearer token.
Configure these values locally in .env.local and in your deployment platform’s environment settings:
PRINTSCALER_API_KEY=psk_replace_with_your_key
PRINTSCALER_PRINTER_ID=123
INTERNAL_PRINT_TOKEN=replace_with_a_long_random_secret
PRINT_DOCUMENT_HOST=documents.example.com
Replace the example document host with the exact hostname where your application stores printable PDFs. The route will accept only HTTPS URLs on that host.
Do not prefix either secret with NEXT_PUBLIC_. Those values must never be included in a client bundle. Keep .env.local out of version control, and use different credentials for development and production.
The fixed printer ID also matters: the caller cannot change the destination by submitting an arbitrary printer ID. A multi-printer application should instead resolve an authorized destination from trusted business data, such as a warehouse assigned to the order.
3. Create a reusable server-side printing function
Create lib/printing.ts:
import 'server-only';
export async function submitPdfPrint(input: {
documentUrl: string;
title: string;
idempotencyKey: string;
}): Promise<void> {
const apiKey = process.env.PRINTSCALER_API_KEY;
const printerId = Number(process.env.PRINTSCALER_PRINTER_ID);
if (!apiKey || !Number.isSafeInteger(printerId) || printerId < 1) {
throw new Error('Invalid printing configuration');
}
const response = await fetch(
'https://api.printscaler.com/v1/printjobs',
{
method: 'POST',
headers: {
Authorization: `Bearer ${apiKey}`,
'Content-Type': 'application/json',
'X-Idempotency-Key': input.idempotencyKey,
},
body: JSON.stringify({
printerId,
contentType: 'pdf_uri',
content: input.documentUrl,
title: input.title,
}),
cache: 'no-store',
}
);
if (!response.ok) {
throw new Error(`Print submission failed: ${response.status}`);
}
}
If your project does not already include the server-only package, add it using your package manager. Its purpose here is to catch accidental imports of this module into client-side code.
The function uses the actual PrintScaler print-job endpoint and sends a PDF URL. The URL must be retrievable by the printing service; a browser-only session cookie does not travel with this request.
A signed object-storage URL is often suitable, provided it remains valid for the expected retrieval window. For documents that should not be exposed through a URL, the API also accepts pdf_base64. Consult the print-job API documentation for the full integration reference.
Why the idempotency key belongs here
A network failure does not necessarily mean a request failed. The service might have accepted the job before your application lost the response.
Reusing the same X-Idempotency-Key lets your workflow retry the same logical submission without creating another print job. Generate that key when the business operation is created, not independently on every retry.
For example, an initial packing-slip operation might use packing-slip:order-1042:v1:original. An intentional reprint needs a different operation key. The guide to preventing duplicate print jobs covers that distinction in more detail.
4. Add an authenticated Next.js Route Handler
Create app/api/internal/print/route.ts. This example uses the @/ import alias; adjust it if your project uses a different layout.
import { timingSafeEqual } from 'node:crypto';
import { submitPdfPrint } from '@/lib/printing';
export const runtime = 'nodejs';
function authorized(request: Request, token: string): boolean {
const actual = Buffer.from(
request.headers.get('authorization') ?? ''
);
const expected = Buffer.from(`Bearer ${token}`);
return actual.length === expected.length &&
timingSafeEqual(actual, expected);
}
export async function POST(request: Request) {
const token = process.env.INTERNAL_PRINT_TOKEN;
const allowedHost = process.env.PRINT_DOCUMENT_HOST;
if (!token || !allowedHost) {
return Response.json({ error: 'Not configured' }, { status: 503 });
}
if (!authorized(request, token)) {
return Response.json({ error: 'Unauthorized' }, { status: 401 });
}
let documentUrl: string;
let operationId: string;
try {
const body: unknown = await request.json();
if (!body || typeof body !== 'object') throw new Error();
const fields = body as Record<string, unknown>;
if (typeof fields.documentUrl !== 'string' ||
typeof fields.operationId !== 'string') throw new Error();
const url = new URL(fields.documentUrl);
if (url.protocol !== 'https:' || url.hostname !== allowedHost ||
url.username || url.password || url.port) throw new Error();
if (!/^[A-Za-z0-9:_-]{1,120}$/.test(fields.operationId)) {
throw new Error();
}
documentUrl = url.href;
operationId = fields.operationId;
} catch {
return Response.json({ error: 'Invalid input' }, { status: 400 });
}
try {
await submitPdfPrint({
documentUrl,
title: `Document ${operationId}`,
idempotencyKey: `nextjs:${operationId}`,
});
return Response.json({ submitted: true }, { status: 202 });
} catch {
return Response.json(
{ error: 'Print submission could not be confirmed' },
{ status: 502 }
);
}
}
This route demonstrates several useful boundaries:
- Only a caller with the internal token can submit work.
- The destination printer comes from server configuration.
- Document URLs must use an approved host.
- Callers supply a stable operation identifier for retries.
- Upstream response bodies and signed document URLs are not returned in errors.
The host restriction reduces accidental or unauthorized document-source selection, but it is not document-level authorization. Only trusted workflows should hold the internal token. Keep the approved document host under your control, and do not treat this example as a general-purpose public URL printing service.
For production, also configure request-size limits and rate limits at your application or gateway layer.
5. Submit a test print from a trusted caller
Start your development server, then call the route from a terminal. Replace the URL with an actual PDF hosted on your configured document domain:
curl --request POST http://localhost:3000/api/internal/print \
--header "Authorization: Bearer $INTERNAL_PRINT_TOKEN" \
--header 'Content-Type: application/json' \
--data '{
"documentUrl": "https://documents.example.com/packing-slip-1042.pdf",
"operationId": "packing-slip:order-1042:v1:original"
}'
Set INTERNAL_PRINT_TOKEN in that terminal before running the command; Next.js reading .env.local does not automatically export variables into your shell.
A successful response from this example means the API submission was accepted. It does not mean the sheet has physically emerged from the printer.
Check the PrintScaler dashboard for the job and its history. During testing, submit the same operation twice with the same key and verify that it does not create duplicate output. To test a deliberately new print, use a new operation identifier.
Also test an invalid token and a document URL on a different host. Both should be rejected before any print request is submitted.
6. Connect printing to a Next.js user interface
Do not call the internal route from a Client Component with the shared token. Putting that token in browser code would remove the protection the route was designed to provide.
For a user-facing print button, use a separate authenticated Server Action or Route Handler that:
- Verifies the user’s session using your application’s authentication system.
- Accepts an order or document ID rather than an arbitrary PDF URL.
- Checks that the user can print that document at that location.
- Resolves the PDF and printer on the server.
- Creates or retrieves a persisted print-operation record.
- Calls
submitPdfPrintwith that operation’s stable idempotency key.
For multiple printers, extend the helper to accept a server-resolved printer ID instead of reading a single environment variable. Never assume that hiding a printer selector in the interface prevents an unauthorized destination change.
Disabling a button while a request is pending improves usability, but it is not duplicate prevention. Two tabs, repeated workflow deliveries, or a network retry can still submit the same operation. The persisted operation key is the important safeguard.
If your server-side workflow can call the helper directly, it does not need to make an HTTP request back into its own application. The internal route is useful when a separate trusted process needs an integration endpoint.
Handle job status, offline printers, and retries
PrintScaler exposes states including new, sent_to_client, queued, in_progress, done, error, cancelled, and expired. Design your interface around the difference between submitting work and observing its eventual result.
For example, show “Print request submitted” after API acceptance rather than “Packing slip printed.” Later, update the application from job-state information. Treat completion as the printing system’s reported outcome, not independent proof that the correct paper was collected.
For production tracking, extend the example to capture the documented print-job response and persist its identifier alongside the business operation. The minimal helper intentionally discards that response and therefore is not a complete tracking implementation.
Use the job-state reference to map service states into your application’s workflow. PrintScaler also provides HMAC-SHA256-signed, retried webhooks for job-state changes and computer or printer events.
Retry according to the failure
- Invalid credentials or malformed requests: fix the request rather than repeatedly submitting it.
- Rate limiting: slow the caller and retry with backoff.
- Timeouts or temporary service failures: retry with the original idempotency key.
- Offline computers: examine the existing queued job instead of creating another one.
- Expired jobs: decide whether the document is still useful before deliberately creating a new print operation.
PrintScaler’s API rate limit is 10 requests per second with a burst of 30. Use a durable application queue for sustained bursts, and avoid relying on a request handler continuing to run after it returns a response.
Troubleshoot common Next.js printing problems
The PDF opens in my browser but will not print
Check whether the document requires a login cookie, points to localhost, or has an expired signature. Use a service-accessible URL or submit the PDF as Base64. Avoid logging signed URLs while investigating failures.
Printing works locally but fails after deployment
Confirm that the deployed environment has all four configuration values and can make outbound HTTPS requests. Your deployment does not need the office printer driver; the agent computer does. Also confirm that the deployment uses the Node.js runtime for the example route.
The job appears, but no paper comes out
Check the agent computer, local print queue, paper supply, and printer status. A dashboard test page helps separate printer connectivity from a document-specific failure. For labels or unusual paper sizes, inspect the printer’s reported capabilities before selecting print options.
A document prints twice
Check whether each retry generated a fresh operation ID. Also check whether two different application events independently triggered printing. Idempotency protects a shared operation key; it does not know that two unrelated keys represent the same packing slip.
Choose a plan and move to production
PrintScaler charges per print request, not per page. A multi-page PDF sent as one print request therefore differs from submitting every page as a separate job.
The Free plan includes 100 prints per month and one computer, making it suitable for testing this integration. Review the current plans and limits before estimating production volume, particularly if you will connect several locations.
For implementation help, the Markdown API reference can be supplied to an AI coding assistant alongside your application’s authentication and document-storage requirements. Keep actual API keys out of prompts and shared code samples.
Put physical printing behind a deliberate server action
Reliable Next.js printing starts with clear boundaries: the browser requests an authorized business action, server-side code creates a stable print operation, and the local agent handles printer delivery. Keep credentials private, retry with the same operation key, and distinguish submission from completion.
Create a free PrintScaler account, connect one printer, and test the workflow with a single PDF before wiring it into order processing.
Frequently asked questions
Can Next.js print directly to a local printer?
A deployed Next.js application generally cannot reach a printer on a private office network directly. With PrintScaler, server-side code submits an HTTPS request, and an agent on the printer's computer delivers the job locally.
Can I print a PDF from Next.js without opening a print dialog?
Yes. Submit the PDF from server-side code through a printing API rather than calling window.print(). Your application must authenticate the action and select an authorized destination printer.
Should I use a Server Action or Route Handler for printing?
A Server Action can suit a print button in an authenticated Next.js application, while a Route Handler can expose an endpoint for a trusted workflow. Both should call shared server-only printing logic and enforce authorization before submission.
Can I keep my PrintScaler API key in a NEXT_PUBLIC variable?
No. NEXT_PUBLIC variables can be included in browser code, exposing the credential to users. Keep the key in a server-only environment variable and submit print requests from server-side code.
What happens when the printer computer is offline?
PrintScaler queues jobs while the computer is offline, and they can print when it reconnects. Jobs expire after a configurable time, so your application should avoid treating submission as immediate physical completion.
How do I prevent duplicate prints when a Next.js request times out?
Persist a stable identifier for each intended print operation and send it as the X-Idempotency-Key on every retry. Use a new key only for a genuinely new operation, such as an explicitly requested reprint.