Running a Playwright script on AWS Lambda

On This Page Why Run Playwright on AWS Lambda?January 26, 2026 · 15 min read · Tool Comparison

Running a Playwright script on AWS Lambda

Have you always tried run a uncomplicated script on AWS Lambda, expecting it to & # 8220; just work & # 8221;?

I did.

And it didn & # 8217; t employment.

What looked like a small undertaking quickly ran into browser limitations, miss habituation, and runtime constraints.

Lambda seemed ideal for lightweight automation, but the setup was far from straightforward.

As our needs grew, it turn open that Playwright could run on Lambda-but not without the right configuration.

With the proper approach, though, Lambda can become a fast, scalable, and cost-efficient way to execute Playwright scripts on demand.

Overview

Running a Playwright script on AWS Lambda allows you to execute browser automation in a serverless environment without care infrastructure. With the right setup, Lambda can treat lightweight Playwright chore efficiently and on requirement.

Key Steps and Considerations

  • Choose between Lambda Layers or Container Images
  • Install Playwright with compatible browser dependencies
  • Configure headless mode for serverless performance
  • Write a Lambda manager that launches and closes the browser correctly
  • Optimize memory, timeout, and package size
  • Use CloudWatch logs for debugging

Best Practices

  • Prefer container-based deployment for reliable browser support
  • Keep Playwright and Chromium edition in sync
  • Use environment variable for URLs and credentials
  • Allocate sufficient retentivity to improve startup time
  • Limit script size and extraneous dependencies
  • Store yield (screenshots, data) in S3 for easygoing retrieval

This article explores how to run Playwright scripts on AWS Lambda, continue deployment options, configuration stairs, and better practices for reliable execution.

Why Run Playwright on AWS Lambda?

Running Playwright on AWS Lambda allows you to execute browser mechanisation without managing host.

For job such as generating screenshots, creating PDFs, submitting pocket-sized forms, or performing quick data extraction, Lambda provides an efficient environs that lead only when triggered. This helps reduce both cost and usable effort.

AWS Lambda is also designed to scale automatically. It can handle a few execution or a large number of parallel invocations with no additional form. This makes it a potent fit for event motor workflows or workloads with unpredictable traffic.

Playwright aligns well with this model because of its ability to run in headless mode with minimal overhead. With proper frame-up, Lambda becomes a practical option for running Playwright handwriting faithfully.

Key benefits include:

  • No servers to manage or keep
  • Automatic scaling establish on incoming requests
  • Pay only for execution time
  • Suitable for lightweight or on demand browser tasks

These advantages make AWS Lambda an appealing choice for teams looking to run Playwright scripts in a serverless and cost-efficient mode.

However, as testing needs increase and browser coverage becomes more demanding, yet Lambda can face limitations.

In scenarios where you require real device, panoptic browser support, or high-volume parallel execution, offers a scalable alternative. It provides ready-to-use real environments that can complement or extend your serverless Playwright workflows.

Challenges of Running Browser Automation on Lambda

Running Playwright on AWS Lambda is potential, but it introduces constraints that are not present in traditional server environments. Lambda & # 8217; s circumscribed runtime, storage, and dependance support can affect how reliably a headless browser starts and executes.

Common challenges include:

  • Large browser binarythat exceed Lambda & # 8217; s deployment package limit
  • Missing scheme libraryrequired by Chromium and other Playwright browsers
  • Restricted memory and CPU, which can decelerate browser initialization
  • Cold start hold, peculiarly for mapping that launch a browser instance
  • Execution time limits, which can interrupt long automation tasks
  • Network form numberwhen running inside a VPC
  • Circumscribed impermanent storage, affecting book that generate files or seizure screenshots

Understanding these challenges helps you select the right deployment method and configure Playwright to run swimmingly in a serverless environment.

Read More:

Prerequisites for Deploying Playwright on AWS Lambda

Before you deploy Playwright scripts to AWS Lambda, you need a few tools, services, and canonical configurations in place. These assure that you can package dependency right and manage your map without unexpected issues.

You should have:

  • An active AWS accountwith access to make and handle Lambda purpose
  • IAM permissionsto work with Lambda, CloudWatch Logs, S3 (if needed), and ECR for container ikon
  • Node.js and npminstall locally to develop and test your Playwright project
  • A Playwright projectset up with at least one working hand and the required dependencies in package.json
  • The AWS CLIconfigure locally to deploy and manage resources from your machine
  • Dockerinstalled, if you plan to use Lambda container picture for packaging Playwright and browser
  • A basic understanding ofAWS Lambda boundsuch as timeout, memory, and deployment sizing

Having these prerequisites ready will make it much easier to choose a deployment method and travel swimmingly into the configuration and packaging measure.

Read More:

Choosing the Right Deployment Method

