How to Run Puppeteer in Firebase Functions
Run Puppeteer in Firebase Functions by packaging a compatible browser, configuring the function, and validating the deployed runtime. Includes runnable code and fixes for common launch errors.

Short answer: Puppeteer needs two things in a deployed Firebase Function: its Node.js automation library and a compatible browser executable that exists in the Linux runtime. Installing the npm package alone does not prove Chrome will be present after deployment. Choose either puppeteer, which downloads a compatible Chrome during installation, or puppeteer-core with a separately managed browser such as @sparticuz/chromium. Then close the browser, await all work, and validate the exact dependency and runtime combination in Firebase.
This guide uses a JavaScript HTTPS function and includes an option using @sparticuz/chromium. Firebase’s current documentation lists Node.js 20 and 22 as supported runtimes and Node.js 18 as deprecated. There is no Firebase-specific compatibility matrix in the sources cited here for current Puppeteer and serverless Chromium releases, so treat the examples as implementation patterns to validate in your project. See Firebase’s runtime configuration guide and Puppeteer’s installation guide.
1. Initialize a Firebase Functions project
If you do not already have a Functions codebase, install the Firebase CLI, sign in, and initialize Functions from your project directory. The CLI creates the conventional functions/ directory and package manifest.
npm install -g firebase-tools
firebase login
firebase init functions
Choose JavaScript or TypeScript when prompted. The examples below use JavaScript with CommonJS imports, as commonly generated by the CLI. If your package uses ES modules, adapt the imports and ensure the package configuration matches.
2. Pick how to provide Chrome
| Approach | Browser provisioning | Use when | Trade-off |
|---|---|---|---|
puppeteer |
Downloads a compatible Chrome during installation | You want Puppeteer to manage its browser download | Install scripts must run, and the downloaded browser cache must make it into the deployed artifact |
puppeteer-core plus managed browser |
You supply a browser path or connect to a remote browser | You need explicit control of browser provisioning | You must configure the executable and launch options yourself |
puppeteer-core plus @sparticuz/chromium |
The Chromium package supplies a serverless-oriented Linux binary | You want a browser package designed for serverless environments | Pin and validate compatible versions, deployment size, and behavior in Firebase |
Puppeteer documents that puppeteer downloads Chrome, while puppeteer-core does not and requires a managed browser or remote endpoint. Configuration defaults for regular Puppeteer do not automatically apply to puppeteer-core. Package managers can also block install scripts, which prevents the browser download. Review the official Puppeteer installation guidance and configuration reference.

