Generate PDFs in Next.js on Vercel Without Chrome
In this article
Generating PDFs in Next.js on Vercel without running a headless Chrome browser is achievable using lightweight JavaScript libraries that build PDFs directly from data or HTML strings. This approach avoids the cold-start latency and memory limits associated with browser automation, making it faster and more cost-effective for serverless functions. You'll use libraries like pdf-lib for programmatic PDF creation or react-pdf (via @react-pdf/renderer) for rendering React components to PDF. This guide covers both methods, with steps tailored for Vercel's serverless environment.
What You'll Need
- A Next.js project (App Router or Pages Router) deployed or ready to deploy on Vercel.
- Node.js 18+ installed locally for testing.
- Basic familiarity with Next.js API routes or server actions.
- For the
react-pdfmethod: a React component that renders the PDF content.
Step-by-Step
Method 1: Using pdf-lib (Programmatic PDFs)
- Install pdf-lib: Run
npm install pdf-libin your project root. - Create an API route: In your
app/api/generate-pdf/route.ts(App Router) orpages/api/generate-pdf.ts(Pages Router), importPDFDocumentfrompdf-lib. - Build the PDF document: Inside the route handler, create a new PDF document with
const pdfDoc = await PDFDocument.create(). Add pages and text usingpdfDoc.addPage()andpage.drawText(). You can also embed images or draw shapes. - Serialize and return: After building, call
const pdfBytes = await pdfDoc.save(). Return the bytes as a response with the appropriate headers:Content-Type: application/pdfandContent-Disposition: attachment; filename="document.pdf". - Test locally: Run
npm run devand visithttp://localhost:3000/api/generate-pdfto ensure the PDF downloads. - Deploy to Vercel: Push your code. Vercel will automatically build and serve the API route. No additional configuration is needed because
pdf-libis pure JavaScript and works in serverless functions.
Method 2: Using @react-pdf/renderer (React Components to PDF)
- Install the library: Run
npm install @react-pdf/renderer. - Create a PDF document component: In a file like
components/MyPDF.tsx, importDocument,Page,Text,View, andStyleSheetfrom@react-pdf/renderer. Define your PDF layout using these components and styles. - Generate the PDF in an API route: In your API route, import
renderToBufferfrom@react-pdf/renderer. Render your component to a buffer withconst buffer = await renderToBuffer(. Note: JSX in a server file requires TypeScript or Babel configuration; in Next.js, you can use a) .tsxfile for the route. - Return the buffer: Set the response headers as in Method 1 and send the buffer as the body.
- Handle dynamic data: Pass data via query parameters or request body to make the PDF dynamic. For example, fetch user data inside the route and pass it to the component.
- Deploy: Same as above – push to Vercel. The library is server-compatible and does not require Chrome.
Common Mistakes
- Using client-side only libraries: Some PDF libraries rely on browser APIs (like
window). Ensure the library you choose works in Node.js. Bothpdf-liband@react-pdf/rendererare server-safe. - Forgetting to set response headers: Without
Content-Type: application/pdf, the browser may try to render the response as text or JSON. - Using
fsto write files: Vercel's serverless functions have a read-only filesystem except for/tmp. Do not attempt to write PDFs to disk; always return them as a response. - Passing non-serializable data to
renderToBuffer: Ensure the data you pass to the React PDF component is plain JSON, not functions or class instances. - Not handling large PDFs: If your PDF is very large (many pages), it may exceed Vercel's response size limit (4.5 MB for serverless functions). Consider splitting or compressing.
Tips
- Use streaming for large PDFs: If you need to generate a large PDF, consider using a streaming response (e.g.,
ReadableStream) to send chunks, but this is more complex. For most use cases, a simple buffer is fine. - Cache PDFs when possible: If the PDF content is static for a given user, store the generated PDF in a CDN or object storage and serve it from there to reduce serverless invocations.
- Use
pdf-libfor simple tables and text: It's lightweight and fast. For complex layouts with images and styling,@react-pdf/rendereris more convenient. - Test with different data sizes: Vercel has a 10-second execution limit for hobby plans. Ensure your PDF generation completes within that time. If not, optimize your code or consider a dedicated server.
- Set a custom filename: Use
Content-Dispositionheader withfilename*to support non-ASCII filenames.
Troubleshooting
- PDF downloads but is corrupted: Check that you're returning the correct buffer/bytes. For
pdf-lib, ensure you callawait pdfDoc.save(). For@react-pdf/renderer, ensure you userenderToBufferand notrenderToStream(which returns a Node stream, not a buffer). - 404 on API route: Ensure the route file is in the correct directory (
app/api/.../route.tsorpages/api/...ts). Also, check that you export a named function (e.g.,GETorPOST). - Timeout errors: If your PDF takes too long, try simplifying the content, reducing image sizes, or using
pdf-libinstead of@react-pdf/renderer(which is slower due to React overhead). - Memory limit exceeded: Vercel has a 1024 MB memory limit. If your PDF uses large images or many pages, consider compressing images or generating the PDF in chunks.
- Font issues:
@react-pdf/rendererincludes standard fonts, but custom fonts need to be embedded. UseFont.registerfrom the library and ensure the font file is accessible (e.g., frompublic/or a CDN).
Frequently Asked Questions
Can I use Puppeteer or Playwright on Vercel?
Technically yes, but it's not recommended because they require a headless browser binary, which increases cold start times and memory usage. Vercel's serverless functions have a 250 MB limit for the deployment, and the browser binary can exceed that. The methods above avoid this entirely.
Which library is faster: pdf-lib or @react-pdf/renderer?
pdf-lib is typically faster because it directly manipulates PDF structures. @react-pdf/renderer has the overhead of React reconciliation. For simple PDFs, use pdf-lib; for complex layouts, the convenience of @react-pdf/renderer may be worth the speed trade-off.
Can I generate a PDF from an HTML string?
Yes, but not with the libraries mentioned. You would need an HTML-to-PDF converter like html-pdf-node (which uses Puppeteer) or pdfkit with manual HTML parsing. For a pure JS solution, consider using pdfmake which accepts a JSON structure similar to HTML.
How do I add images to the PDF?
With pdf-lib, use pdfDoc.embedPng() or embedJpg() and then draw the image. With @react-pdf/renderer, use the Image component and provide a URL or base64 data. Ensure the image is accessible from the server (e.g., from a CDN or public/ folder).
Can I generate a PDF on the client side instead?
Yes, but the question is about server-side generation. Client-side generation would require downloading a library like jspdf and running in the browser, which is fine but may not be suitable for dynamic server-side data. The server-side approach is more secure for sensitive data.
Does this work on Vercel's edge runtime?
No, these libraries rely on Node.js APIs. Use the Node.js runtime (default) for your API routes. If you need edge functions, you'd have to use a different approach like a third-party PDF service.