ScreenshotNeo

BlogHow-to

How to Bundle the Headless Chromium Module with AWS Lambda

Package headless Chromium for AWS Lambda with a ZIP and layer or a container image, then launch it with Puppeteer Core and @sparticuz/chromium.

By the ScreenshotNeo team30 September 202611 min read

How to Bundle the Headless Chromium Module with AWS Lambda

Direct answer: Bundle headless Chromium for Lambda either as a Node.js ZIP package plus a Lambda layer, or in a Lambda container image. Use a layer when you want to share a browser build across ZIP-deployed functions and the package fits Lambda’s ZIP limits. Use a container image when the browser and its dependencies make ZIP packaging impractical or when you want one immutable artifact. For Node.js, pair @sparticuz/chromium with puppeteer-core, match the function’s Linux runtime and CPU architecture, and use the package’s launch configuration. [AWS layer packaging, Sparticuz Chromium]

This guide walks through both deployment choices, gives runnable examples and a container recipe, and covers sizing, architecture, version pinning, runtime behavior, and common failures.

1. Choose a deployment model

A Lambda layer is a ZIP archive containing supplementary code or data. Lambda extracts it under /opt, where Node.js can load packages from the expected layer directory. You can attach up to five layers to a function, and a layer version can be shared across functions. The function itself remains a separate deployment ZIP. [AWS: Packaging layer content, AWS: Lambda layers]

With a container image, the runtime, application, Chromium, and browser dependencies are built into the image. Lambda container-image functions cannot attach layers; include all dependencies in the image. Images can be up to 10 GB uncompressed. [AWS: Container images]

Choose When it fits Trade-off
ZIP plus layer You want to reuse a browser dependency across functions, and the artifacts fit ZIP and aggregate uncompressed limits. Paths, runtime compatibility, and layer versions need deliberate management.
Container image Browser dependencies make ZIP packaging difficult, or you want one complete, immutable artifact. Layers are unavailable; build and publish the full runtime image.

Chromium is a substantial dependency, and Puppeteer’s troubleshooting documentation calls out Lambda package size as a challenge. Remove development files and unused browser assets from ZIPs. If the resulting deployment cannot fit Lambda’s ZIP constraints, use an image rather than repeatedly trimming files needed at runtime. [Puppeteer troubleshooting]

2. Match the runtime, operating system, and architecture

Build Node.js layer contents for the same Node.js version as the function and in a Linux-compatible environment. Lambda runs on Amazon Linux; a layer assembled on macOS or Windows can contain incompatible native dependencies. AWS expects Node.js packages in nodejs/node_modules or a runtime-specific path such as nodejs/node22/node_modules. Check the current supported runtime and exact path for the function you deploy. [AWS: Node.js layers]

Also check the Lambda architecture setting before choosing a Chromium artifact. Lambda commonly uses x86_64 or arm64; the browser binary must match. Sparticuz documents x64 binaries in its npm package and separate arm64 layer or remote-pack options. Do not assume an x64 package will run on an arm64 function. [Sparticuz Chromium README]

  1. In the Lambda function configuration, record its Node.js runtime and architecture.
  2. Choose the corresponding Chromium distribution and automation library.
  3. Build dependencies in a matching Linux environment; for native modules, build for the target architecture as well.
  4. Deploy and invoke the function in the target configuration. A local run on a different OS or CPU does not validate the Lambda artifact.

3. Build and use a ZIP package with a Lambda layer

There are two common ways to divide the ZIP deployment: put Chromium in a layer and the handler plus Puppeteer Core in the function ZIP, or put Chromium and its decompression support in the layer and install a compatible Puppeteer Core dependency alongside the handler. Keeping the browser in a shared layer avoids repeating that browser payload across ZIPs. Ensure your layer paths follow AWS’s Node.js conventions. [AWS Node.js layer paths]

Build a reusable layer

The following shell commands create the expected top-level nodejs/node_modules path and install the Chromium package. Run them in a Linux environment matching the target architecture and runtime assumptions, and pin the version you have selected for deployment instead of leaving it floating.

mkdir -p chromium-layer/nodejs
cd chromium-layer
npm init -y
npm install --omit=dev @sparticuz/chromium@PINNED_VERSION
cd ..
zip -r chromium-layer.zip chromium-layer/nodejs

For a real build, make the archive root contain nodejs/, not an extra enclosing chromium-layer/ directory. One reliable approach is to zip from within the layer directory:

cd chromium-layer
zip -r ../chromium-layer.zip nodejs
cd ..

Publish the ZIP as a Lambda layer compatible with the target Node.js runtime and architecture. Attach the resulting layer version ARN to the function. If the layer is architecture-specific, publish and attach the correct build for each architecture.

Install the handler’s dependencies separately in its function directory:

mkdir function
cd function
npm init -y
npm install --omit=dev puppeteer-core
cd ..

Zip the handler and its node_modules from the function directory and upload that ZIP as the function code. The layer’s modules are available under /opt/nodejs/node_modules at runtime. If your selected packaging arrangement keeps the Chromium package in the function instead, install it as a production dependency there; avoid duplicating large browser files across the layer and ZIP.

