AWS Lambda Screenshot API Integration

Capture screenshots from AWS Lambda without Chromium layers. Use API Gateway, EventBridge, S3 triggers, Step Functions with a single fetch() call.

Vitalii Holben Updated

AWS Lambda runs your code without servers to manage. But running a headless browser inside Lambda? That takes a Lambda Layer for Chromium, 2 GB of memory allocation, careful /tmp management, and a deployment package that pushes against the 250 MB limit before you write a single line of business logic. ScreenshotRun replaces all of that with one HTTPS call from your Lambda function. The rendering happens on our infrastructure. Your function stays under 1 MB, runs in 128 MB of memory, deploys in seconds.

For a broader comparison of serverless platforms (Vercel, Cloudflare Workers, Google Cloud Functions), see our serverless screenshots guide. This page goes deep on Lambda-specific patterns: API Gateway endpoints, EventBridge schedules, S3 event pipelines, Step Functions orchestration.

Why Puppeteer Struggles on Lambda

The @sparticuz/chromium package (successor to the abandoned chrome-aws-lambda) compresses Chromium into a Lambda Layer. The compressed layer weighs around 50 MB. At runtime, it decompresses to 180+ MB in /tmp, which Lambda limits to 512 MB by default (expandable to 10 GB, but at added cost). Add Puppeteer itself, your function code, node_modules. You are constantly managing size budgets.

Memory is the next constraint. Chromium needs at least 1,024 MB to launch reliably. Complex pages with heavy JavaScript push that to 2,048 MB. Lambda charges per GB-second, so a function that burns 2 GB for 8 seconds costs roughly 16x what a 128 MB function running for 1 second costs. That multiplier adds up fast at scale.

Cold starts compound the problem. A Lambda function carrying Chromium takes 3-5 seconds to cold-start while it decompresses the binary, initializes the browser process, loads fonts, and allocates memory. Warm invocations skip this, but Lambda recycles idle instances after 5-15 minutes. For bursty workloads (a dashboard that triggers 50 screenshots at 8 AM), most invocations hit cold starts simultaneously.

Then there are the runtime quirks. Missing system fonts render text as blank rectangles. The --no-sandbox flag is mandatory because Lambda doesn't support Linux namespaces. Some sites detect the headless user agent and serve different content or block the request entirely. Every one of these issues requires its own workaround.

Calling an external screenshot API eliminates all of these constraints. Your function makes a fetch() call, receives the result, and moves on. No layers, no font packages, no sandbox flags, no cold-start tuning.

Basic Lambda Handler

The simplest integration: a Lambda function that receives a URL parameter and forwards it to the ScreenshotRun API. The function returns the resulting screenshot URL as JSON.

// handler.ts — AWS Lambda screenshot function
import { APIGatewayProxyEvent, APIGatewayProxyResult } from 'aws-lambda';

export const handler = async (event: APIGatewayProxyEvent): Promise<APIGatewayProxyResult> => {
    const url = event.queryStringParameters?.url;

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

    const params = new URLSearchParams({
        url,
        format: 'webp',
        width: '1280',
        height: '800',
        block_cookies: 'true',
        block_ads: 'true',
    });

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

    if (!response.ok) {
        const error = await response.text();
        return { statusCode: 502, body: JSON.stringify({ error: 'Capture failed', detail: error }) };
    }

    const data = await response.json();

    return {
        statusCode: 200,
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ screenshot_url: data.screenshot_url, captured_at: new Date().toISOString() }),
    };
};

This function needs 128 MB of memory and zero external dependencies. The fetch API is built into the Node.js 18+ runtime that Lambda supports natively. Deploy it with a zip file under 1 MB. Compare that to the 50+ MB Chromium layer approach.

API Gateway REST Endpoint

Pair the Lambda function with API Gateway to create a public screenshot endpoint. Clients send a GET request with a URL parameter, API Gateway invokes Lambda, Lambda calls ScreenshotRun, and the response flows back through the same chain.

# template.yaml — AWS SAM
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31

Resources:
  ScreenshotFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: handler.handler
      Runtime: nodejs20.x
      MemorySize: 128
      Timeout: 30
      Environment:
        Variables:
          SCREENSHOTRUN_API_KEY: !Ref ApiKeyParameter
      Events:
        CaptureApi:
          Type: Api
          Properties:
            Path: /capture
            Method: get

Parameters:
  ApiKeyParameter:
    Type: String
    NoEcho: true

Deploy with sam build && sam deploy --guided. SAM provisions the API Gateway, Lambda function, IAM role, and CloudWatch log group in one stack. The endpoint accepts requests like GET /capture?url=https://example.com and returns JSON with the screenshot URL.

For production use, add an API key or IAM authorization on the API Gateway stage. Without it, anyone who discovers your endpoint can burn through your screenshot quota.

