Vercel Screenshot API Integration

Take screenshots in Vercel serverless functions and Edge Functions. No Chromium binary, no bundle size issues. Working Next.js API route examples and OG image generation.

Vitalii Holben Updated

If you are building with Next.js on Vercel and need screenshots, the first instinct is usually Puppeteer. That instinct runs straight into Vercel's 50 MB function bundle limit — Chromium alone exceeds it. The standard workaround is a separate server just to run a browser, which defeats the point of serverless. The cleaner path is a screenshot API: one fetch call from your API route, image bytes come back in the response, done.

ScreenshotRun fits naturally into Next.js API routes, Edge Functions, and any other serverless compute Vercel provides. The browser runs on ScreenshotRun's infrastructure. Your function stays lightweight.

Your First Screenshot in a Vercel Serverless Function

Create a Next.js API route at app/api/screenshot/route.ts:

import { NextRequest, NextResponse } from "next/server";

export async function GET(req: NextRequest) {
  const url = req.nextUrl.searchParams.get("url");

  if (!url) {
    return NextResponse.json({ error: "url parameter required" }, { status: 400 });
  }

  const response = await fetch(
    `https://api.screenshotrun.com/v1/screenshots/capture?` +
      new URLSearchParams({
        url,
        format: "png",
        width: "1280",
        height: "720",
        full_page: "false",
        block_ads: "true",
      }),
    {
      headers: {
        Authorization: `Bearer ${process.env.SCREENSHOTRUN_API_KEY}`,
      },
    }
  );

  if (!response.ok) {
    return NextResponse.json({ error: "Screenshot failed" }, { status: 500 });
  }

  const imageBuffer = await response.arrayBuffer();

  return new NextResponse(imageBuffer, {
    headers: {
      "Content-Type": "image/png",
      "Cache-Control": "public, max-age=3600",
    },
  });
}

Deploy to Vercel and call it at /api/screenshot?url=https://example.com. The function proxies the image straight back to the client. The Cache-Control header tells Vercel's CDN to cache the response for an hour, so repeated requests for the same URL skip the API call entirely.

Setting the API Key in Vercel

Go to your project's Settings → Environment Variables. Add SCREENSHOTRUN_API_KEY with the value from your ScreenshotRun dashboard. Set it for Production, Preview, and Development environments.

In your code, read it with process.env.SCREENSHOTRUN_API_KEY. Never hardcode API keys or commit them to your repository — Vercel injects environment variables at build time and runtime automatically.

For local development, add it to .env.local:

SCREENSHOTRUN_API_KEY=your_key_here

Next.js reads .env.local automatically in development. The same code runs locally and in production without changes.

OG Image Generation

Open Graph images are one of the most common screenshot API use cases on Vercel. When a URL gets shared on Slack, Twitter, or LinkedIn, the platform fetches the og:image meta tag and shows a preview card. Generating those images dynamically — with the page's actual content, title, or product data — makes cards look professional instead of defaulting to a generic logo.

The pattern: render an HTML template server-side, capture it as a PNG, and return it from an API route that your og:image meta tag points to:

import { NextRequest, NextResponse } from "next/server";

export async function GET(req: NextRequest) {
  const { searchParams } = req.nextUrl;
  const title = searchParams.get("title") ?? "Untitled";
  const description = searchParams.get("description") ?? "";

  // Build an HTML template with the dynamic content
  const html = `
    
    
    
      
    
    
      

${title}

${description}

`; const response = await fetch( "https://api.screenshotrun.com/v1/screenshots/capture", { method: "POST", headers: { Authorization: `Bearer ${process.env.SCREENSHOTRUN_API_KEY}`, "Content-Type": "application/json", }, body: JSON.stringify({ html, format: "png", width: 1200, height: 630, }), } ); const imageBuffer = await response.arrayBuffer(); return new NextResponse(imageBuffer, { headers: { "Content-Type": "image/png", "Cache-Control": "public, max-age=86400, immutable", }, }); }

In your page component, point the og:image tag at this route:

// app/blog/[slug]/page.tsx
export async function generateMetadata({ params }: { params: { slug: string } }) {
  const post = await getPost(params.slug);

  return {
    openGraph: {
      images: [
        {
          url: `/api/og?title=${encodeURIComponent(post.title)}&description=${encodeURIComponent(post.excerpt)}`,
          width: 1200,
          height: 630,
        },
      ],
    },
  };
}

Each blog post, product page, and user profile gets its own OG image generated on demand. The 24-hour cache means Vercel generates it once per day per URL, not on every social media crawl.

