Frameworks · Updated 2026-12-03
Generate PDFs in Next.js
Generating PDFs inside a Next.js app often means bundling a headless browser into a serverless function and then fighting its size limits and missing fonts. This guide skips that: a route handler sends your data to DevilPDF and streams the finished PDF back. The function stays small and runs anywhere Next.js runs, including Vercel.
You need the App Router (Next.js 13.4 or later) and a DevilPDF API key. The free plan includes 500 documents a month.
#1. Add the API key
Sign up, create a key under API keys, and add it to .env.local:
DEVILPDF_API_KEY=dp_live_...Do not prefix it with NEXT_PUBLIC_. That prefix ships the value to the browser. Without it, the key is only readable on the server. On Vercel, add the same variable under the project's environment variables.
#2. A small server-only helper
import "server-only";
export async function renderPdf(body: Record<string, unknown>): Promise<ArrayBuffer> {
const res = await fetch("https://devilpdf.com/v1/render", {
method: "POST",
headers: {
Authorization: `Bearer ${process.env.DEVILPDF_API_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({ ...body, output: "file" }),
cache: "no-store",
});
if (!res.ok) {
const { error } = await res.json();
throw new Error(`${error.type}: ${error.message}`);
}
return res.arrayBuffer();
}import "server-only" makes the build fail if a client component ever imports this file. Install it with npm install server-only. "output": "file" asks for the PDF bytes instead of a JSON document with a link.
#3. The route handler
import { renderPdf } from "@/lib/devilpdf";
export async function GET(
_req: Request,
{ params }: { params: Promise<{ number: string }> },
) {
const { number } = await params;
const invoice = await getInvoice(number);
if (!invoice) return new Response("Not found", { status: 404 });
const pdf = await renderPdf({
template: "invoice",
data: invoice,
filename: `invoice-${number}`,
});
return new Response(pdf, {
headers: {
"Content-Type": "application/pdf",
"Content-Disposition": `inline; filename="invoice-${number}.pdf"`,
},
});
}
// Replace with your database query. Check that the signed-in user may see this invoice.
async function getInvoice(number: string) {
return {
number,
issue_date: "2026-12-03",
company: { name: "Northwind Studio" },
customer: { name: "Acme Robotics Inc." },
items: [
{ name: "Brand identity system", quantity: 1, unit_price: 4800 },
{ name: "Front-end development", quantity: 46, unit_price: 135 },
],
tax_rate: 13,
tax_label: "HST",
};
}Open /invoices/INV-1001 and the PDF shows in the browser. Change inline to attachment to force a download. In Next.js 15 and later params is a promise, as above. On Next.js 14, type it as a plain object and drop the await.
The invoice starter adds up the items, discount and tax itself. Fetch GET /v1/templates/invoice with your key to see every field it accepts in sample_data. The other starters are quote, receipt, statement, report, packing-slip and certificate.
#Link instead of bytes
If you would rather store a link on the order, or email it, leave out "output": "file". The response is JSON with url, id and pages.
export async function POST(req: Request) {
const order = await req.json();
const res = await fetch("https://devilpdf.com/v1/render", {
method: "POST",
headers: {
Authorization: `Bearer ${process.env.DEVILPDF_API_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({ template: "receipt", data: order }),
});
const doc = await res.json();
if (!res.ok) return Response.json({ error: doc.error.message }, { status: 502 });
return Response.json({ url: doc.url, pages: doc.pages });
}Validate order before you pass it on, as you would for any request body. Hosted links expire: after 24 hours on the free plan, longer on paid plans. Copy the file to your own storage if it must live longer, or have DevilPDF deliver it to your S3 bucket.
#A button in the UI
A client component only needs a link to your route. The API key is never involved.
export function DownloadInvoice({ number }: { number: string }) {
return (
<a href={`/invoices/${number}`} target="_blank" rel="noopener">
Download PDF
</a>
);
}#Why not Puppeteer in the function?
You can, and many people do, with puppeteer-core and a serverless build of Chromium such as @sparticuz/chromium. Its README notes that the browser archive is over 50 MB, which is why there is a separate -min package that downloads it at runtime, and that it ships with a single font, Open Sans, which covers Latin, Greek and Cyrillic. Anything else needs fonts you add yourself. We cover that in Arabic text missing in PDFs on Vercel.
With an API, the function only makes an HTTP request, and every script renders: send "locale": "ar" or "ja" and the labels, numbers and direction follow. See languages.
#Next steps
- Quickstart
- Templates: copy a starter or write your own in HTML.
- Generate PDFs in Node.js
- Generate PDFs from a Supabase Edge Function
- Get a free API key