Runnable Puppeteer handler

This CommonJS handler uses the package’s documented launch helpers. It opens the supplied URL, captures a screenshot, closes the browser even if navigation or capture fails, and returns the image as base64. Replace the sample URL with an input validated by your application before accepting arbitrary user input.

const puppeteer = require('puppeteer-core');
const chromium = require('@sparticuz/chromium');

exports.handler = async (event) => {
  let browser;
  try {
    const url = event?.url || 'https://example.com';
    const parsed = new URL(url);
    if (!['http:', 'https:'].includes(parsed.protocol)) {
      throw new Error('Only http and https URLs are supported');
    }

    browser = await puppeteer.launch({
      args: chromium.args,
      defaultViewport: chromium.defaultViewport,
      executablePath: await chromium.executablePath(),
      headless: true,
    });

    const page = await browser.newPage();
    await page.goto(parsed.href, { waitUntil: 'domcontentloaded', timeout: 30000 });
    const image = await page.screenshot({ type: 'png' });
    return {
      statusCode: 200,
      headers: { 'content-type': 'image/png' },
      isBase64Encoded: true,
      body: image.toString('base64'),
    };
  } catch (error) {
    console.error('Screenshot capture failed', error);
    return { statusCode: 500, body: 'Screenshot capture failed' };
  } finally {
    if (browser) await browser.close();
  }
};

Set the handler entry point to index.handler if the file is named index.js. The handler uses domcontentloaded to avoid waiting indefinitely for pages with persistent network activity. If the target page needs client-side rendering, wait for a specific selector or an appropriate network state, with a timeout. The Chromium package documents its arguments, default viewport, and executable path helpers; use these rather than guessing a system Chromium path. [Sparticuz launch example]

4. Package Chromium in a Lambda container image

Use an AWS Lambda Node.js base image when possible so the Lambda runtime interface is already part of the image. The Dockerfile below installs production dependencies and copies an application handler. Pin the Chromium package version and build the image for the same architecture configured on the function.

FROM public.ecr.aws/lambda/nodejs:22

WORKDIR ${LAMBDA_TASK_ROOT}
COPY package.json package-lock.json ./
RUN npm ci --omit=dev
COPY index.js ./

CMD ["index.handler"]

Use this package.json in the same directory:

{
  "name": "lambda-chromium-capture",
  "version": "1.0.0",
  "type": "commonjs",
  "dependencies": {
    "@sparticuz/chromium": "PINNED_VERSION",
    "puppeteer-core": "PINNED_VERSION"
  }
}

Use the handler from the prior section as index.js. Build and push the image to Amazon ECR, then create or update the Lambda function with the image URI. For an OS-only or alternative base image, AWS requires a runtime interface client so the image can communicate with the Lambda runtime API. Follow AWS’s image requirements for the exact base image and target platform. [AWS: Create a Lambda container image]

Container images can be up to 10 GB uncompressed, which provides more room than ZIP packaging, but it is still useful to keep images focused: include only the runtime, application, Chromium assets, and required libraries. Lambda container-image functions do not take layers, so a dependency must be in the image or available through a design supported by the application. [AWS image requirements]

5. Tune page readiness, screenshots, and invocation behavior

Browser work has two distinct waits: starting Chromium, then waiting for the target page. Configure Lambda’s timeout to leave room for both plus screenshot encoding and response transfer. Set explicit navigation timeouts rather than allowing a slow or never-ending page to consume the full invocation. The sample’s 30-second navigation timeout is a code default, not a performance guarantee; choose limits appropriate to your endpoint and Lambda timeout.

  • Readiness: domcontentloaded is a practical starting point. For a known client-rendered page, wait for a meaningful selector. networkidle-style waits can stall on analytics, streaming, or long polling; use them only when suitable.
  • Viewport: Set a deliberate viewport when visual consistency matters. A wider viewport can change responsive layout and image dimensions.
  • Full page: A full-page screenshot may require more memory and image encoding time than a viewport capture, particularly on tall pages.
  • Cleanup: Close pages and the browser in a finally block. Reusing a browser across warm invocations can reduce repeated startup work, but it requires careful page cleanup, concurrency control, and stale-process handling. Start with per-invocation lifecycle management until reuse is designed and monitored.
  • Input safety: If callers control the URL, validate the scheme and destination. A browser can make network requests; restrict access to internal addresses and services according to your application’s security boundary.

No universal startup time or capture rate is implied by these packaging patterns. Measure cold and warm invocations with your own pages, architecture, memory setting, image dimensions, and network conditions before setting capacity expectations.

6. Pin versions and keep the artifacts compatible

@sparticuz/chromium follows Chromium’s release cycle rather than ordinary semantic versioning; its project warns that breaking changes can occur at patch level. It is not tied to one specific Puppeteer version, but that does not remove the need to check compatibility. Pin Chromium and Puppeteer Core (or Playwright) versions, review release notes, and deploy upgrades as a matched, tested artifact. [Sparticuz compatibility guidance]

  1. Record the Lambda runtime, architecture, Chromium package version, and automation-client version in build metadata.
  2. Build a new immutable ZIP/layer version or image tag for an upgrade.
  3. Invoke the new artifact with representative pages, including a slow page and a page with client-side rendering.
  4. Promote the new layer version or image only after checking logs, errors, memory, and duration.

