AWS Lambda Screenshot API Integration

Take screenshots in AWS Lambda without Chromium layers. Working Node.js and Python examples with S3 storage, SQS queues, and EventBridge scheduling.

Vitalii Holben Updated

Getting screenshots out of Lambda without a screenshot API means packaging Chromium as a Lambda layer. That layer sits at 50–100 MB compressed, pushes the function past inline code size limits, and adds 2–5 seconds to cold starts. On ARM (Graviton2) the binaries sometimes refuse to run at all. ScreenshotRun replaces that entire layer with one HTTP call — the function stays small, cold starts stay fast, and the same code runs on x86 and ARM without changes.

Your function sends a request to the capture endpoint, gets a PNG or PDF back, and stores it wherever you need — S3, DynamoDB, an SQS queue for downstream processing.

First Screenshot in a Lambda Function (Node.js)

Lambda's Node.js runtime includes the https module, so you can make the API call without any additional dependencies. For production use, most teams prefer axios or native fetch (available from Node.js 18+):

export const handler = async (event) => {
  const url = event.url || event.queryStringParameters?.url;

  if (!url) {
    return { statusCode: 400, body: JSON.stringify({ error: "url required" }) };
  }

  const params = new URLSearchParams({
    url,
    format: "png",
    width: "1280",
    height: "720",
    full_page: "false",
    block_ads: "true",
  });

  const response = await fetch(
    `https://api.screenshotrun.com/v1/screenshots/capture?${params}`,
    {
      headers: { Authorization: `Bearer ${process.env.SCREENSHOTRUN_API_KEY}` },
      signal: AbortSignal.timeout(55000), // stay under Lambda timeout
    }
  );

  if (!response.ok) {
    return { statusCode: 500, body: JSON.stringify({ error: "Screenshot failed" }) };
  }

  const buffer = Buffer.from(await response.arrayBuffer());

  return {
    statusCode: 200,
    headers: { "Content-Type": "image/png" },
    body: buffer.toString("base64"),
    isBase64Encoded: true,
  };
};

When Lambda is behind API Gateway, returning isBase64Encoded: true with a base64 body tells the gateway to decode the binary before sending it to the client. The browser receives a raw PNG.

Storing Screenshots in S3

Returning images directly from Lambda works for on-demand captures, but most pipelines store screenshots in S3 for persistence and downstream access. The AWS SDK v3 is available in Lambda's Node.js runtime without bundling:

import { S3Client, PutObjectCommand } from "@aws-sdk/client-s3";

const s3 = new S3Client({ region: process.env.AWS_REGION });

export const handler = async (event) => {
  const { url, key } = event;

  const params = new URLSearchParams({
    url,
    format: "png",
    width: "1280",
    full_page: "true",
    block_ads: "true",
  });

  const response = await fetch(
    `https://api.screenshotrun.com/v1/screenshots/capture?${params}`,
    {
      headers: { Authorization: `Bearer ${process.env.SCREENSHOTRUN_API_KEY}` },
      signal: AbortSignal.timeout(55000),
    }
  );

  if (!response.ok) throw new Error(`Screenshot failed: ${response.status}`);

  const buffer = Buffer.from(await response.arrayBuffer());
  const s3Key = key || `screenshots/${Date.now()}-${encodeURIComponent(url)}.png`;

  await s3.send(new PutObjectCommand({
    Bucket: process.env.S3_BUCKET,
    Key: s3Key,
    Body: buffer,
    ContentType: "image/png",
    Metadata: { "source-url": url, "captured-at": new Date().toISOString() },
  }));

  return { key: s3Key, size: buffer.length, url };
};

The function captures the page, writes the PNG to S3, and returns the key. Downstream functions can read from S3 using the key. Add a webhook if you want ScreenshotRun to notify your function asynchronously instead of waiting inline.

Python Lambda with boto3

Python Lambda functions have urllib3 and boto3 available without any packaging. For HTTP calls, urllib3 works fine, though most teams include requests in their deployment package for readability:

import os
import urllib3
import boto3
from datetime import datetime

http = urllib3.PoolManager()
s3 = boto3.client("s3")


