Guides · playwright pdf timeout vercel lambda
Playwright PDF Timeout on Vercel or Lambda: Fixes
If you searched for Playwright PDF timeout on Vercel or Lambda, your logs probably show one of these:
page.setContent: Timeout 30000ms exceeded.while waiting fornetworkidlebrowserType.launch: Executable doesn't exist at …/ms-playwright/chromium-…/chrome-linux/chromeTask timed out after 3.00 secondson AWS LambdaFUNCTION_INVOCATION_TIMEOUTon Vercel- A deploy that fails because the function bundle is over the 250 MB unzipped limit
This is the Playwright companion to our Puppeteer serverless HTML to PDF timeout fix. The root cause is the same — a browser per invocation — but the errors and the quick fixes are Playwright-specific.
Why it times out
page.pdf() only works in Chromium, so a serverless Playwright PDF function has to:
- Ship a Chromium build that runs on the platform (the full
playwrightbrowser download does not fit, so people useplaywright-core+@sparticuz/chromium) - Decompress and launch it on cold start
- Load your HTML and wait for fonts, images, and scripts
Steps 1–2 are paid on every cold start. Step 3 is where waitUntil: "networkidle" quietly adds seconds, because it waits for 500ms of network silence. And Lambda’s default timeout is just 3 seconds unless you raise it.
Quick fixes if you keep Playwright
These genuinely help, in order of payoff:
1. Use a serverless Chromium build with playwright-core.
import chromium from "@sparticuz/chromium";
import { chromium as playwright } from "playwright-core";
let browser; // reused across warm invocations
async function getBrowser() {
if (!browser) {
browser = await playwright.launch({
args: chromium.args,
executablePath: await chromium.executablePath(),
headless: true,
});
}
return browser;
}Match the @sparticuz/chromium version to the Chromium revision your playwright-core version expects, or launches fail in confusing ways.
2. Reuse the browser, not just the code. Keep browser in module scope (as above) and open a new context/page per request. Warm invocations then skip the launch entirely.
3. Stop waiting for networkidle.
const page = await (await getBrowser()).newPage();
await page.setContent(html, { waitUntil: "load", timeout: 15000 });
const pdf = await page.pdf({ format: "A4", printBackground: true });
await page.close();Inline critical CSS, embed small images as data URIs, and self-host fonts so load is enough.
4. Raise the platform limits. On Lambda, increase the function timeout and memory (more memory also means more CPU). On Vercel, set maxDuration for the route within what your plan allows.
5. Move it off the request. Put the PDF job on a queue (SQS, a background function) so the user-facing request never waits for Chromium.
If those get you under the limit and you need Chrome-exact output, you are done. If you are still fighting cold starts, the alternative is to not run a browser at all.
The browser-free option
For documents built from data — invoices, receipts, statements, certificates — you usually do not need Chrome. DocuHook takes data + an HTML template and returns application/pdf, rendered with Dompdf on its side. Your function sends one fetch:
// Vercel route handler or Lambda — no playwright-core, no @sparticuz/chromium
export async function POST(req) {
const order = await req.json();
const rows = order.items
.map((_, i) => `<tr><td>{{items.${i}.name}}</td><td>{{items.${i}.qty}}</td><td>{{items.${i}.total}}</td></tr>`)
.join("");
const res = await fetch("https://docuhook.com/api/v1/render", {
method: "POST",
headers: {
Authorization: `Bearer ${process.env.DOCUHOOK_API_KEY}`,
"Content-Type": "application/json",
Accept: "application/pdf",
},
body: JSON.stringify({
mode: "sync",
data: order,
html: INVOICE_HTML.replace("<!--ROWS-->", rows),
filename: "invoice.pdf",
}),
});
if (!res.ok) return new Response(await res.text(), { status: res.status });
return new Response(await res.arrayBuffer(), {
headers: { "Content-Type": "application/pdf" },
});
}Templates have no loop syntax, which is why the rows are expanded with indexed tokens before the call; DocuHook still fills and HTML-escapes every value. Your bundle drops Chromium entirely, so the size limit and the cold-start launch both go away.
For webhook-triggered documents, send "mode": "async" to get a 202 with a job_id and result_url immediately, then download the PDF from result_url with Accept: application/pdf in a later step. See Stripe webhook to PDF invoice for the full pattern.
Dompdf vs Chrome: the honest caveat
Dompdf is not a browser. Tables, borders, backgrounds, images, and fonts are fine; flexbox, grid, and JavaScript-rendered content are not supported. If your PDF is a screenshot of a React dashboard or uses CSS that only Chrome handles, keep Playwright and apply the fixes above.
There is a middle path too: ask DocuHook for the merged HTML only ("format": "html") and print it in one warm, long-running Chromium worker instead of in every serverless invocation.
Decision checklist
- Document built from JSON with table-based layout → browser-free API call; delete Chromium from the function
- Chrome-exact rendering required, low volume →
playwright-core+@sparticuz/chromium, reused browser,waitUntil: "load", higher timeout - Chrome-exact, high volume or bursts → queue + one warm Chromium worker; serverless only enqueues
- Triggered by a webhook → always async; acknowledge first, render later
Related guides
- Puppeteer serverless HTML to PDF timeout fix
- How to generate PDF from HTML in Next.js
- Python HTML to PDF without WeasyPrint or Playwright
- Shopify orders/paid webhook to PDF invoice
The 3-line fix
Replace the launch / setContent / pdf() block with:
const res = await fetch("https://docuhook.com/api/v1/render", { method: "POST", headers: { Authorization: `Bearer ${process.env.DOCUHOOK_API_KEY}`, "Content-Type": "application/json" }, body: JSON.stringify({ data: payload, html: templateHtml }) });
const pdf = Buffer.from(await res.arrayBuffer()); // application/pdf
// no Chromium in the bundle, no cold-start launchTry your template in the live sandbox (no signup), read the API docs, or get an API key. The Free plan covers 100 PDFs a month (watermarked) — enough to test against your real timeouts.