3. Configure the runtime and install dependencies
Set the runtime in functions/package.json, and install the Functions SDK and Puppeteer package from inside functions/. The CLI setting in firebase.json, if present, takes precedence over the package manifest runtime.
cd functions
npm install firebase-functions firebase-admin
npm install puppeteer
Use an active, supported Node.js version. For example, set this in functions/package.json:
{
"engines": { "node": "20" },
"dependencies": {
"firebase-functions": "...",
"puppeteer": "..."
}
}
The ellipses above stand for versions managed by your package manager; commit the actual versions and lock file generated for your project. Do not copy an old example’s browser and Puppeteer versions as a current compatibility promise.
4. Implement an HTTPS screenshot function
This handler accepts a URL, opens it in headless Chrome, captures a PNG, and returns the bytes. It includes basic input checks, a navigation timeout, and browser cleanup in finally, so failures do not skip the close attempt.
const { onRequest } = require("firebase-functions/v2/https");
const puppeteer = require("puppeteer");
exports.capturePage = onRequest(
{ timeoutSeconds: 120, memory: "1GiB" },
async (req, res) => {
const rawUrl = req.query.url;
if (typeof rawUrl !== "string") {
res.status(400).send("Provide a url query parameter.");
return;
}
let target;
try {
target = new URL(rawUrl);
if (!["http:", "https:"].includes(target.protocol)) {
throw new Error("Unsupported protocol");
}
} catch {
res.status(400).send("The url must be a valid HTTP or HTTPS URL.");
return;
}
let browser;
try {
browser = await puppeteer.launch({ headless: true });
const page = await browser.newPage();
await page.setViewport({ width: 1280, height: 800, deviceScaleFactor: 1 });
await page.goto(target.href, {
waitUntil: "networkidle2",
timeout: 60000
});
const image = await page.screenshot({ type: "png", fullPage: true });
res.set("Content-Type", "image/png");
res.status(200).send(image);
} catch (error) {
console.error("capturePage failed", error);
if (!res.headersSent) res.status(500).send("Could not capture the page.");
} finally {
if (browser) await browser.close().catch((error) => {
console.error("Browser close failed", error);
});
}
}
);
The puppeteer launch above relies on Puppeteer finding the Chrome version it manages. That depends on its browser installation and deployment packaging being correct. If you deploy successfully but receive a missing Chrome error, verify the install step and browser cache before changing function memory or timeout.
5. Alternative: package serverless Chromium explicitly
When managing the binary yourself, use puppeteer-core and pass an explicit executable path and Chromium arguments. Install both as production dependencies when the deployed function needs them:
cd functions
npm install puppeteer-core @sparticuz/chromium
Replace the imports and launch portion in the handler with the following. Keep the rest of the request validation, navigation, response, and cleanup logic.
const puppeteer = require("puppeteer-core");
const chromium = require("@sparticuz/chromium");
// Inside the HTTPS handler:
browser = await puppeteer.launch({
args: chromium.args,
defaultViewport: { width: 1280, height: 800, deviceScaleFactor: 1 },
executablePath: await chromium.executablePath(),
headless: true
});
Check the package’s current compatibility guidance before selecting versions. Its README explains version matching and shows serverless launch options, and notes the binary can exceed 50 MB. Its documented out-of-the-box runtime support names AWS Lambda; that is not Firebase-specific certification. Pin versions in the lock file and test the exact deployment target. See the project README.
6. Tune capture behavior for the actual page
Page loading is the largest source of unpredictable duration. networkidle2 can work for ordinary pages, but analytics, streaming connections, long polling, and ads may keep network activity open. Choose a readiness condition that matches the content you need:
- Use
domcontentloadedif the initial DOM is enough and you will wait for a specific selector afterward. - Use
loadwhen load-event resources matter. - Use
networkidle2for pages that settle after a short burst of requests, and retain a finite timeout. - For a single important component, wait for that selector rather than waiting indefinitely for the entire page to become idle.
Other practical options include viewport dimensions and device scale factor via page.setViewport; full page capture via fullPage: true; and an element screenshot through page.locator(".selector").screenshot() in Puppeteer versions that provide Locator APIs. For very long pages, full-page images can use substantial memory. Capture an element or a viewport when a complete page image is unnecessary.
Set navigation and function timeouts deliberately. Firebase documents maximum timeouts of 3,600 seconds for HTTP and callable functions, 1,800 seconds for scheduled and task queue functions, and 540 seconds for other event-driven functions. Those are ceilings, not sensible defaults for a screenshot endpoint. Configure memory based on measured pages: browser startup, large images, multiple tabs, and full-page screenshots all affect peak use. Firebase exposes function memory and timeout as runtime options in its management documentation.
7. Test locally, then deploy
- Run
npm installfromfunctions/and confirm the package manager did not skip Puppeteer’s browser install script. - Start the Firebase Emulator Suite and invoke the function with a small, public test page. The emulator helps validate handler behavior, but the deployed Linux runtime remains the decisive browser check.
- Deploy Functions using the Firebase CLI. The standard command is:
firebase deploy --only functions
Firebase’s getting started guide covers CLI initialization and deployment. Check project billing before deploying: Firebase’s current guidance requires the Blaze pay-as-you-go plan for Cloud Functions deployments. Review current Firebase pricing and project billing settings before running browser workloads.
8. Troubleshooting
| Error or symptom | Likely cause | Fix |
|---|---|---|
Could not find Chrome |
Puppeteer’s install script was blocked, or its downloaded browser cache is absent from deployment | Allow the install script or install browsers explicitly with Puppeteer’s documented browser install command; confirm deployment includes the cache. For puppeteer-core, provide a real executablePath. |
Failed to launch or executable not found |
Incorrect binary path, incompatible binary, or wrong OS artifact | Log/check the resolved path, use a Linux-compatible browser, align package versions, and test in the Firebase runtime. |
| Local works, deployed function fails | Local Chrome differs from the deployed artifact or Linux environment | Do not rely on a developer machine’s browser path. Package the browser or use a serverless binary, then run an integration check against the deployed function. |
| Function times out during navigation | Slow target, never-idle network requests, or overly strict readiness condition | Set an explicit navigation timeout, wait for a relevant selector or a less strict load condition, and bound the overall function timeout. |
| Out-of-memory or process termination | Large page, full-page screenshot, multiple concurrent browsers, or insufficient allocation | Measure memory for representative pages, reduce image dimensions or full-page work, avoid unnecessary parallel tabs, and increase function allocation based on observed peak use. |
| Deployment package too large | Bundled browser artifact exceeds practical deployment packaging constraints | Inspect the package contents and the vendor’s current size limits. Sparticuz documents a minimal package option with separately hosted Chromium data; evaluate that operational trade-off before using it. |
| Function returns before capture finishes | Unawaited asynchronous work | Await browser launch, navigation, screenshot, and cleanup. Firebase may cut off unfinished work when the invocation ends. |
| Temporary storage accumulates | Files written to temporary storage are not removed between warm invocations | Use unique temporary names, remove generated files when done, and close the browser in finally. Firebase notes temporary files can persist between invocations and consume memory. |
9. Performance, reliability, and cost
A browser process has meaningful startup and memory overhead. Reusing a browser across invocations may appear to reduce startup time, but it adds lifecycle and isolation concerns; a crashed process or leftover page state can affect later work. Start with a browser per request and close it reliably. If you later optimize reuse, handle browser disconnections, page isolation, and cleanup explicitly, and validate concurrent requests under the selected function generation and settings.