EventBridge Scheduled Captures

EventBridge (the service formerly known as CloudWatch Events) triggers Lambda functions on a schedule. This is the AWS equivalent of a cron job — useful for daily dashboard snapshots, weekly competitor page captures, hourly uptime monitoring with visual proof.

// scheduled-capture.ts — EventBridge → Lambda → S3
import { S3Client, PutObjectCommand } from '@aws-sdk/client-s3';

const s3 = new S3Client({});

interface ScheduledTarget {
    name: string;
    url: string;
    full_page: boolean;
}

const targets: ScheduledTarget[] = [
    { name: 'homepage', url: 'https://your-app.com', full_page: false },
    { name: 'pricing', url: 'https://your-app.com/pricing', full_page: true },
    { name: 'dashboard', url: 'https://your-app.com/dashboard', full_page: true },
];

export const handler = async () => {
    const date = new Date().toISOString().slice(0, 10);
    const results = [];

    for (const target of targets) {
        const params = new URLSearchParams({
            url: target.url,
            format: 'png',
            width: '1920',
            height: '1080',
            full_page: String(target.full_page),
            block_ads: 'true',
            response_type: 'image',
        });

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

        if (!res.ok) {
            results.push({ target: target.name, status: 'failed' });
            continue;
        }

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

        await s3.send(new PutObjectCommand({
            Bucket: process.env.SCREENSHOT_BUCKET,
            Key: `captures/${date}/${target.name}.png`,
            Body: buffer,
            ContentType: 'image/png',
        }));

        results.push({ target: target.name, status: 'captured', size: buffer.length });
    }

    return { date, results };
};

Add the EventBridge rule in your SAM template:

  ScheduledCapture:
    Type: AWS::Serverless::Function
    Properties:
      Handler: scheduled-capture.handler
      Runtime: nodejs20.x
      MemorySize: 256
      Timeout: 120
      Policies:
        - S3CrudPolicy:
            BucketName: !Ref ScreenshotBucket
      Events:
        DailyCapture:
          Type: Schedule
          Properties:
            Schedule: cron(0 8 * * ? *)
            Description: Daily screenshot capture at 8 AM UTC

Every morning at 8 AM, the function captures each target URL, stores the PNG in S3 organized by date, logs the file sizes, and returns a summary. The S3 bucket becomes a visual archive you can browse with any S3-compatible tool or serve through CloudFront.

S3 Event-Driven Pipeline

Lambda can trigger on S3 events. Upload a JSON file containing URLs to an S3 bucket, and Lambda automatically processes each URL into a screenshot. This pattern works well for batch operations where another system (a CRM export, a web scraper, a data pipeline) produces a list of URLs that need visual captures.

// s3-trigger.ts — S3 upload triggers screenshot capture
import { S3Event } from 'aws-lambda';
import { S3Client, GetObjectCommand, PutObjectCommand } from '@aws-sdk/client-s3';

const s3 = new S3Client({});

export const handler = async (event: S3Event) => {
    for (const record of event.Records) {
        const bucket = record.s3.bucket.name;
        const key = record.s3.object.key;

        // Read the uploaded JSON file
        const obj = await s3.send(new GetObjectCommand({ Bucket: bucket, Key: key }));
        const body = await obj.Body?.transformToString();
        const urls: string[] = JSON.parse(body || '[]');

        for (const url of urls) {
            const params = new URLSearchParams({
                url,
                format: 'webp',
                width: '1280',
                full_page: 'true',
                block_cookies: 'true',
                response_type: 'image',
            });

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

            if (res.ok) {
                const buffer = Buffer.from(await res.arrayBuffer());
                const slug = new URL(url).hostname.replace(/\./g, '-');

                await s3.send(new PutObjectCommand({
                    Bucket: bucket,
                    Key: `screenshots/${slug}-${Date.now()}.webp`,
                    Body: buffer,
                    ContentType: 'image/webp',
                }));
            }
        }
    }
};

Configure the S3 trigger to fire only on .json files in a specific prefix (like input/) to avoid infinite loops where the function's own output triggers another invocation. The full page screenshot feature captures the entire scrollable content, which is particularly useful for archiving long-form pages.

Step Functions for Batch Orchestration

When you need to capture hundreds of URLs with retry logic, rate limiting, error handling, and parallel execution control, Step Functions orchestrates the workflow better than a single Lambda trying to do everything. A Step Functions state machine can fan out captures across multiple Lambda invocations, handle failures individually (retry one failed URL without reprocessing the whole batch), track progress through the AWS console, and collect results into a single output.

