Puppeteer in Lambda
To use Puppeteer in a Lambda function you need:
puppeteer-core- Chromium
- In
sst dev, we’ll use a locally installed Chromium version. - In
sst deploy, we’ll use the@sparticuz/chromiumpackage. It comes with a pre-built binary for Lambda.
- In
Chromium version
Since Puppeteer has a preferred version of Chromium, we’ll need to check the version of Chrome that a given version of Puppeteer supports. Head over to the Puppeteer’s Chromium Support page and check which versions work together.
For example, Puppeteer v23.1.1 supports Chrome for Testing 127.0.6533.119. So, we’ll use the
v127 of @sparticuz/chromium.
npm install puppeteer-core@23.1.1 @sparticuz/chromium@127.0.0Install Chromium locally
To use this locally, you’ll need to install Chromium.
npx @puppeteer/browsers install chromium@latest --path /tmp/localChromiumOnce installed you’ll see the location of the Chromium binary, /tmp/localChromium/chromium/mac_arm-1350406/chrome-mac/Chromium.app/Contents/MacOS/Chromium.
Update this in your Lambda function.
// This is the path to the local Chromium binaryconst YOUR_LOCAL_CHROMIUM_PATH = "/tmp/localChromium/chromium/mac_arm-1350406/chrome-mac/Chromium.app/Contents/MacOS/Chromium";You’ll notice we are using the right binary with the SST_DEV environment variable.
const browser = await puppeteer.launch({ args: chromium.args, defaultViewport: chromium.defaultViewport, executablePath: process.env.SST_DEV ? YOUR_LOCAL_CHROMIUM_PATH : await chromium.executablePath(), headless: chromium.headless,});Deploy
We don’t need a layer to deploy this because @sparticuz/chromium comes with a pre-built
binary for Lambda.
We just need to set it in the nodejs.install.
{ nodejs: { install: ["@sparticuz/chromium"] }}And on deploy, SST will use the right binary.
We are giving our function more memory and a longer timeout since running Puppeteer can take a while.
const api = new sst.aws.Function("MyFunction", { url: true, memory: "2 GB", timeout: "15 minutes", handler: "index.handler", nodejs: { install: ["@sparticuz/chromium"], },});View the full example.