User Agents

Web browsers and everyday web tech, explained

Run Puppeteer in Firebase Functions with a Deployable Browser

· 7 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

Running Puppeteer in Firebase Functions allows you to automate browser tasks—such as generating PDFs, taking screenshots, or scraping dynamic content—directly within a serverless environment. Because Firebase Functions (powered by Google Cloud Functions) run in a restricted environment, you cannot simply install a browser on the host machine. To achieve this, you must use puppeteer along with puppeteer-core and a compatible Chromium binary, or leverage the built-in environment capabilities of the Node.js 18+ runtimes which provide better support for the necessary system dependencies required to launch a headless browser.

What You'll Need

  • A Firebase project with the Blaze (pay-as-you-go) plan, as the free Spark plan does not allow outbound networking to non-Google services.
  • Node.js installed locally (version 18 or higher is strongly recommended).
  • Firebase CLI installed and initialized in your project directory.
  • A basic understanding of asynchronous JavaScript (async/await).

Step-by-Step

  1. Initialize your Firebase Functions environment: If you haven't already, run firebase init functions in your terminal. Select JavaScript or TypeScript. Ensure you are using a modern Node.js runtime. In your functions/package.json, ensure the engines field is set to "node": "18" or higher. This is critical because newer runtimes include the system libraries (like libnss3 and libatk) that Chromium requires to boot.
  2. Install the necessary dependencies: Navigate to your functions folder and install puppeteer. While puppeteer-core is smaller, installing the full puppeteer package simplifies the process by attempting to download a compatible version of Chromium during the install phase. Run npm install puppeteer. If you are deploying to a very memory-constrained environment, you might use puppeteer-core and point to a remote browser, but for most deployable browser needs, the standard package is the starting point.
  3. Configure the Browser Launch Arguments: You cannot launch Puppeteer with default settings in a serverless environment. You must use the --no-sandbox and --disable-setuid-sandbox flags. Google Cloud Functions run as a privileged user in a container, and the Chrome sandbox requires a user namespace that is often unavailable or restricted in these environments. Without these flags, the browser will fail to launch with a "sandbox" error.
  4. Write the Function Logic: Create an HTTPS trigger. Inside the handler, wrap your Puppeteer logic in a try...catch...finally block. It is imperative to call await browser.close() in the finally block. If you fail to close the browser, the function instance will keep the process alive, leading to memory leaks and causing subsequent function calls to fail or timeout because the available RAM is exhausted by zombie browser processes.
  5. Adjust Memory Allocation: Puppeteer is resource-heavy. The default 256MB or 512MB allocation for Firebase Functions is almost always insufficient for a headless browser. You must increase the memory to at least 2GB. In your function definition, use the runWith configuration: exports.myPuppeteerFunction = functions.runWith({ memory: '2GB', timeoutSeconds: 300 }).https.onRequest(...). If you are rendering complex pages or heavy PDFs, 4GB may be necessary.
  6. Handle the Deployment: Run firebase deploy --only functions. During deployment, Firebase uploads your node_modules. Because Puppeteer downloads Chromium into the node_modules folder, the deployment package can become quite large. Ensure your internet connection is stable and that you aren't exceeding the maximum deployment size for Cloud Functions.
  7. Test the Endpoint: Trigger your function via the provided URL. Check the Firebase Console logs to ensure the browser launched correctly and that no "missing shared library" errors appear. If the function times out, increase the timeoutSeconds in the runWith configuration.

Common Mistakes

One of the most frequent errors is forgetting to set the --no-sandbox flag. Developers often test their code locally on macOS or Windows where the sandbox works perfectly, only to find the function crashing immediately upon deployment to the Linux-based Firebase environment. Another common pitfall is using the Spark plan. Since Puppeteer often needs to navigate to external websites to render content, the lack of outbound networking on the free tier will result in connection timeouts that look like browser crashes but are actually network restrictions.

