OG Image Generator API

Auto-generate Open Graph images for every URL. Boost click-through rates by 2–5× with dynamic social previews — no design work required.

Get Free API Key

Why Open Graph Images Determine Your Click-Through Rate

When someone shares a link on Twitter, LinkedIn, Slack, or iMessage, the platform fetches the Open Graph image attached to that URL and renders it as a rich preview card. Studies consistently show that posts with compelling visual previews generate 2–5× more clicks than plain-text links. Yet most SaaS products, blogs, and documentation sites still serve a static fallback image — the same generic logo on every page. That means every shared link looks identical, provides no context, and completely wastes the attention of whoever scrolled past it.

Dynamic OG images fix this by generating a unique preview for every page. A blog post gets a card showing its title, author, and publication date. A product page gets a card with the product name and a key metric. A documentation page gets a card with the library name and the specific function being documented. The preview becomes a mini-advertisement for the content, giving the reader a reason to click before they even reach the page. For developer-focused products in particular — APIs, SDKs, dev tools — rich previews signal quality and professionalism in a community where first impressions matter enormously.

The challenge is infrastructure. Generating images at scale requires a headless browser, an HTML rendering pipeline, a caching layer, and careful handling of fonts, icons, and dynamic text layout. Building that stack in-house takes weeks and adds ongoing maintenance burden. SnapAPI abstracts all of that behind a single API call, giving you dynamic OG images in a few lines of code.

How the SnapAPI OG Image Pipeline Works

The SnapAPI screenshot endpoint renders any URL or HTML template to a pixel-perfect PNG or JPEG in under two seconds. For OG image generation, you typically use one of two patterns: URL-based generation (screenshot an existing page) or HTML template generation (inject dynamic data into a custom template). Both patterns return a hosted image URL suitable for use in og:image meta tags.

URL-based generation is the simplest approach. You pass the page URL to SnapAPI and receive a screenshot. This works well for marketing pages and long-form content where the page itself looks good as a thumbnail. The limitation is that full-page screenshots can be too information-dense for the 1200×630 OG image dimensions — too much text, too many elements, making the preview unreadable at social-card size.

HTML template generation is more powerful for programmatic use cases. You design a minimal, high-contrast template with large typography and bold branding, inject the dynamic data (title, author, tags, metrics), and pass the rendered HTML to SnapAPI. The result is a clean, purpose-built image that reads instantly at thumbnail size. This approach gives you full design control without requiring image manipulation libraries or server-side Canvas rendering.

Next.js API Route: OG Image on Demand

// pages/api/og.js
export default async function handler(req, res) {
  const { title, author, date, tag } = req.query;

  const html = `
    <html>
    <head>
      <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body {
          width: 1200px; height: 630px;
          background: linear-gradient(135deg, #667eea, #764ba2);
          display: flex; align-items: center; justify-content: center;
          font-family: Inter, sans-serif; color: white;
        }
        .card { padding: 80px; width: 100%; }
        .tag { background: rgba(255,255,255,.2); padding: 6px 16px;
               border-radius: 20px; font-size: 18px; display: inline-block; margin-bottom: 24px; }
        h1 { font-size: 64px; font-weight: 800; line-height: 1.1;
             margin-bottom: 32px; max-width: 900px; }
        .meta { font-size: 22px; opacity: 0.8; }
        .logo { position: absolute; top: 48px; right: 64px;
                font-size: 28px; font-weight: 800; opacity: 0.9; }
      </style>
    </head>
    <body>
      <div class="logo">YourBrand</div>
      <div class="card">
        <div class="tag">${tag || 'Article'}</div>
        <h1>${title}</h1>
        <div class="meta">${author} &bull; ${date}</div>
      </div>
    </body>
    </html>
  `;

  const params = new URLSearchParams({
    access_key: process.env.SNAPAPI_KEY,
    html: html,
    viewport_width: '1200',
    viewport_height: '630',
    format: 'png',
    cache: '1',
    cache_ttl: '86400'
  });

  const imgRes = await fetch(
    `https://snapapi.pics/screenshot?${params}`
  );

  res.setHeader('Content-Type', 'image/png');
  res.setHeader('Cache-Control', 'public, s-maxage=31536000, stale-while-revalidate');
  imgRes.body.pipe(res);
}

With this route live, your _document.js or next/head usage becomes trivial. For any blog post, you construct the OG URL dynamically from the post's metadata:

// In your blog post template
const ogImageUrl = `https://yourdomain.com/api/og?` +
  `title=${encodeURIComponent(post.title)}&` +
  `author=${encodeURIComponent(post.author)}&` +
  `date=${encodeURIComponent(post.date)}&` +
  `tag=${encodeURIComponent(post.category)}`;

// In <Head>
<meta property="og:image" content={ogImageUrl} />
<meta name="twitter:card" content="summary_large_image" />
<meta name="twitter:image" content={ogImageUrl} />

CDN Caching Strategy for OG Images