7. Troubleshooting

Symptom Likely cause Fix
Could not find Chrome or executable path error The launch configuration omitted the package helper, the package is absent from the deployed artifact, or the layer path is wrong. Check that the dependency is in the function ZIP or attached layer, verify the archive root and nodejs/node_modules path, and use await chromium.executablePath().
Exec format error or Chromium exits immediately The binary architecture does not match the Lambda architecture, or the build contains incompatible native assets. Match x64/arm64 across Lambda, Chromium artifact, and build environment. Publish a matching layer or rebuild the image.
Module cannot be found in Lambda The ZIP has an extra directory level, an unsupported layer layout, or dependencies were installed only as development dependencies and pruned. Inspect the archive contents. Put layer dependencies under nodejs/node_modules or the runtime-specific path. Include required production packages in the deployed artifact.
Deployment package or layer is too large Chromium, duplicate assets, or development files exceed ZIP-oriented size limits. Remove files not needed at runtime, avoid duplicate browser copies, and move the full stack into a Lambda container image if ZIP packaging still cannot fit.
Function times out during launch or navigation Cold browser startup plus page loading exceeds the invocation budget, or the page never reaches the chosen readiness condition. Set explicit navigation and overall timeouts, use a suitable readiness selector, increase the function timeout when justified, and inspect whether the target page hangs.
Screenshot is blank or incomplete The page was captured before its content rendered, lazy content was not triggered, or a navigation error was ignored. Wait for the relevant selector, scroll or otherwise trigger lazy-loaded content when required, and log navigation status and page errors before capture.
Browser process or memory failures Large pages, full-page images, excess concurrent pages, or failure to close browser resources can exhaust available resources. Close browser/page reliably, limit concurrency, use a smaller viewport or capture, and measure memory under representative workloads.
Works locally, fails in Lambda The local OS, architecture, shared libraries, or environment differs from Lambda. Build in a Lambda-compatible Linux environment or use the Lambda base image, then validate the deployed architecture and artifact.

8. Performance, reliability, and cost considerations

Chromium capture time includes browser initialization, network access to the target, page rendering, and image encoding. Those parts vary by page and deployment configuration. Avoid making performance promises from package choice alone: measure cold starts separately from warm invocations, record capture duration and memory, and use realistic target pages. Full-page capture and high-resolution screenshots can increase memory and output size.

For reliability, keep browser shutdown in a finally block, set bounded waits, log enough context to diagnose a failed navigation, and avoid returning stack traces or sensitive page data to public callers. If reusing the browser between invocations, make that state management explicit and ensure a failed page cannot poison subsequent captures.

Lambda cost depends on the configured resources and invocation duration, along with any associated image storage, network, or logging costs. A slow external page can extend billed execution even when Chromium itself is fast. Set timeouts, restrict excessive screenshot dimensions, and track duration and memory by capture type. Consult current AWS pricing for the region and configuration you use rather than relying on a fixed per-shot estimate.

9. Or skip the browser setup

If your task is to capture public website screenshots rather than run custom browser code, ScreenshotNeo provides a website screenshot API and MCP server. It makes a GET request to return a PNG, JPEG, WebP, or PDF, with options for full-page capture, selectors, device presets, custom headers, cookies, and other browser behavior. See the API documentation for parameters and setup.

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}`);
  • Cookie banners are accepted and removed before capture; the service also removes known newsletter popups and chat widgets, with each cleanup step configurable.
  • Bot checks and CAPTCHAs, blank pages, timeouts, failed loads, and cache hits cost nothing. Responses identify the page verdict and billing status in headers.
  • An MCP server gives AI agents tools for screenshots, page information, and PDF capture.
  • The Free plan includes 1,000 shots monthly with no card. Paid plans start at $5 for 3,000 shots; every feature is on every plan.

Sign up for 1,000 free screenshots a month, with no card required.

10. Frequently asked questions

Can I use Playwright instead of Puppeteer?

Yes. Sparticuz documents use with Puppeteer or Playwright. Use the Chromium package’s executable path and launch arguments in the automation client’s launch configuration, and confirm the chosen versions and architecture work together. [Sparticuz Chromium README]

Does a Lambda container image support layers?

No. Lambda container-image functions cannot have Lambda layers attached. Add the browser and all other dependencies to the image. [AWS container image documentation]

Can I use the same layer for every Lambda architecture?

Only if its binaries support each architecture, which should not be assumed. Publish and attach artifacts that match the function’s architecture.

Why choose puppeteer-core?

puppeteer-core is the browser automation client used in this deployment pattern, while Chromium is supplied by the serverless Chromium package. Puppeteer’s Lambda guidance discusses the packaging challenge and points to Sparticuz Chromium as a workaround. [Puppeteer troubleshooting]