Before running Playwright on AWS Lambda, it is important to decide how you will package the browser binaries and dependencies. Lambda does not include these components by default, so choosing the right deployment method determines how smoothly your handwriting will run.

There are two independent approaching:

1. AWS Lambda Layers

Lambda Layers allow you to box Playwright and its browser dependencies singly and attach them to your function. This keeps your function codification smaller and easier to cope. However, Layers hold sizing limit, and preparing them correctly can be complex due to the declamatory Chromium binary Playwright requires.

2. AWS Lambda Container Images(Recommended)

Container images provide a more flexible way to include everything Playwright needs. By using a Docker icon, you can install all required browsers and library without worry about Lambda & # 8217; s sizing restrictions. This method oftentimes results in more reliable browser launches and simpler maintenance over time.

How to Decide

  • Choose Layersif your scripts are small, and you want to reuse the same Playwright binaries across multiple office.
  • Choose Container Imagesif you desire an leisurely frame-up, best compatibility with Chromium, and fewer promotion restriction.

Selecting the correct method early helps ensure your Playwright scripts run consistently and reduces deployment complexity.

Read More:

Configuring Playwright for Serverless Execution

To run Playwright dependably on AWS Lambda, you need to adjust how it is configure. The goal is to keep the browser lightweight, the script predictable, and the execution time within Lambda limit.

The first footstep is to do sure Playwright always runs in headless mode. Lambda execute not have a showing environment, so a seeable browser is neither needed nor supported. Headless mode also reduces startup clip and resourcefulness use.

Where potential, use a single browser engine such as Chromium for Lambda. This keeps the bundle smaller and simplifies dependency direction. You can still use early browsers in local or CI environments, but Lambda benefits from a minimum and consistent setup.

It is too crucial to tune timeouts and retries for a serverless context. Lambda map can be slower to get, and network calls may occasionally guide longer than on a local machine. Increasing timeouts slightly and enabling a minor number of retries for key actions can make your scripts more stable.

Configuration details to consider include:

  • Enabling headless mode for all Lambda tally
  • Limiting the number of browsers or projects to reduce size and complexity
  • Adjusting default timeouts to match Lambda & # 8217; s performance profile
  • Using environment variables for base URLs, credentials, and former settings
  • Disabling heavy features such as video recording if not required
  • Directing logs, screenshots, or results to S3 or another extraneous entrepot service

By treating serverless as a first class environment in your Playwright configuration, you reduce surprisal and do it much easy to deploy the same scripts consistently on AWS Lambda.

Read More:

Deploying Playwright Using AWS Lambda Layers (Option 1)

AWS Lambda Layers let you package shared dependencies formerly and reuse them across multiple functions.

For Playwright, this signify order the Playwright library and its browser binary inside a bed, then attaching that layer to any Lambda function that involve to run browser automation.

Because Playwright and Chromium are relatively large, this approach works better for modest apparatus and when you stick within Lambda & # 8217; s size limit.

Workflow

To use a Lambda Layer for Playwright, you will:

For autonomous testing across multiple user personas, check out SUSATest — it explores your app like 10 different real users.

  • Create a pamphlet that will become the layer
  • Install Playwright and its browsers into that folder
  • Package the folder as a ZIP file
  • Upload it as a Lambda Layer
  • Attach the layer to your Lambda function

Creating the layer contents

On a machine that matches the Lambda runtime (for example, Amazon Linux for the Node.js runtime):

  • Create a working directory and a nodejs folder inside it. Lambda require Node.js dependencies under nodejs/node_modules in the layer.
  • Install Playwright into that folder and download the required browsers.

Example:

mkdir -p playwright-layer/nodejs
cd playwright-layer/nodejs

npm init -y
npm install playwright
npx playwright install chromium

At this point, the nodejs folder contains node_modules with Playwright and Chromium dependencies.

Packaging and uploading the layer

From the playwright-layer directory, create a ZIP file:

cd ..
zip -r playwright-layer.zip nodejs

Then, in the AWS Console:

  • Go to AWS Lambda → Layers
  • Create a new layer
  • Upload playwright-layer.zip
  • Select the appropriate runtime, for example Node.js

After the layer is create, remark its ARN. You will attach this ARN to your Lambda function.

Attaching the layer to a Lambda function

In the Lambda purpose configuration:

  • Open the Layers section
  • Choose Add a layer
  • Select the custom Playwright layer you create

When to Use This Approach

Your part can now import and use Playwright in its handler without pack it forthwith in the part code bundle.

  • Using Lambda Layers for Playwright is worthy when:
  • You want to part the like Playwright edition across several functions
  • Your bundle remains within Lambda & # 8217; s sizing limits
  • You do not ask frequent changes to browser binaries

If your Playwright setup grows larger or you involve more control over dependencies, a container based deployment is usually more flexible, which is why it is recommended as the second option.