Keep requests bounded. Validate the URL scheme, restrict which hosts your endpoint may visit when inputs are untrusted, and avoid returning sensitive browser errors to callers. An unrestricted screenshot endpoint can be abused to make requests to internal or sensitive network targets. Set limits on input size and capture duration, and consider authentication or an allowlist for your endpoint.
Function cost depends on the Firebase plan, allocated resources, execution duration, and workload; do not estimate it from timeout ceilings. Browser workloads should be measured with representative pages and concurrency. Review Firebase’s current pricing before production deployment. Also include bandwidth and storage costs if your function stores images rather than returning them directly.
Or skip the browser setup
If your goal is simply to capture a website, ScreenshotNeo provides a website screenshot API and MCP server. One GET request can return a PNG, JPEG, WebP, or PDF. See the ScreenshotNeo API documentation for request options.
curl -G "https://api.screenshotneo.com/v1/shot" \
-d access_key=YOUR_API_KEY \
--data-urlencode url=https://stripe.com \
-o shot.webp
import requests
r = requests.get(
"https://api.screenshotneo.com/v1/shot",
params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"},
timeout=90,
)
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({
access_key: 'YOUR_API_KEY',
url: 'https://stripe.com'
});
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
ScreenshotNeo removes cookie banners, newsletter popups, and chat widgets before the shot. Bot checks, blank pages, and failed loads are never billed. Its MCP server lets AI agents take screenshots. The free plan includes 1,000 screenshots a month with no card; paid plans start at $5 for 3,000. Sign up free for ScreenshotNeo.
FAQ
Does installing Puppeteer install Chrome?
The puppeteer package downloads a compatible browser when its installation script runs. puppeteer-core does not. Verify the browser artifact is available in the deployed function.
Can I use my laptop’s Chrome path in Firebase?
No. The deployed function runs in a Linux environment and does not share your laptop’s filesystem. Package or otherwise provide a compatible browser executable.
Is @sparticuz/chromium officially certified for Firebase?
The cited project documentation describes serverless usage and AWS Lambda support, but does not establish a Firebase-specific tested compatibility matrix. Validate your chosen versions in Firebase.
What memory setting should I use?
There is no universal value for all pages. Start with a representative workload, measure memory use, and adjust for your page sizes, screenshot dimensions, and concurrency.
Can I run Puppeteer from a background or scheduled function?
The browser code can run in different function types, but each type has its own maximum duration. Configure a realistic timeout for the task and ensure the event handler awaits the full browser operation.