Without caching, every social crawler visit — and there can be hundreds per day for a popular post — triggers a new screenshot render. That drives up API usage and increases latency for the first load. The correct approach is aggressive CDN caching with the s-maxage directive, which instructs CDN edges to cache the response independently of client-side cache headers.

Setting s-maxage=31536000 (one year) means the CDN serves the cached image for 12 months without revalidating. Pair this with stale-while-revalidate and the CDN serves the stale image while refreshing in the background. For content that changes infrequently (blog posts, documentation), this is the optimal strategy. For dynamic dashboards or metrics pages, reduce the TTL to match your data refresh cycle — hourly or daily.

If you use Vercel, its Edge Network handles s-maxage automatically. Cloudflare, Fastly, and AWS CloudFront all respect the same directive. The result is that after the first render, OG image delivery is effectively free — served from edge nodes at sub-20ms latency worldwide, without touching your API quota.

Build-Time Pre-Generation for Static Sites

For static site generators like Gatsby, Astro, or Hugo, you can pre-generate all OG images at build time and commit them to your CDN or object storage. This eliminates runtime API calls entirely — the images exist before any user visits the page. The build script iterates over your content collection, calls SnapAPI for each item, and saves the resulting PNG to your public/ directory or uploads it to S3.

# build-og-images.sh
#!/bin/bash
POSTS_DIR="./content/posts"
OUTPUT_DIR="./public/og"
mkdir -p $OUTPUT_DIR

for post in $POSTS_DIR/*.md; do
  slug=$(basename "$post" .md)
  title=$(grep "^title:" "$post" | sed 's/title: //')

  curl -s "https://snapapi.pics/screenshot"     -d "access_key=$SNAPAPI_KEY"     -d "html=..."     -d "format=png"     -o "$OUTPUT_DIR/$slug.png"

  echo "Generated OG image for: $slug"
done

OG Image API Feature Comparison

FeatureSnapAPIVercel OGBannerbearCloudinary
HTML template support✅ Full HTML/CSS✅ JSX only❌ JSON templates⚠️ Limited
URL screenshot
Custom fonts
Free tier200/moGenerous25 transforms
Render speed<2s<1s1-3s<1s
REST APINext.js only

Real-World Use Cases

Beyond blog posts, dynamic OG images add measurable value across several content types. SaaS dashboards can generate shareable metric cards — imagine a user sharing their weekly analytics summary, with an OG image showing a key number like "32% growth this week." Product changelog pages can generate release-specific previews, making each changelog share look distinct in social feeds. Job boards and marketplace listings can auto-generate cards with the job title, company logo, and salary range, creating eye-catching previews that stand out in LinkedIn or Twitter feeds. Documentation sites can generate per-page cards with the function signature and a short description, helping developers remember what they were reading when they reshare links weeks later.

Each of these use cases follows the same pattern: define a minimal HTML template, inject the dynamic data, call the SnapAPI screenshot endpoint, cache aggressively. The consistency of the pattern means you can build a single OG image service and reuse it across your entire product surface with minimal adaptation.

Start Generating OG Images in Minutes

Free tier includes 200 screenshots/month. No credit card required.

Get Your Free API Key

Frequently Asked Questions

What image dimensions should OG images be?

The recommended OG image size is 1200×630 pixels (1.91:1 aspect ratio). This renders well on Facebook, Twitter/X, LinkedIn, and iMessage. For Twitter "summary_large_image" cards specifically, the image must be at least 300×157 and no larger than 4096×4096. Sticking to 1200×630 satisfies all platforms. SnapAPI lets you set viewport_width and viewport_height to match these exact dimensions.

How do I use custom fonts in my OG image template?

The safest approach is to embed the font as a base64-encoded data URI in your HTML template's <style> block. Alternatively, load the font from a publicly accessible CDN URL — Google Fonts works well. Avoid loading fonts from localhost or private URLs that the SnapAPI render server cannot reach. Inter, Roboto, and system-ui all work out of the box without any embedding required.

Can I cache OG images to reduce API usage?

Absolutely — and you should. Use SnapAPI's built-in caching by passing cache=1&cache_ttl=86400 in your request parameters. For CDN-level caching, set Cache-Control: public, s-maxage=31536000 on your OG image endpoint response. For static sites, pre-generate images at build time and serve them as static assets — zero runtime API calls, maximum performance.

Does SnapAPI support transparent PNG backgrounds for OG images?

OG images should use opaque backgrounds — social platforms (Facebook, Twitter) render transparent PNGs with a black or white fill that often looks broken. Design your template with an explicit background color or gradient. Use PNG format for crisp text rendering, or JPEG with quality=90+ for smaller file sizes when you have photographic backgrounds.

What is the rate limit for the OG image endpoint?

SnapAPI rate limits apply to all screenshot requests. The Starter plan ($19/mo, 5,000 requests) is sufficient for most blogs and SaaS products. For high-traffic sites, combine SnapAPI's built-in response caching with CDN caching to ensure the API is only called once per unique image, not once per visitor. Most production setups stay well within limits with proper caching in place.