Memory mismanagement is also prevalent. Many developers attempt to run Puppeteer with 512MB of RAM to save costs. Chromium is a memory-hungry application; when it hits the memory limit, the function doesn't always throw a clean error. Instead, it often crashes silently or hangs, leading to "Deadline Exceeded" errors in the logs. Always start with 2GB and scale down only after verifying stability.

Lastly, neglecting the browser.close() command is a critical mistake. In a local environment, a forgotten browser instance just sits in the background. In a serverless environment, where instances are reused across multiple requests (warm starts), failing to close the browser means each new request spawns a new Chromium process while the old ones remain in memory. This quickly consumes all available RAM, causing the function to crash after a few successful runs.

Tips

To improve performance, avoid launching a new browser instance for every single request if your volume is high. While serverless is designed to be stateless, you can define the browser variable outside the function handler scope. This allows a "warm" function instance to potentially reuse a browser connection, although this requires complex logic to check if the browser is still responsive and to handle crashes. For most users, launching and closing within the handler is safer and more predictable.

Use page.setRequestInterception(true) to block unnecessary resources. By blocking images, CSS, and fonts using a request interceptor, you can significantly reduce the memory footprint and speed up the page load time. This is especially useful if you only need to scrape text or generate a basic PDF. Disabling image and stylesheet requests can often cut the execution time in half.

If you find that the deployment package is too large or the installation is unstable, consider using a "browserless" service. These are external APIs that host the Chromium instance for you. You simply connect to them using puppeteer.connect({ browserWSEndpoint: 'wss://...' }). This removes the need to install the browser in your Firebase function entirely, reducing your memory requirement from 2GB to 256MB and speeding up your deployment times significantly.

Troubleshooting

If you encounter the error Error: Failed to launch the browser process!, the first step is to check your Node.js version. Ensure you are on Node 18 or 20. If you are on an older version, the underlying OS image lacks the necessary shared libraries (like libatk-1.0.so.0). Updating the runtime in package.json and redeploying usually solves this. If the error persists, verify that you have included --no-sandbox in your launch arguments.

When facing Deadline Exceeded or Timeout errors, check the logs to see if the browser is hanging on a specific page load. You can add await page.goto(url, { waitUntil: 'networkidle2', timeout: 30000 }) to ensure the function doesn't wait indefinitely for a slow third-party asset. If the page is simply heavy, increase the function's timeoutSeconds to 540 (the maximum for some configurations).

If you see Out of Memory errors in the Google Cloud Console, increase the memory allocation in runWith. If you are already at 4GB and still crashing, it is a sign that you are either leaking browser instances (check your finally block) or the page you are rendering is too massive for a single instance. In the latter case, consider splitting the task into multiple smaller functions or moving to a dedicated VM (Compute Engine) rather than a serverless function.

Frequently Asked Questions

Does Puppeteer work on the Firebase Spark plan?

No, because the Spark plan restricts outbound networking. Since Puppeteer needs to access external websites, you must upgrade to the Blaze plan.

Why is my function taking so long to start?

This is likely a "cold start." Because the Puppeteer package and the Chromium binary are large, it takes longer for Firebase to initialize the container. Increasing memory can sometimes speed up the cold start process.

Can I use a custom version of Chrome?

Yes, by using puppeteer-core and providing the executablePath to a specific binary. However, ensuring that binary is present in the deployment image is difficult, which is why the default puppeteer package is recommended.

Is it possible to run Puppeteer in the background?

Firebase Functions are event-driven and have a maximum execution time. You cannot run a browser indefinitely. For long-running tasks, use Cloud Tasks to queue the work or move to a dedicated server.

How do I handle CAPTCHAs with Puppeteer in Firebase?

Handling CAPTCHAs is difficult in serverless environments because many services block the IP ranges used by Google Cloud. You may need to use a proxy service or a third-party CAPTCHA solving API.

Will this increase my Firebase bill significantly?

Because Puppeteer requires higher memory (2GB+), you will consume more GB-seconds than a standard function. Monitor your usage in the Google Cloud Console to avoid unexpected costs.