User Agents

Web browsers and everyday web tech, explained

Generate PDFs in Next.js on Vercel Without Chrome

· 6 min read · Browsers

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

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-pdf method: a React component that renders the PDF content.

Step-by-Step

Method 1: Using pdf-lib (Programmatic PDFs)

  1. Install pdf-lib: Run npm install pdf-lib in your project root.
  2. Create an API route: In your app/api/generate-pdf/route.ts (App Router) or pages/api/generate-pdf.ts (Pages Router), import PDFDocument from pdf-lib.
  3. Build the PDF document: Inside the route handler, create a new PDF document with const pdfDoc = await PDFDocument.create(). Add pages and text using pdfDoc.addPage() and page.drawText(). You can also embed images or draw shapes.
  4. Serialize and return: After building, call const pdfBytes = await pdfDoc.save(). Return the bytes as a response with the appropriate headers: Content-Type: application/pdf and Content-Disposition: attachment; filename="document.pdf".
  5. Test locally: Run npm run dev and visit http://localhost:3000/api/generate-pdf to ensure the PDF downloads.
  6. Deploy to Vercel: Push your code. Vercel will automatically build and serve the API route. No additional configuration is needed because pdf-lib is pure JavaScript and works in serverless functions.

Method 2: Using @react-pdf/renderer (React Components to PDF)

  1. Install the library: Run npm install @react-pdf/renderer.
  2. Create a PDF document component: In a file like components/MyPDF.tsx, import Document, Page, Text, View, and StyleSheet from @react-pdf/renderer. Define your PDF layout using these components and styles.
  3. Generate the PDF in an API route: In your API route, import renderToBuffer from @react-pdf/renderer. Render your component to a buffer with const buffer = await renderToBuffer(). Note: JSX in a server file requires TypeScript or Babel configuration; in Next.js, you can use a .tsx file for the route.
  4. Return the buffer: Set the response headers as in Method 1 and send the buffer as the body.
  5. 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.
  6. 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. Both pdf-lib and @react-pdf/renderer are 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 fs to 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-lib for simple tables and text: It's lightweight and fast. For complex layouts with images and styling, @react-pdf/renderer is 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-Disposition header with filename* 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 call await pdfDoc.save(). For @react-pdf/renderer, ensure you use renderToBuffer and not renderToStream (which returns a Node stream, not a buffer).
  • 404 on API route: Ensure the route file is in the correct directory (app/api/.../route.ts or pages/api/...ts). Also, check that you export a named function (e.g., GET or POST).
  • Timeout errors: If your PDF takes too long, try simplifying the content, reducing image sizes, or using pdf-lib instead 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/renderer includes standard fonts, but custom fonts need to be embedded. Use Font.register from the library and ensure the font file is accessible (e.g., from public/ 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.