Preview Deployment Visual QA

Every pull request on Vercel gets a unique preview URL. That is a natural checkpoint for catching visual regressions before they reach production. After Vercel deploys the preview, a webhook or GitHub Action can trigger a screenshot comparison:

// Capture both preview and production versions of key pages
async function compareDeployments(previewUrl: string, productionUrl: string, path: string) {
  const [previewScreenshot, productionScreenshot] = await Promise.all([
    fetch(`https://api.screenshotrun.com/v1/screenshots/capture?` +
      new URLSearchParams({ url: previewUrl + path, format: "png", width: "1280" }), {
      headers: { Authorization: `Bearer ${process.env.SCREENSHOTRUN_API_KEY}` },
    }),
    fetch(`https://api.screenshotrun.com/v1/screenshots/capture?` +
      new URLSearchParams({ url: productionUrl + path, format: "png", width: "1280" }), {
      headers: { Authorization: `Bearer ${process.env.SCREENSHOTRUN_API_KEY}` },
    }),
  ]);

  return {
    preview: Buffer.from(await previewScreenshot.arrayBuffer()),
    production: Buffer.from(await productionScreenshot.arrayBuffer()),
  };
}

Both captures run in parallel. Pass the resulting buffers to an image diff library like pixelmatch or send them to a vision model for plain-language change descriptions. This catches shifted layouts, missing images, and broken fonts before the PR merges — without setting up a full Playwright test suite for visual checks.

Async Captures with Webhooks

Vercel serverless functions have a maximum execution time of 60 seconds on Pro plans, 300 seconds on Enterprise. For most screenshots that is plenty. But if you are capturing slow pages or running bulk captures, the webhook parameter lets your function return immediately while ScreenshotRun delivers the result asynchronously:

export async function POST(req: NextRequest) {
  const { url } = await req.json();

  // Fire and forget — returns immediately
  await fetch(
    `https://api.screenshotrun.com/v1/screenshots/capture?` +
      new URLSearchParams({
        url,
        format: "png",
        width: "1280",
        webhook_url: `${process.env.VERCEL_URL}/api/screenshot-webhook`,
      }),
    {
      headers: { Authorization: `Bearer ${process.env.SCREENSHOTRUN_API_KEY}` },
    }
  );

  return NextResponse.json({ status: "queued" });
}

// Webhook receiver at /api/screenshot-webhook
export async function POST_WEBHOOK(req: NextRequest) {
  const { url, image_url, metadata } = await req.json();

  // Store result in your database
  await saveScreenshot({ url, image_url, metadata });

  return NextResponse.json({ received: true });
}

The first function queues the capture and returns { status: "queued" } in milliseconds. ScreenshotRun calls your webhook route when the screenshot is ready. This pattern works well for user-triggered captures where you want a fast UI response before the image is ready.

Edge Functions

Vercel Edge Functions run at the CDN edge rather than in a regional serverless environment. They have stricter constraints — no Node.js APIs, no filesystem access, no native modules — but lower latency and no cold starts. ScreenshotRun works in Edge Functions because it only requires fetch, which is available in all edge runtimes:

import { NextRequest, NextResponse } from "next/server";

export const runtime = "edge";

export async function GET(req: NextRequest) {
  const url = req.nextUrl.searchParams.get("url");
  if (!url) return NextResponse.json({ error: "url required" }, { status: 400 });

  const response = await fetch(
    `https://api.screenshotrun.com/v1/screenshots/capture?` +
      new URLSearchParams({ url, format: "webp", width: "1280" }),
    {
      headers: { Authorization: `Bearer ${process.env.SCREENSHOTRUN_API_KEY}` },
    }
  );

  const buffer = await response.arrayBuffer();
  return new NextResponse(buffer, {
    headers: { "Content-Type": "image/webp", "Cache-Control": "public, max-age=3600" },
  });
}

Using webp format makes sense for edge delivery — WebP files are typically 30–40% smaller than PNGs for the same visual quality, which matters when you are serving images from edge locations to end users.

Parameters for Vercel Deployments

Parameter Recommended value Reason
format webp for delivery, png for OG images WebP reduces bandwidth; PNG required for some social platforms
width 1280 for pages, 1200 for OG Standard desktop viewport; 1200×630 is the OG spec
block_ads true Cleaner captures, no ad overlays in screenshots
cache_ttl 3600–86400 Avoid re-rendering the same URL on every request
full_page false for OG, true for archival OG images need a fixed 1200×630; archival needs full content
webhook_url Your /api/screenshot-webhook route Async delivery for bulk captures or slow pages

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