Tutorial

Open Graph Image Generation: Automate OG Images with a Screenshot API

Build a dynamic OG image service that generates beautiful social media preview cards on demand — without image libraries or design files.

2026-04-04 · 8 min read

Why OG Images Matter

When someone shares a link on Twitter, LinkedIn, Slack, or iMessage, the platform fetches the og:image meta tag to display a preview card. Pages without a custom OG image fall back to a generic placeholder — or nothing at all. Personalized OG images showing the article title, author, and brand increase click-through rates significantly because they stand out in crowded social feeds.

The traditional approach is to pre-generate a static OG image at publish time using a design tool or image manipulation library like Sharp, Pillow, or ImageMagick. This works for blog posts but breaks down for dynamic content: user profile pages, product listings, search results, and any page where content changes frequently or is personalized per viewer.

The Screenshot API Approach

The most flexible OG image generation approach uses an HTML template rendered as a screenshot. You create a hidden page or route in your application that renders the OG card design — title, description, branding, avatar or thumbnail — then use SnapAPI to capture it as a 1200x630 JPEG. The screenshot becomes the OG image. No image library, no design file, no font embedding code.

// og-image API route (Node.js / Express)
app.get("/og", async (req, res) => {
  const { title, author } = req.query;

  // 1. Generate the OG card HTML page URL
  const cardUrl = `https://your-app.com/og-card?title=${encodeURIComponent(title)}&author=${encodeURIComponent(author)}`;

  // 2. Screenshot it at 1200x630
  const params = new URLSearchParams({
    url: cardUrl,
    width: "1200",
    height: "630",
    format: "jpeg",
    quality: "90",
    full_page: "false",
  });

  const snap = await fetch(`https://api.snapapi.pics/v1/screenshot?${params}`, {
    headers: { "X-Api-Key": process.env.SNAPAPI_KEY },
  });

  res.setHeader("Content-Type", "image/jpeg");
  res.setHeader("Cache-Control", "public, max-age=86400");
  snap.body.pipeTo(new WritableStream({
    write(chunk) { res.write(chunk); },
    close() { res.end(); },
  }));
});

The /og-card route renders a minimal HTML page that displays the OG card design using CSS and your application data. It can include web fonts, gradients, custom artwork, and dynamic content. SnapAPI renders it exactly as a browser would, so every CSS feature works as expected.

Caching OG Images

Generating a screenshot on every OG image request is wasteful. Add a Redis or CDN cache layer keyed on the page identifier. On the first request, generate the screenshot and cache the image bytes with a 24-hour TTL. Subsequent requests for the same article OG image are served from cache in milliseconds without hitting SnapAPI at all.

For published content that rarely changes, you can pre-generate OG images at publish time — trigger a SnapAPI call in your CMS publish webhook and store the result in S3. Return the S3 URL in the og:image meta tag. This eliminates runtime latency entirely for static content.

Invalidating Social Media Caches

Twitter and Facebook cache OG images aggressively. After updating an OG image, use the platform debug tools to force re-crawling: Twitter Card Validator at cards-dev.twitter.com/validator, and Facebook Sharing Debugger at developers.facebook.com/tools/debug. For LinkedIn, use their Post Inspector tool. Scraping these tools programmatically is against their terms, so manual invalidation is required after significant design changes.

Sign up at snapapi.pics for 200 free captures per month to start building your OG image service. The screenshot endpoint supports the 1200x630 dimensions recommended by the Open Graph protocol and returns JPEG with configurable quality for fast social media loading.

Building the OG Card HTML Template

The OG card template is just a regular web page that happens to be 1200x630 pixels. Style it with CSS just like any other page: use web fonts via Google Fonts or self-hosted, apply your brand colors, add the logo, and lay out the title and metadata however your design calls for. The key constraint is that the page should look good at exactly 1200x630 and not depend on the user's viewport beyond that size.

A simple, high-performing OG card template includes: a solid or gradient background in your brand color, the article title in large white text (36-48px), the author name and date in smaller text, your site logo in a corner, and optionally a thumbnail image passed via a query parameter. Avoid complex animations or interactive elements — the screenshot captures a static state.

