Have you ever tried running a simple Playwright script on AWS Lambda, expecting it to “just work”?
I did.
And it didn’t work.
What looked like a small task quickly ran into browser limitations, missing dependencies, and runtime constraints.
Lambda seemed ideal for lightweight automation, but the setup was far from straightforward.
As our automation needs grew, it became clear 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 managing infrastructure. With the right setup, Lambda can handle lightweight Playwright tasks efficiently and on demand.
Key Steps and Considerations
- Choose between Lambda Layers or Container Images
- Install Playwright with compatible browser dependencies
- Configure headless mode for serverless execution
- Write a Lambda handler 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 versions in sync
- Use environment variables for URLs and credentials
- Allocate sufficient memory to improve startup time
- Limit script size and external dependencies
- Store outputs (screenshots, data) in S3 for easy retrieval
This article explores how to run Playwright scripts on AWS Lambda, covering deployment options, configuration steps, and best practices for reliable execution.
Why Run Playwright on AWS Lambda?
Running Playwright on AWS Lambda allows you to execute browser automation without managing servers.
For tasks such as generating screenshots, creating PDFs, submitting small forms, or performing quick data extraction, Lambda provides an efficient environment that runs only when triggered. This helps reduce both cost and operational effort.
AWS Lambda is also designed to scale automatically. It can handle a few executions or a large number of parallel invocations with no additional configuration. This makes it a strong fit for event driven 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 setup, Lambda becomes a practical option for running Playwright scripts reliably.
Key benefits include:
- No servers to manage or maintain
- Automatic scaling based 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 manner.
However, as testing needs increase and browser coverage becomes more demanding, even Lambda can face limitations.
In scenarios where you require real devices, broader browser support, or high-volume parallel execution, BrowserStack Automate 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 possible, but it introduces constraints that are not present in traditional server environments. Lambda’s limited runtime, storage, and dependency support can affect how reliably a headless browser starts and executes.
Common challenges include:
- Large browser binaries that exceed Lambda’s deployment package limits
- Missing system libraries required by Chromium and other Playwright browsers
- Restricted memory and CPU, which can slow browser initialization
- Cold start delays, especially for functions that launch a browser instance
- Execution time limits, which can interrupt longer automation tasks
- Network configuration issues when running inside a VPC
- Limited temporary storage, affecting scripts that generate files or capture screenshots
Understanding these challenges helps you choose the right deployment method and configure Playwright to run smoothly in a serverless environment.
Prerequisites for Deploying Playwright on AWS Lambda
Before you deploy Playwright scripts to AWS Lambda, you need a few tools, services, and basic configurations in place. These ensure that you can package dependencies correctly and manage your functions without unexpected issues.
You should have:
- An active AWS account with access to create and manage Lambda functions
- IAM permissions to work with Lambda, CloudWatch Logs, S3 (if needed), and ECR for container images
- Node.js and npm installed locally to develop and test your Playwright project
- A Playwright project set up with at least one working script and the required dependencies in package.json
- The AWS CLI configured locally to deploy and manage resources from your machine
- Docker installed, if you plan to use Lambda container images for packaging Playwright and browsers
- A basic understanding of AWS Lambda limits such as timeout, memory, and deployment size
Having these prerequisites ready will make it much easier to choose a deployment method and move smoothly into the configuration and packaging steps.
Read More: How to uninstall Playwright
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 scripts will run.
There are two main approaches:
1. AWS Lambda Layers
Lambda Layers allow you to package Playwright and its browser dependencies separately and attach them to your function. This keeps your function code smaller and easier to manage. However, Layers have size limits, and preparing them correctly can be complex due to the large Chromium binaries Playwright requires.
2. AWS Lambda Container Images (Recommended)
Container images provide a more flexible way to include everything Playwright needs. By using a Docker image, you can install all required browsers and libraries without worrying about Lambda’s size restrictions. This method often results in more reliable browser launches and simpler maintenance over time.
How to Decide
- Choose Layers if your scripts are small, and you want to reuse the same Playwright binaries across multiple functions.
- Choose Container Images if you want an easier setup, better compatibility with Chromium, and fewer packaging limitations.
Selecting the right method early helps ensure your Playwright scripts run consistently and reduces deployment complexity.
Read More: How to download a file using Playwright
Configuring Playwright for Serverless Execution
To run Playwright reliably on AWS Lambda, you need to adjust how it is configured. The goal is to keep the browser lightweight, the scripts predictable, and the execution time within Lambda limits.
The first step is to make sure Playwright always runs in headless mode. Lambda does not have a display environment, so a visible browser is neither needed nor supported. Headless mode also reduces startup time and resource usage.
Where possible, use a single browser engine such as Chromium for Lambda. This keeps the bundle smaller and simplifies dependency management. You can still use other browsers in local or CI environments, but Lambda benefits from a minimal and consistent setup.
It is also important to tune timeouts and retries for a serverless context. Lambda functions can be slower to start, and network calls may occasionally take longer than on a local machine. Increasing timeouts slightly and enabling a small number of retries for key actions can make your scripts more stable.
Configuration details to consider include:
- Enabling headless mode for all Lambda runs
- Limiting the number of browsers or projects to reduce size and complexity
- Adjusting default timeouts to match Lambda’s performance profile
- Using environment variables for base URLs, credentials, and other settings
- Disabling heavy features such as video recording if not required
- Directing logs, screenshots, or results to S3 or another external storage service
By treating serverless as a first class environment in your Playwright configuration, you reduce surprises and make it much easier to deploy the same scripts consistently on AWS Lambda.
Deploying Playwright Using AWS Lambda Layers (Option 1)
AWS Lambda Layers let you package shared dependencies once and reuse them across multiple functions.
For Playwright, this means placing the Playwright library and its browser binaries inside a layer, then attaching that layer to any Lambda function that needs to run browser automation.
Because Playwright and Chromium are relatively large, this approach works best for smaller setups and when you stay within Lambda’s size limits.
Workflow
To use a Lambda Layer for Playwright, you will:
- Create a folder 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 expects 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/nodejsnpm 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 created, note its ARN. You will attach this ARN to your Lambda function.
Attaching the layer to a Lambda function
In the Lambda function configuration:
- Open the Layers section
- Choose Add a layer
- Select the custom Playwright layer you created
When to Use This Approach
Your function can now import and use Playwright in its handler without bundling it directly in the function code package.
- Using Lambda Layers for Playwright is suitable when:
- You want to share the same Playwright version across several functions
- Your bundle remains within Lambda’s size limits
- You do not need frequent changes to browser binaries
If your Playwright setup grows larger or you need more control over dependencies, a container based deployment is usually more flexible, which is why it is recommended as the second option.
Read More: Playwright with .Net: A 2026 guide
Deploying Playwright Using AWS Lambda Container Images (Option 2 – Recommended)
Using AWS Lambda container images is the most reliable and flexible way to run Playwright on Lambda. This method removes many of the size and dependency limitations you encounter with Lambda Layers. With a container image, you control the entire runtime environment, including browser binaries, system libraries, and Node.js versions.
Why this method is recommended
Using container images provides several advantages when running Playwright on AWS Lambda:
- No size limitations because the container is not restricted by Lambda’s ZIP package limits
- All browser dependencies included using Playwright’s supported base images
- Consistent runtime environment across development, testing, and production
- Simpler maintenance since updates to Playwright or Chromium only require rebuilding the image
- Fewer compatibility issues compared to manually assembling layers
- Better control over configuration, libraries, and system dependencies
This makes container images the most reliable and scalable option for deploying Playwright scripts on AWS Lambda.
What You Do When Creating the Container
The process of preparing your Playwright container for AWS Lambda involves a few straightforward steps:
- Create a Dockerfile that uses a Playwright-compatible base image with the required browser dependencies.
- Install your Node.js packages inside the container, including Playwright and any project-specific modules.
- Copy your Playwright scripts or Lambda handler into the container so they are available at runtime.
- Build the Docker image locally to ensure everything works as expected.
- Push the image to Amazon ECR, where Lambda can pull it during execution.
- Configure your Lambda function to use the container image as its runtime environment.
Creating the Dockerfile
Start by using an official Playwright base image that includes the necessary browser dependencies:
FROM mcr.microsoft.com/playwright:v1.42.0-jammyWORKDIR /app
COPY package*.json ./
RUN npm installCOPY . .
CMD [ “index.handler” ]
This ensures that Playwright and Chromium run correctly inside Lambda’s environment.
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 repository if needed, and push the image:
aws ecr get-login-password –region us-east-1
| docker login –username AWS –password-stdin .dkr.ecr.amazonaws.comdocker tag playwright-lambda:latest .dkr.ecr.amazonaws.com/playwright-lambda:latest
docker push .dkr.ecr.amazonaws.com/playwright-lambda:latest
Deploying the container to Lambda
In the AWS Console:
- Create a new Lambda function
- Choose Container image as the deployment option
- Select the image from your ECR repository
After deployment, configure memory and timeout settings based on your Playwright script’s requirements.
When to use this method
Using container images is ideal when you want:
- Full control over the Playwright runtime environment
- Consistent browser dependencies without manual packaging
- Fewer size constraints for deployments
- An easier and more maintainable setup than Lambda Layers
This approach provides the most predictable experience for running Playwright scripts on AWS Lambda and is well suited for production workloads.
Read More: Async/Await in Playwright
Writing a Playwright Handler Function for AWS Lambda
The handler is the entry point of your Lambda function. This is where you launch Playwright, run your script, clean up resources, and return a response or store results.
A good handler should:
- Launch the browser and page
- Perform the required actions
- Close the browser even 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 basic response. In a real project, you might store the screenshot in S3 or process data instead.
// index.js
const { chromium } = require(‘playwright’);exports.handler = async (event) => {
let browser;try {
browser = await chromium.launch({
headless: true,
});const page = await browser.newPage();
const url = event.url || ‘https://example.com’;
await page.goto(url, { waitUntil: ‘networkidle’ });// Example action: take a screenshot
await page.screenshot({ path: ‘/tmp/page.png’ });return {
statusCode: 200,
body: JSON.stringify({
message: ‘Playwright script completed successfully’,
urlVisited: url,
}),
};
} catch (error) {
console.error(‘Error running Playwright in Lambda:’, error);return {
statusCode: 500,
body: JSON.stringify({
message: ‘Playwright script failed’,
error: error.message,
}),
};
} finally {
if (browser) {
await browser.close();
}
}
};
Key points to keep in mind:
- Always run the handler as an async function so you can await Playwright calls
- Use a try catch finally block to handle errors and ensure the browser closes
- Keep work inside the handler lean so it fits within the Lambda timeout
- Write any temporary files to /tmp, which is the writable directory in Lambda
This handler pattern gives you a clean and predictable way to run Playwright inside AWS Lambda.
Optimizing Playwright Performance on AWS Lambda
Running Playwright on AWS Lambda works best when the function is tuned for speed and stability. The goal is to reduce startup time, stay within resource limits, and make each invocation as efficient as possible.
Here are key areas to focus on:
1. Tune Memory and Timeout Settings
- Allocate more memory to improve CPU performance and reduce browser startup time
- Set the timeout high enough for the full 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 unused 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 mode for all Lambda executions
- Avoid fixed waits; rely on smart waits like waitForSelector or waitUntil options
- Limit navigation steps and heavy operations to what is strictly required
- Keep each function focused on one clear task rather than many unrelated actions
4. Use the /tmp Directory Wisely
- Write temporary files such as screenshots or PDFs to /tmp
- Clean up files when they are no longer needed to avoid hitting space limits
- Offload final outputs to S3 or another external service if they must be retained
5. Handle Cold Starts and Concurrency
- Prefer container images so dependencies are fully baked into the runtime
- Use provisioned concurrency 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 metrics and logs to track duration, memory usage, and errors
- Identify slow steps in the Playwright flow and optimize or simplify them
- Regularly test with realistic data and concurrency levels
By applying these practices, you can make Playwright scripts run more efficiently on AWS Lambda and reduce failures caused by timeouts, resource limits, or unnecessary overhead.
Even with these optimizations, Lambda is still best suited for lightweight Playwright tasks. As test 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 practical next step.
Scale Playwright Testing Beyond Lambda with BrowserStack Automate
When testing needs go beyond what AWS Lambda can reliably support-such as broader browser coverage, real mobile devices, or higher parallel execution-BrowserStack Automate becomes a natural extension to your Playwright workflow.
Instead of running browsers inside Lambda, your Playwright scripts can connect directly to BrowserStack’s cloud infrastructure, where tests are executed on real desktop and mobile environments. In this model, Lambda or your CI system simply serves as the test runner, while BrowserStack handles the execution layer.
Key capabilities include:
- Support for real browsers and devices: Run Playwright tests on a wide range of real desktop browsers and mobile devices, ensuring coverage that closely reflects actual user environments.
- Parallel execution: Execute large numbers of Playwright tests concurrently, significantly reducing overall test duration and improving feedback speed.
- Comprehensive debugging and logging: Access detailed debugging information including console output, network traffic, HAR files, screenshots, and video recordings from each test run.
- Quick integration and SDK support: Integrate your Playwright test suite with minimal changes using the BrowserStack Playwright SDK, enabling a faster and more streamlined setup.
- Local testing support: Test applications running in secure or internal environments through local connectivity features that allow Playwright tests in the cloud to access development or staging systems safely.
By adopting BrowserStack Automate alongside your Lambda-based Playwright setup, you ensure your testing infrastructure remains both flexible and robust-ready for event-driven jobs and large scale regression suites alike.
Conclusion
Running Playwright on AWS Lambda offers an efficient way to execute lightweight automation tasks without maintaining servers. With the right configuration, Lambda can launch headless browsers, perform targeted actions, and scale on demand, making it well-suited for event-driven or occasional automation workflows.
However, Lambda has clear limits around execution time, memory, and browser packaging. For broader test coverage, real devices, or larger test suites, extending your setup with a cloud testing platform becomes essential.
Combining Lambda’s on-demand compute with the scalability and device coverage of BrowserStack Automate gives you a flexible approach that supports both small serverless tasks and larger, production-grade testing needs.
By understanding the strengths of each platform and using them where they fit best, you can build a Playwright testing workflow that is fast, reliable, and ready to scale as your application grows.
Useful Resources for Playwright
- Playwright Automation Framework
- Playwright Java Tutorial
- Playwright Python tutorial
- Playwright Debugging
- End to End Testing using Playwright
- Visual Regression Testing Using Playwright
- Mastering End-to-End Testing with Playwright and Docker
- Page Object Model in Playwright
- Scroll to Element in Playwright
- Understanding Playwright Assertions
- Cross Browser Testing using Playwright
- Playwright Selectors
- Playwright and Cucumber Automation
Tool Comparisons:




