How to Generate Dynamic Open Graph Images with a Screenshot API
Render per-page Open Graph images from an HTML template, store them at a public stable URL, and avoid the mistakes that break social previews.
An Open Graph image is the picture that appears when someone shares your link in a social feed or chat app. A dynamic OG image is one you generate per page (with the post title, author, product name or price) instead of using one site-wide graphic.
This guide is about publishing OG images for your own pages. If you are building the other side, an app that shows previews for links your users paste, see building a link preview service. For the platform-by-platform image rules, see the social media image sizes guide.
The approach in one paragraph
Build an HTML page that is exactly 1200 × 630 pixels and renders one piece of content as a card. When that content is published or changed, a server-side job asks a screenshot API to capture the card, checks the result, and uploads it to public storage under a file name that includes a hash of the card's content. The page's og:image tag points at that stored file. Crawlers fetch a plain static image; your API key never leaves your server.
publish/update event
│
▼
your server ──POST /api/screenshot──▶ Screenshotly ──loads──▶ https://yoursite.com/og/<slug> (1200×630 template)
│◀────────── PNG bytes ──────────┘
▼
upload to bucket/CDN: og/<slug>-<hash>.png (public, immutable)
▼
<meta property="og:image" content="https://cdn.yoursite.com/og/<slug>-<hash>.png">
Two rules that save most of the debugging
1. og:image must be a public, stable URL. Social crawlers fetch the image anonymously. The Screenshotly endpoint is POST https://screenshotly.app/api/screenshot with an x-api-key header, so a crawler can't call it, and you must never put the key in your HTML. The API's optional storage delivery returns a signed URL that expires after 24 hours, so that doesn't work as an og:image either. Store the bytes yourself.
2. A new image needs a new URL. Meta's sharing documentation says images are cached by URL and won't update unless the URL changes. Name files by content hash (launch-post-3f9a1c.png) and the problem goes away.
Step 1: build the card template
The template is an ordinary page on your site, for example /og/[slug], that renders a fixed-size card. Keep it free of cookie banners, analytics popups, chat widgets and anything else your normal layout injects.
// Renders the OG card HTML for one post. Serve it at /og/:slug from any framework.
const escapeHtml = (value) =>
String(value).replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]);
export function renderOgCard({ title, category, author }) {
return `<!doctype html>
<html>
<head>
<meta charset="utf-8">
<style>
@font-face { font-family: 'Brand'; src: url('/fonts/brand-bold.woff2') format('woff2'); font-weight: 700; }
html, body { margin: 0; width: 1200px; height: 630px; overflow: hidden; }
body {
box-sizing: border-box; padding: 72px; display: flex; flex-direction: column; justify-content: space-between;
background: #0f172a; color: #f8fafc; font-family: 'Brand', system-ui, sans-serif;
}
.category { font-size: 28px; letter-spacing: 0.08em; text-transform: uppercase; color: #93c5fd; }
h1 { margin: 0; font-size: 64px; line-height: 1.15; max-width: 1000px;
display: -webkit-box; -webkit-line-clamp: 3; -webkit-box-orient: vertical; overflow: hidden; }
.footer { display: flex; justify-content: space-between; font-size: 28px; }
</style>
</head>
<body>
<div class="category">${escapeHtml(category)}</div>
<h1>${escapeHtml(title)}</h1>
<div class="footer"><span>${escapeHtml(author)}</span><span>yoursite.com</span></div>
<script>
// Signal readiness only after web fonts have loaded.
document.fonts.ready.then(() => document.body.setAttribute('data-og-ready', '1'));
</script>
</body>
</html>`;
}
Template guidelines that matter in practice:
- Look content up by slug on the server. Don't accept the title as a query parameter, or anyone can make your domain render arbitrary text. Escape everything you insert, as above.
- Clamp long titles.
-webkit-line-clampstops a 140-character title from running off the card. - Keep text away from the edges. Platforms display the image at different sizes and some crop slightly. Generous padding (72 px here) keeps titles intact.
- Fix the size.
width: 1200px; height: 630px; overflow: hiddenonhtmlandbodymakes the page exactly one card tall.
Open /og/your-slug in a browser with the window set to 1200 × 630 to design it. What you see is what the capture produces.
Step 2: capture the card
The request for one card:
{
"url": "https://yoursite.com/og/launch-post",
"width": 1200,
"height": 630,
"deviceScaleFactor": 1,
"fullPage": true,
"waitForSelector": "body[data-og-ready]",
"format": "png"
}
Why each field is there:
width/height1200 × 630 set the browser window to the card size. Send both; a custom size needs both values.deviceScaleFactor: 1gives exactly 1200 × 630 output. DPR 2 would produce 2400 × 1260, which platforms accept but which costs bandwidth for no visible gain in a feed.fullPage: trueon a template that is exactly 630 pixels tall still produces a 1200 × 630 image. We use it because the current renderer only loads web fonts for full-page captures (checked 13 November 2026). If your card uses only system fonts,fullPagecan befalse.waitForSelectorwaits (up to 10 seconds) until the template marks itself ready afterdocument.fonts.ready. If the selector never appears, the capture still happens, so check the output (step 3).format: "png"keeps text edges crisp. For photo-heavy cards,"jpeg"with"quality": 85gives much smaller files.
All of these fields are available on the Free plan.
Step 3: capture, verify and upload on publish
This script runs on your server when a post is published or edited. It hashes the card's inputs, skips work if that version already exists, captures, checks the dimensions, and uploads to S3 with a long cache lifetime. It uses sharp and the AWS SDK v3; swap in your own storage client if you use R2, GCS or something else.
import { createHash } from 'node:crypto';
import sharp from 'sharp';
import { S3Client, PutObjectCommand, HeadObjectCommand } from '@aws-sdk/client-s3';
const s3 = new S3Client({ region: process.env.AWS_REGION });
const BUCKET = process.env.OG_BUCKET;
const PUBLIC_BASE = process.env.OG_PUBLIC_BASE; // e.g. https://cdn.yoursite.com
const SITE = process.env.SITE_URL; // e.g. https://yoursite.com
async function exists(key) {
try {
await s3.send(new HeadObjectCommand({ Bucket: BUCKET, Key: key }));
return true;
} catch {
return false;
}
}
export async function publishOgImage(post) {
// Hash everything that changes the card, including a template version.
const hash = createHash('sha256')
.update(JSON.stringify({ v: 3, title: post.title, category: post.category, author: post.author }))
.digest('hex')
.slice(0, 12);
const key = `og/${post.slug}-${hash}.png`;
if (await exists(key)) return `${PUBLIC_BASE}/${key}`;
const res = await fetch('https://screenshotly.app/api/screenshot', {
method: 'POST',
headers: {
'x-api-key': process.env.SCREENSHOTLY_API_KEY,
'content-type': 'application/json',
},
body: JSON.stringify({
url: `${SITE}/og/${post.slug}`,
width: 1200,
height: 630,
deviceScaleFactor: 1,
fullPage: true,
waitForSelector: 'body[data-og-ready]',
format: 'png',
}),
});
if (!res.ok) throw new Error(`OG capture failed (${res.status}): ${await res.text()}`);
const png = Buffer.from(await res.arrayBuffer());
// Never publish a card with the wrong shape (e.g. template overflowed).
const { width, height } = await sharp(png).metadata();
if (width !== 1200 || height !== 630) {
throw new Error(`Unexpected OG size ${width}x${height} for ${post.slug}`);
}
await s3.send(new PutObjectCommand({
Bucket: BUCKET,
Key: key,
Body: png,
ContentType: 'image/png',
CacheControl: 'public, max-age=31536000, immutable',
}));
return `${PUBLIC_BASE}/${key}`;
}
Store the returned URL with the post (for example an ogImageUrl column) and render it in the page head. Because the hash covers the card's inputs, editing the title produces a new file and a new URL, and an unchanged post never triggers a second capture.
Failure handling. If the capture or the size check fails, keep the post's previous ogImageUrl, or fall back to a static site-wide default, and retry later. Don't block publishing on the OG image. Failed captures don't count against your Screenshotly quota.
Backfilling existing content. Run the same function over old posts with low concurrency. Per-minute limits are 5 requests on Free, 40 on Basic, 80 on Growth and 200 on Scale. On HTTP 429, wait for the Retry-After header.
Step 4: add the meta tags
<meta property="og:type" content="article">
<meta property="og:url" content="https://yoursite.com/blog/launch-post">
<meta property="og:title" content="We shipped the thing">
<meta property="og:description" content="What changed, why, and how to try it.">
<meta property="og:image" content="https://cdn.yoursite.com/og/launch-post-3f9a1c2b7d4e.png">
<meta property="og:image:type" content="image/png">
<meta property="og:image:width" content="1200">
<meta property="og:image:height" content="630">
<meta property="og:image:alt" content="Card reading 'We shipped the thing' by Jane Doe">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:image" content="https://cdn.yoursite.com/og/launch-post-3f9a1c2b7d4e.png">
- The Open Graph protocol lists
og:title,og:type,og:imageandog:urlas required, and says a page that specifiesog:imageshould also specifyog:image:alt. - Meta recommends sending
og:image:widthandog:image:heightso the image renders correctly the first time a link is shared. - Use absolute
https://URLs for the page and the image. - Make sure the image path isn't behind authentication, isn't a short-lived signed URL, and isn't disallowed in your
robots.txt.
What the platforms document
Checked against each platform's own documentation on 13 November 2026:
| Platform | What its docs say |
|---|---|
| Meta (Facebook) | Use images at least 1200 × 630 for the best display; 600 × 315 at minimum for larger previews; 200 × 200 is the smallest allowed. Keep close to 1.91:1. Maximum file size 8 MB. Images are cached by URL. |
Requires og:title, og:image, og:description and og:url. Minimum image 1200 × 627, recommended ratio 1.91:1, max 5 MB. Images under 401 px wide display as a thumbnail. |
|
| Slack | Without an app handling the domain, Slack's classic unfurl reads common Open Graph and X Card metadata. |
| X | X's card documentation wasn't retrievable when we checked, so we don't state X-specific limits here. Send twitter:card = summary_large_image and check X's current docs. |
A 1200 × 630 PNG well under 5 MB satisfies every documented requirement above. The image sizes guide has the sources and more detail.
Test before you share
- Open the stored image URL in a private browser window. It should load without cookies or headers.
- Run the page through Meta's Sharing Debugger (requires a Facebook login). It shows which tags were scraped and triggers a fresh scrape.
- Run it through LinkedIn's Post Inspector, which also refreshes LinkedIn's cached preview.
- Paste the link into a private Slack channel to check the unfurl.
Refreshing only affects new shares. Posts made before the refresh may keep the old preview.
Variations
Product UI in the card. Point the capture at a real product page instead of a template, still at 1200 × 630. Use blockAds (all plans) to hide common ad and consent elements. On Growth and above, hideSelectors removes specific elements and mockup can wrap the capture in a browser frame. Note that a mockup's output takes the frame template's dimensions, so resize or pad it to 1200 × 630 (sharp's resize with fit: 'contain' works) before publishing.
Several card designs. Add a template field to the hashed inputs and serve /og/[slug]?t=minimal variants from the same route. Changing the design then automatically produces new URLs.
Alternatives to a screenshot API. If you're on Next.js, next/og renders images from JSX at the edge with a subset of CSS. A screenshot API renders the template in a full browser, so any CSS, web font or chart library you already use works unchanged. Pick whichever fits your stack.
Checklist
- Template is exactly 1200 × 630, escapes inserted text and contains no popups or third-party widgets
- Capture runs server-side; the API key is never in client code or HTML
- Output size is verified before upload
- Image lives at a public, permanent URL with a content hash in the name
-
og:image,og:image:width,og:image:height,og:image:altandtwitter:cardare set - A static fallback image exists for failures
- Previews are checked in Meta's Sharing Debugger and LinkedIn's Post Inspector
Related
- Building previews for links your users paste: Link preview generation
- Platform image rules with sources: Social media image sizes
- Picking capture sizes for other jobs: Choosing a screenshot viewport
- Overview for marketing teams: Social media previews use case
Try a 1200 × 630 capture of your own template in the playground, or create a free account for 100 captures to build the pipeline.
About the Author

Asad Ali
CTO at ZTABS and the developer behind Screenshotly. Writes about screenshot automation, API design, and building reliable SaaS backends with Next.js, Node.js, and TypeScript.
Credentials: CTO at ZTABS, full-stack developer, builder and maintainer of Screenshotly and its official JavaScript and Python clients
Frequently Asked Questions
Can I put the screenshot API URL directly in og:image?
No. The capture endpoint is a POST request that needs your API key, so social crawlers can't call it, and exposing the key in HTML would let anyone spend your quota. Capture the image on your server, store the bytes somewhere public, and put that stable URL in og:image.
Can I use Screenshotly's storage URL as my og:image?
Not for long. With storage enabled, the API returns a signed link that expires after 24 hours. Use it to download the file if you like, but host the image in your own bucket or CDN for anything that will be shared.
What size should a dynamic OG image be?
1200×630 pixels. Meta recommends images of at least 1200×630 at close to a 1.91:1 ratio, and LinkedIn lists 1200×627 as its minimum with a 1.91:1 recommended ratio. A 1200×630 template captured at deviceScaleFactor 1 satisfies both.
Why does my updated OG image still show the old version?
Platforms cache images by URL. Meta's documentation says to use a new URL for a new image. Put a content hash in the file name so every change produces a new URL, then refresh the page in Meta's Sharing Debugger or LinkedIn's Post Inspector. Existing posts may keep the old preview.
Which Screenshotly plan do I need?
Everything in this guide uses fields available on the Free plan (width, height, fullPage, waitForSelector, format). The Free plan includes 100 captures in total, so a site with many pages or frequent edits will need a paid plan's monthly quota.
Ready to capture your first screenshot?
Get started with 100 free screenshots. No credit card required.