Read More:

Deploying Playwright Using AWS Lambda Container Images (Option 2 & # 8211; Recommended)

Using AWS Lambda container images is the most reliable and flexile way to run Playwright on Lambda. This method withdraw many of the sizing and dependency limit you encounter with Lambda Layers. With a container image, you control the entire runtime surroundings, include browser binaries, system libraries, and Node.js versions.

Why this method is recommended

Using container images cater several advantages when running Playwright on AWS Lambda:

  • No size limitation because the container is not restricted by Lambda & # 8217; s ZIP package limits
  • All browser dependency included using Playwright & # 8217; s supported base picture
  • Consistent runtime environment across development, testing, and product
  • Simpler maintenance since updates to Playwright or Chromium only require rebuilding the image
  • Fewer compatibility issues equate to manually assembling layers
  • Better control over configuration, library, and system dependencies

This makes container image the most reliable and scalable option for deploying Playwright scripts on AWS Lambda.

What You Do When Creating the Container

The summons of preparing your Playwright container for AWS Lambda involves a few straightforward steps:

  • Create a Dockerfilethat uses a Playwright-compatible base image with the required browser dependencies.
  • Install your Node.js packagesinside the container, including Playwright and any project-specific modules.
  • Copy your Playwright playscript or Lambda managerinto the container so they are uncommitted at runtime.
  • Build the Docker imagetopically to ensure everything works as expected.
  • Push the icon to Amazon ECR, where Lambda can pull it during execution.
  • Configure your Lambda functionto use the container image as its runtime environment.

Creating the Dockerfile

Start by using an official Playwright bag image that include the necessary browser dependencies:

FROM mcr.microsoft.com/playwright: v1.42.0-jammy

WORKDIR /app

COPY package * .json ./
RUN npm install

COPY . .

CMD [& # 8220; index.handler & # 8221;]

This ensures that Playwright and Chromium run correctly inside Lambda & # 8217; s surround.

Building and pushing the container

Once the Dockerfile is ready, build and tag your image:

docker build -t playwright-lambda.

Authenticate to Amazon ECR, create a monument if necessitate, and push the persona:

aws ecr get-login-password & # 8211; region us-east-1
| docker login & # 8211; username AWS & # 8211; password-stdin .dkr.ecr.amazonaws.com

docker tag playwright-lambda: latest .dkr.ecr.amazonaws.com/playwright-lambda: up-to-the-minute
docker push .dkr.ecr.amazonaws.com/playwright-lambda: up-to-the-minute

Deploying the container to Lambda

In the AWS Console:

  • Create a new Lambda function
  • Choose Container iconas the deployment option
  • Select the image from your ECR repository

After deployment, configure retentivity and timeout scope based on your Playwright script & # 8217; s necessity.

When to use this method

Using container images is idealistic when you want:

  • Full control over the Playwright runtime environment
  • Consistent browser dependency without manual packaging
  • Fewer size constraint for deployment
  • An easier and more maintainable setup than Lambda Layers

This approach provides the most predictable experience for running Playwright hand on AWS Lambda and is well suited for production workload.

Read More:

Writing a Playwright Handler Function for AWS Lambda

The handler is the entry point of your Lambda role. This is where you launch Playwright, run your script, clean up resources, and return a answer or store outcome.

A full handler should:

  • Launch the browser and page
  • Perform the required actions
  • Close the browser yet if an error occurs
  • Return a clear result or status

Below is a simple example in Node.js that opens a page, takes a screenshot, and returns a canonical response. In a real project, you might store the screenshot in S3 or process data instead.

// index.js
const {chromium} = require (& # 8216; playwright & # 8217;);

exports.handler = async (event) = & gt; {
let browser;

try {
browser = await chromium.launch ({
headless: true,
});

const page = await browser.newPage ();

const url = event.url || & # 8216; https: //example.com & # 8217;;
await page.goto (url, {waitUntil: & # 8216; networkidle & # 8217;});

// Example action: take a screenshot
await page.screenshot ({route: & # 8216; /tmp/page.png & # 8217;});

return {
statusCode: 200,
body: JSON.stringify ({
content: & # 8216; Playwright script completed successfully & # 8217;,
urlVisited: url,
}),
};
} match (error) {
console.error (& # 8216; Error running Playwright in Lambda: & # 8217;, error);

return {
statusCode: 500,
body: JSON.stringify ({
message: & # 8216; Playwright hand failed & # 8217;,
error: error.message,
}),
};
} finally {
if (browser) {
await browser.close ();
}
}
};

Key point to continue in mind:

  • Always run the coach as an async function so you can await Playwright calls
  • Use a try catch last block to deal errors and ensure the browser closes
  • Keep employment inside the handler lean so it go within the Lambda timeout
  • Write any temporary files to /tmp, which is the writable directory in Lambda

This coach pattern gives you a clean and predictable way to run Playwright inside AWS Lambda.

Read More:

Optimizing Playwright Performance on AWS Lambda

Running Playwright on AWS Lambda works best when the map is tune for speed and stability. The goal is to reduce startup time, stay within resource boundary, and create each invocation as efficient as possible.

Here are key areas to concentre on:

1. Tune Memory and Timeout Settings

  • Allocate more retention to improve CPU execution and reduce browser inauguration time
  • Set the timeout eminent enough for the entire Playwright flow, but not higher than needed
  • Monitor CloudWatch logs to see where time is spent and adjust accordingly

2. Keep the Container or Package Lean

  • Remove fresh dependencies from package.json
  • Avoid bundling unnecessary assets or large libraries
  • Use a single browser engine (such as Chromium) for Lambda instead of multiple browsers

3. Optimize the Playwright Script

  • Use headless style for all Lambda performance
  • Avoid bushel delay; rely on smart waits like waitForSelector or waitUntil choice
  • Limit sailing stairs and heavy operations to what is strictly require
  • Keep each function focused on one open job rather than many unrelated activeness

4. Use the/tmpDirectory Wisely

  • Write temporary files such as screenshots or PDFs to /tmp
  • Clean up files when they are no longer needed to forefend hitting infinite limits
  • Offload final outputs to S3 or another external service if they must be keep

5. Handle Cold Starts and Concurrency

  • Prefer container images so dependencies are fully bake into the runtime
  • Use provisioned concurrence for latency-sensitive use cases
  • Design functions so they complete quickly rather than running long, complex workflows

6. Monitor and Adjust Based on Real Usage

  • Use CloudWatch metric and logs to trail continuance, memory usage, and error
  • Identify slow steps in the Playwright flow and optimize or simplify them
  • Regularly test with realistic data and concurrence degree

By applying these practices, you can get Playwright scripts run more expeditiously on AWS Lambda and cut failures stimulate by timeouts, resource limit, or unnecessary overhead.

Even with these optimizations, Lambda is still best suited for lightweight Playwright task. As exam complexity grows, you may need broader browser coverage, real devices, or higher parallel execution than Lambda can comfortably support.

In such cases, extending your setup with a cloud testing platform becomes a hardheaded succeeding step.

Scale Playwright Testing Beyond Lambda with BrowserStack Automate

When testing needs go beyond what AWS Lambda can reliably support-such as broad browser reporting, real mobile device, or high parallel execution-BrowserStack Automate become a natural propagation to your Playwright workflow.

Instead of pass browsers inside Lambda, your Playwright book can connect directly to BrowserStack & # 8217; s cloud base, where tryout are executed on real background and mobile environments. In this model, Lambda or your CI scheme simply serves as the test runner, while BrowserStack deal the execution bed.

Key capableness include:

  • Support for real browsers and devices:Run Playwright tests on a wide range of real desktop browsers and nomadic devices, ensuring coverage that closely ponder actual exploiter environments.
  • Parallel executing:Execute large numbers of Playwright trial concurrently, significantly reducing overall examination duration and better feedback swiftness.
  • Comprehensive debugging and logging:Access detailed debugging info include console output, network traffic, HAR files, screenshots, and video transcription from each test run.
  • Quick integration and SDK support:Integrate your Playwright test suite with minimum changes using the BrowserStack Playwright SDK, enable a faster and more flowing setup.
  • Local testing support:Test applications lam in secure or national environments through local connectivity features that allow Playwright exam in the cloud to approach growth or staging system safely.

By borrow BrowserStack Automate alongside your Lambda-based Playwright frame-up, you ensure your screen infrastructure remains both flexible and robust-ready for event-driven chore and large scale regression suite alike.

Talk to an Expert

Conclusion

Running Playwright on AWS Lambda offers an efficient way to accomplish lightweight mechanisation tasks without maintaining host. With the correct conformation, Lambda can launch headless browser, perform aim action, and scale on demand, get it well-suited for event-driven or occasional automation workflows.

However, Lambda has open limits around executing time, memory, and browser packaging. For broader test coverage,, or large, lead your setup with a cloud testing platform becomes all-important.

Combining Lambda & # 8217; s on-demand compute with the scalability and device coverage of BrowserStack Automate gives you a flexible approach that supports both small serverless job and larger, production-grade examination needs.

By read the strength of each program and using them where they fit best, you can build a Playwright testing workflow that is fast, true, and ready to scale as your application grows.

Useful Resources for Playwright

Tool Comparisons:

Tags

On This Page

7,000+ Views

# Ask-and-Contributeabout this topic with our Discord community.

Related Guides

Automate This With SUSA

Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts needed.

Try SUSA Free

Test Your App Autonomously

Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts.

Try SUSA Free