def handler(event, context):
    url = event.get("url")
    if not url:
        return {"statusCode": 400, "body": "url required"}

    params = urllib3.request.urlencode({
        "url": url,
        "format": "png",
        "width": "1280",
        "full_page": "false",
        "block_ads": "true",
    })

    response = http.request(
        "GET",
        f"https://api.screenshotrun.com/v1/screenshots/capture?{params}",
        headers={"Authorization": f"Bearer {os.environ['SCREENSHOTRUN_API_KEY']}"},
        timeout=55,
    )

    if response.status != 200:
        return {"statusCode": 500, "body": "Screenshot failed"}

    key = f"screenshots/{datetime.utcnow().strftime('%Y/%m/%d')}/{int(datetime.utcnow().timestamp())}.png"

    s3.put_object(
        Bucket=os.environ["S3_BUCKET"],
        Key=key,
        Body=response.data,
        ContentType="image/png",
        Metadata={"source-url": url},
    )

    return {"statusCode": 200, "key": key, "size": len(response.data)}

Scheduled Screenshots with EventBridge

Lambda pairs naturally with EventBridge for scheduled captures — monitoring dashboards overnight, archiving competitor pages weekly, running visual regression checks before each deploy. Set up a rule in EventBridge Scheduler and pass the target URL in the event payload:

{
  "url": "https://competitor.com/pricing",
  "label": "competitor-pricing-weekly"
}

The Lambda function receives this event on the schedule, captures the screenshot, stores it in S3 with a date-stamped key, and optionally sends a notification if the image differs from last week's capture. The whole pipeline runs without a server.

Async Processing with SQS

For bulk captures — crawling a sitemap, monitoring hundreds of URLs, processing user-submitted links — SQS decouples the submission from the capture work. One Lambda function enqueues URLs, another processes them from the queue with concurrency controls:

// Queue processor — triggered by SQS
export const handler = async (event) => {
  const results = await Promise.allSettled(
    event.Records.map(async (record) => {
      const { url, jobId } = JSON.parse(record.body);

      const params = new URLSearchParams({
        url,
        format: "png",
        width: "1280",
        block_ads: "true",
      });

      const response = await fetch(
        `https://api.screenshotrun.com/v1/screenshots/capture?${params}`,
        {
          headers: { Authorization: `Bearer ${process.env.SCREENSHOTRUN_API_KEY}` },
          signal: AbortSignal.timeout(55000),
        }
      );

      if (!response.ok) throw new Error(`Failed for ${url}: ${response.status}`);

      const buffer = Buffer.from(await response.arrayBuffer());

      await s3.send(new PutObjectCommand({
        Bucket: process.env.S3_BUCKET,
        Key: `jobs/${jobId}/${encodeURIComponent(url)}.png`,
        Body: buffer,
        ContentType: "image/png",
      }));

      return { url, jobId };
    })
  );

  // SQS batch item failures — only retry the ones that failed
  const failures = results
    .map((r, i) => r.status === "rejected" ? { itemIdentifier: event.Records[i].messageId } : null)
    .filter(Boolean);

  return { batchItemFailures: failures };
};

Returning batchItemFailures tells SQS to only re-queue the URLs that actually failed. Successfully captured screenshots stay out of the retry cycle. Set the SQS batch size to match your Lambda concurrency limit to avoid throttling.

Environment Variables and IAM

Store the API key in Lambda's environment variables, not in code. In the AWS Console: Configuration → Environment variables → SCREENSHOTRUN_API_KEY. For production, use SSM Parameter Store or Secrets Manager and fetch the value at cold start:

import { SSMClient, GetParameterCommand } from "@aws-sdk/client-ssm";

const ssm = new SSMClient({ region: process.env.AWS_REGION });

// Fetch once at cold start, reuse across warm invocations
let apiKey;

async function getApiKey() {
  if (apiKey) return apiKey;
  const { Parameter } = await ssm.send(new GetParameterCommand({
    Name: "/screenshotrun/api-key",
    WithDecryption: true,
  }));
  apiKey = Parameter.Value;
  return apiKey;
}

The key fetches once per cold start and stays in memory across warm invocations. The Lambda execution role needs ssm:GetParameter permission on that specific parameter path, and nothing else.

Timeout Configuration

Set Lambda's timeout to at least 30 seconds for screenshot captures, 60 seconds if you're capturing slow pages or using delay. Keep your fetch timeout 5 seconds below the Lambda timeout so the function can handle errors gracefully rather than getting cut off mid-response:

Scenario Lambda timeout fetch timeout
Standard pages 30s 25s
Pages with delay or wait_for_selector 60s 55s
full-page captures of long pages 60s 55s
Async with webhook_url 10s 8s (just queues the job)

Written by

Vitalii Holben

Co-founder and CEO of ScreenshotRun. Full-stack developer building screenshot API tools that help developers capture, automate, and monitor web pages at scale. Based in Europe, shipping code since 201...

Screenshot API in a few clicks

Free plan includes 200 screenshots every month. No credit card required.

Sign up → copy your key → make your first call