<!-- /og-card route in your app -->
<style>
body { margin:0; width:1200px; height:630px; overflow:hidden;
  background: linear-gradient(135deg, #0f172a 0%, #1e3a5f 100%);
  display:flex; align-items:center; padding:60px;
  font-family: "Inter", sans-serif; color: white; box-sizing:border-box; }
.title { font-size:48px; font-weight:800; line-height:1.2; margin-bottom:24px; }
.meta  { font-size:20px; opacity:0.7; }
.logo  { position:absolute; top:40px; right:60px; height:40px; }
</style>
<img class="logo" src="/logo.svg">
<div>
  <div class="title">{{ title }}</div>
  <div class="meta">{{ author }} · {{ date }}</div>
</div>

Pass title, author, and date as query parameters from your CMS or application, render the template server-side, and SnapAPI captures it at 1200x630. The result is a professional OG image that reflects your real brand without any image library dependencies.

Per-Article vs Per-Section OG Images

Most teams generate one OG image per article or page. But for high-traffic sites, you can go further: generate unique OG images for different sections of long articles when they are shared via fragment links, or create custom OG images for search result pages, author profile pages, tag archive pages, and category landing pages. Each type benefits from its own template — an author page OG image might prominently feature the author photo, while a category page might show recent article thumbnails in a grid.

The screenshot API approach makes this practical because you only maintain HTML templates — not a complex image generation pipeline with different code paths for each content type. Add a new template, register the route, and a new OG image type is live in minutes.

OG Image Generation in Python

For Python-based CMSes (Django, Flask, FastAPI), the OG image generation pattern is identical — call SnapAPI from a view or background task:

import requests

def generate_og_image(title: str, author: str) -> bytes:
    card_url = f"https://your-app.com/og-card?title={requests.utils.quote(title)}&author={requests.utils.quote(author)}"
    resp = requests.get(
        "https://api.snapapi.pics/v1/screenshot",
        params={"url": card_url, "width": "1200", "height": "630", "format": "jpeg", "quality": "90"},
        headers={"X-Api-Key": "YOUR_API_KEY"},
        timeout=30
    )
    resp.raise_for_status()
    return resp.content  # JPEG bytes, upload to S3 or serve directly

Trigger this function from a Django post_save signal or Celery task when a new article is published. Upload the returned bytes to S3, generate a CloudFront URL, and store it in the article model as the og_image field. Your HTML template then reads this URL for the og:image meta tag.

Start generating dynamic OG images at snapapi.pics — 200 free captures per month. The 1200x630 JPEG format with quality 85-90 is the sweet spot between visual quality and file size for social media preview loading speed.

Performance: OG Image Load Time

Social platforms download OG images when they first crawl your URL. Large images slow down the crawl and can cause the platform to skip your image entirely. Keep OG images under 300 KB — a 1200x630 JPEG at quality 85 typically lands between 80 and 200 KB depending on content complexity. Use format=jpeg&quality=85 in your SnapAPI call for the right balance.

For sites behind a CDN like Cloudflare or Fastly, configure the CDN to cache your OG image endpoint at the edge. Add a Cache-Control header of public, max-age=86400, stale-while-revalidate=3600 so the CDN serves cached versions while asynchronously refreshing them, eliminating cold-start latency for social media crawlers from any geography.

Next Steps

Building a dynamic OG image service with SnapAPI takes an afternoon for most teams: design an HTML card template, create a server route that renders it with page-specific data, add a SnapAPI screenshot call with 1200x630 dimensions, cache the result in Redis or S3, and update your meta tags. The result is a professional social sharing experience across every page of your site without maintaining image generation infrastructure.

Sign up at snapapi.pics to get started with 200 free captures per month. All core parameters — format, quality, width, height, and device emulation — are available on the free tier. This gives you a complete environment to test your OG image template before deploying to production.

open graph image generation og image api dynamic og images social media preview screenshot api og image service og image generator
og image automation social preview dynamic image generation link preview card twitter og facebook og
og image api