{
  "Comment": "Batch screenshot capture with controlled parallelism",
  "StartAt": "ProcessUrls",
  "States": {
    "ProcessUrls": {
      "Type": "Map",
      "ItemsPath": "$.urls",
      "MaxConcurrency": 10,
      "Iterator": {
        "StartAt": "CaptureScreenshot",
        "States": {
          "CaptureScreenshot": {
            "Type": "Task",
            "Resource": "arn:aws:lambda:us-east-1:ACCOUNT:function:capture-single",
            "Retry": [
              {
                "ErrorEquals": ["States.TaskFailed"],
                "IntervalSeconds": 5,
                "MaxAttempts": 2,
                "BackoffRate": 2
              }
            ],
            "End": true
          }
        }
      },
      "Next": "Complete"
    },
    "Complete": {
      "Type": "Succeed"
    }
  }
}

MaxConcurrency: 10 limits parallel Lambda invocations, which prevents you from hitting API rate limits or Lambda concurrency quotas simultaneously. Each failed capture retries twice with exponential backoff. The state machine input is a simple JSON array of URLs, and the output is an array of results — one per URL, with success or failure status.

This pattern scales to thousands of URLs. Feed the state machine from an SQS queue or trigger it through EventBridge when a batch file lands in S3. The e-commerce listing capture use case walks through a similar bulk capture workflow.

Store in S3 and Serve via CloudFront

S3 stores the screenshots. CloudFront serves them globally with edge caching. This combination gives you a CDN-backed screenshot archive without managing any servers.

// store-and-serve.ts — capture, store in S3, return CloudFront URL
import { S3Client, PutObjectCommand } from '@aws-sdk/client-s3';

const s3 = new S3Client({});
const CLOUDFRONT_DOMAIN = process.env.CLOUDFRONT_DOMAIN; // d1234abcdef.cloudfront.net

export async function captureAndStore(url: string, folder: string): Promise<string> {
    const params = new URLSearchParams({
        url,
        format: 'webp',
        width: '1280',
        height: '800',
        block_ads: 'true',
        response_type: 'image',
    });

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

    const buffer = Buffer.from(await res.arrayBuffer());
    const key = `${folder}/${Date.now()}.webp`;

    await s3.send(new PutObjectCommand({
        Bucket: process.env.SCREENSHOT_BUCKET,
        Key: key,
        Body: buffer,
        ContentType: 'image/webp',
        CacheControl: 'public, max-age=604800',
    }));

    return `https://${CLOUDFRONT_DOMAIN}/${key}`;
}

That CacheControl header tells CloudFront to cache each screenshot at edge locations for 7 days. Subsequent requests for the same image serve from the nearest edge, bypassing both S3 and Lambda entirely. For screenshots that change frequently (monitoring dashboards, live pages), reduce the TTL or use cache invalidation when a new capture replaces an old one.

Track Metadata in DynamoDB

Screenshots without context are just images. Store metadata alongside each capture (source URL, capture timestamp, viewport dimensions, file size) and you have a searchable archive. DynamoDB handles this well because the access pattern is simple: write once, query by URL or by date range.

// metadata.ts — store capture metadata in DynamoDB
import { DynamoDBClient } from '@aws-sdk/client-dynamodb';
import { DynamoDBDocumentClient, PutCommand, QueryCommand } from '@aws-sdk/lib-dynamodb';

const ddb = DynamoDBDocumentClient.from(new DynamoDBClient({}));

interface CaptureRecord {
    url: string;
    screenshotKey: string;
    capturedAt: string;
    format: string;
    width: number;
    fileSize: number;
}

export async function saveMetadata(record: CaptureRecord) {
    await ddb.send(new PutCommand({
        TableName: process.env.METADATA_TABLE,
        Item: {
            pk: record.url,
            sk: record.capturedAt,
            screenshotKey: record.screenshotKey,
            format: record.format,
            width: record.width,
            fileSize: record.fileSize,
            ttl: Math.floor(Date.now() / 1000) + 90 * 86400, // 90-day retention
        },
    }));
}

export async function getHistory(url: string, limit = 30) {
    const result = await ddb.send(new QueryCommand({
        TableName: process.env.METADATA_TABLE,
        KeyConditionExpression: 'pk = :url',
        ExpressionAttributeValues: { ':url': url },
        ScanIndexForward: false,
        Limit: limit,
    }));

    return result.Items;
}

URL goes in the partition key, capture timestamp in the sort key. Querying "show me all screenshots of example.com from the last 30 days" is a single DynamoDB query. Add a TTL attribute and DynamoDB automatically deletes old records, keeping your table lean without manual cleanup. The compliance monitoring use case relies on exactly this kind of timestamped capture archive.

Parameters for Lambda Queries

Every parameter goes into the URL query string of your fetch() call. These are the ones most relevant for Lambda-based workflows:

Parameter Value What It Does
url Any public URL The page to capture. Pull from the Lambda event payload, SQS message body, S3 object metadata, or DynamoDB record.
format png, jpeg, webp, pdf Output format. WebP produces files 3-5x smaller than PNG, which cuts S3 storage costs.
width Integer (px) Viewport width. 1280 for desktop, 390 for mobile emulation.
height Integer (px) Viewport height. Ignored when full_page is true.
full_page true / false Capture the entire scrollable page. See full page screenshots.
block_ads true / false Remove ads before capture. Cleaner archival images. See ad blocking.
block_cookies true / false Dismiss cookie consent banners automatically.
dark_mode true / false Force dark mode rendering. See dark mode screenshots.
delay Integer (ms) Wait after page load before capturing. Useful for pages with entry animations.
webhook_url URL Receive the result asynchronously via webhook. Avoids Lambda timeout pressure. See webhooks.
cache_ttl Integer (seconds) Cache identical requests API-side. Same URL within the TTL returns the cached screenshot without re-rendering.

Bind these to environment variables, SSM Parameter Store values, Secrets Manager references, or event payload fields. For scheduled captures, hardcode the parameters in the function. For on-demand captures via API Gateway, accept them as query string parameters and pass them through.

What Teams Build with This Integration

An aws lambda screenshot api setup works best when screenshots are part of a larger event-driven system. These are the patterns we see most often from teams running on AWS.

Visual regression after deployment. A CodePipeline stage triggers a Lambda function after each deployment. The function captures key pages, compares them against baseline screenshots stored in S3 (pixel-diff tools or manual review both work), uploads the diff images, and posts the comparison to a Slack channel. Developers see layout changes before customers report them. The responsive design preview page covers the visual QA side of this workflow.

Compliance archival with DynamoDB audit trail. Financial services, healthcare, government contractors — regulated industries that need timestamped proof of what a page displayed. An EventBridge schedule captures target pages daily. Each screenshot goes to S3 with versioning enabled. DynamoDB stores the metadata with a hash of the image for tamper detection. Auditors query by URL and date range to pull the exact screenshot from any given day.

Thumbnail generation for SaaS platforms. A user submits a URL through your application. API Gateway receives the request, Lambda captures the screenshot via ScreenshotRun, stores it in S3, writes the CDN URL back to DynamoDB, and your frontend displays the thumbnail. The entire flow takes 2-4 seconds. No queues needed for this volume. Scale it up with SQS when throughput exceeds what synchronous processing can handle.

Competitor monitoring pipelines. Marketing teams maintain a list of competitor URLs in DynamoDB. A weekly EventBridge trigger reads the list, fans out captures through Step Functions (10 at a time to stay within rate limits), stores results in S3 organized by date. Over time, the S3 bucket builds a visual timeline showing how competitor sites evolve: pricing changes, layout updates, feature announcements, redesigns. The brand monitoring guide covers the strategic angle.

PDF report generation from live dashboards. Business intelligence teams capture Grafana, Metabase, or Looker dashboards as PDFs every Friday afternoon. The Lambda function calls ScreenshotRun with format=pdf and full_page=true, saves the PDF to S3, and sends it to stakeholders via SES (Simple Email Service). No manual screenshotting, no forgotten reports. The website to PDF feature handles the rendering.

ScreenshotRun pairs naturally with the AWS ecosystem. Your Lambda function handles the workflow logic — when to capture, where to store, who to notify. The API handles the browser rendering — loading pages, executing JavaScript, waiting for dynamic content, producing the final image or PDF. One function, one API call, standard AWS services for everything else. Start with 200 free screenshots per month on the starter plan, scale up as your pipeline grows.

FAQ#

No. ScreenshotRun handles browser rendering on its own infrastructure. Your Lambda function makes a standard HTTPS request and receives the screenshot as a URL or binary response. No layers, no Puppeteer, no Chromium binaries in your deployment package.

A Lambda function calling the ScreenshotRun API runs comfortably at 128 MB — the minimum Lambda allows. Compare that to 1,024–2,048 MB required for running Chromium directly inside Lambda.

Yes. Add an EventBridge (CloudWatch Events) rule to your SAM or CloudFormation template with a cron or rate expression. The Lambda function runs on schedule, calls the API, and stores results in S3 or any other AWS service.

Use AWS Step Functions with a Map state and MaxConcurrency set to 10 or whatever your plan allows. Step Functions fans out captures across parallel Lambda invocations while respecting the concurrency limit. Failed captures retry automatically with exponential backoff.

Set your Lambda timeout to at least 30 seconds for standard captures. For complex pages or full-page PDFs, use the webhook_url parameter — ScreenshotRun sends the result to your webhook endpoint asynchronously, so your Lambda function does not need to wait for rendering to finish.

Use AWS Systems Manager Parameter Store (SecureString) or Secrets Manager. Reference the parameter in your SAM template and pass it as an environment variable to the Lambda function. Never hardcode API keys in your function source code.

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