•5 min read

OG image API: one template, a social card for every page

An OG image API turns a page title into a 1200 × 630 social card from a URL. The approaches compared, keeping it safe in public HTML, and Next.js and Nuxt code.

apiog-imagesseotutorials

An OG image API takes one card design and one page's data (title, author, category) and returns a 1200 × 630 image for that page. You point the page's og:image tag at it, and every link someone shares shows its own preview instead of the same generic fallback.

This post compares the three ways to generate OG images, then shows the version where the meta tag itself is the integration: no serverless function, no build step, and a URL that is safe to put in public HTML.

What an OG image API does

When someone shares a link on LinkedIn, X, Slack or iMessage, the platform fetches the page and reads one tag:

<meta property="og:image" content="https://yoursite.com/og/pricing.png">

Whatever image that URL returns is the card. If every page points at the same fallback image, every share looks the same, and a reader scrolling past has no reason to stop on the one about pricing versus the one about your changelog.

An OG image API fixes that by making the image a function of the page. The request carries the title; the response is the picture. For dimensions per platform and the full list of meta tags, see the OG image size guide. This post is about generating the image.

Three ways to generate OG images

ApproachHow it worksGood atCosts you
Serverless functionA route in your app draws the card with a canvas or JSX-to-image libraryFull control in codeCode, a deploy, a framework that supports it, layout written in CSS
Build-time scriptA script screenshots a page per post during the buildWorks with any static hostSlower builds, cards go stale until the next build
Template APIYou design the card in an editor; a URL renders it with the page's dataNo code to host, works on any platform that lets you set a meta tagDesigns live in the editor, not your repo; a first render takes longer than a cached file

If your team wants the card layout in the codebase, reviewed like any component, a serverless function is the right call. If you want a designer (or a marketer) to own the card and engineering to own one line in the <head>, a template API is less to maintain.

The rest of this post is the template API route.

Design the template once

In bannx you build the card on a 1200 × 630 canvas in the editor. The parts that change per page become variables: a title bound to the headline, an author bound to the byline, maybe a kicker for the category. Name the variables whatever you like; the API matches them by name. See variables for declaring them. Colours, logo and fonts can come from a brand kit instead of being fixed on the canvas, which matters later if you run cards for more than one brand (brands).

Publish the template when it looks right. API renders use the published version.

The meta tag is the API

Every template can be rendered from a URL alone with GET /api/v1/templates/:templateId/render. Variables go in the query string, and the image comes back in the response body:

<meta property="og:image"
  content="https://bannx.com/api/v1/templates/TEMPLATE_ID/render?title=Pricing+that+scales&author=Ada&format=png&api_token=RENDER_ONLY_KEY">

Any query key that isn't a render option (format, scale, variation, brand and so on) is treated as a variable, so title and author fill the template's variables of the same name.

A key in a URL is readable by anyone who views the page source. That's why api_token only accepts a render-only key: one minted under Settings → Space → Developers with the Template Render API scope and no MCP tools. Any other key in a URL is refused with 403. If a render-only key leaks, it can render your space's templates and nothing else. See authentication.

That's fine for an internal tool or a quick test. For public pages, though, a leaked render-only key still lets anyone render any title they like on your account. The next section closes that gap.

Make it safe for public HTML: signed URLs

A signed URL has no key in it. It looks like this:

<meta property="og:image"
  content="https://bannx.com/r/TEMPLATE_ID?author=Ada&title=Pricing%20that%20scales&sig=SIGNATURE">

The sig is an HMAC over the template ID and every parameter, made with your space's signing secret. Anyone can open the URL. Nobody can change title= without the signature failing with 403. That's exactly the property an og:image needs.

Each distinct signed URL renders once, on its first open. After that it's served from storage with a one-year immutable cache header, so the second, hundredth and thousandth crawler hit don't render anything.

Mint them in bulk

If you have a list of pages (a sitemap, a CMS export, a database query), sign up to 500 at a time with POST /api/v1/templates/:templateId/signed-urls. This needs a Bearer key with the template.render scope, called from your server or a script, never the browser:

curl -X POST https://bannx.com/api/v1/templates/TEMPLATE_ID/signed-urls \
  -H "Authorization: Bearer $BANNX_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "rows": [
      { "variables": { "title": "Pricing that scales", "author": "Ada" } },
      { "variables": { "title": "Changelog: October", "author": "Grace" } }
    ],
    "options": { "format": "png" }
  }'

The response lists one URL per row, in order:

{
  "templateId": "TEMPLATE_ID",
  "published": true,
  "urls": [
    { "url": "https://bannx.com/r/TEMPLATE_ID?…&sig=…", "path": "/r/…", "variables": { "title": "Pricing that scales", "author": "Ada" } }
  ]
}

Signing doesn't render anything. published: false means the URLs will return 404 until you publish the template.

The same call from Node, chunked for a long page list, writing a slug → URL map you can read at build time:

import { writeFile } from "node:fs/promises";

const TEMPLATE_ID = process.env.OG_TEMPLATE_ID;
const pages = await loadPages(); // [{ slug, title, author }, …] from your CMS or sitemap

const ogUrls = {};
for (let i = 0; i < pages.length; i += 500) {
  const chunk = pages.slice(i, i + 500);
  const res = await fetch(`https://bannx.com/api/v1/templates/${TEMPLATE_ID}/signed-urls`, {
    method: "POST",
    headers: {
      Authorization: `Bearer ${process.env.BANNX_API_KEY}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      rows: chunk.map((p) => ({ variables: { title: p.title, author: p.author } })),
      options: { format: "png" },
    }),
  });
  if (!res.ok) throw new Error(`Signing failed: ${res.status} ${await res.text()}`);
  const { urls } = await res.json();
  urls.forEach((u, j) => (ogUrls[chunk[j].slug] = u.url));
}

await writeFile("og-urls.json", JSON.stringify(ogUrls, null, 2));

Or sign offline

If your pages are rendered on a server, you can skip the API call and sign each URL where you build the page. Owners and admins find the space's signing secret on the template's URL tab, under Signing secret. The signature is:

sig = base64url( HMAC-SHA256( secret, templateId + "\n" + canonicalQuery ) )

canonicalQuery is every parameter except sig, keys sorted, each key=value percent-encoded per RFC 3986 (encodeURIComponent plus !'()*), joined with &. Leave format out for PNG. As a helper:

// lib/og.ts (server only: the secret must never reach the browser)
import { createHmac } from "node:crypto";

const enc = (s: string) =>
  encodeURIComponent(s).replace(/[!'()*]/g, (c) => "%" + c.charCodeAt(0).toString(16).toUpperCase());

export function ogImageUrl(vars: Record<string, string>) {
  const templateId = process.env.OG_TEMPLATE_ID!;
  const query = Object.keys(vars).sort().map((k) => `${enc(k)}=${enc(vars[k])}`).join("&");
  const sig = createHmac("sha256", process.env.BANNX_SIGNING_SECRET!)
    .update(`${templateId}\n${query}`)
    .digest("base64url");
  return `https://bannx.com/r/${templateId}?${query}&sig=${sig}`;
}

Rotating the secret (Rotate, next to it) invalidates every URL signed so far. Add exp (unix seconds) to a URL if you want it to stop rendering after a date; it's signed like any other parameter.

More signed-URL patterns (email, CRM merge fields, badges) are in signed image URLs.

Framework snippets

All of these call the ogImageUrl helper above on the server, so the signing secret stays there.

Next.js (App Router)

// app/blog/[slug]/page.tsx
import { ogImageUrl } from "@/lib/og";

export async function generateMetadata({ params }) {
  const { slug } = await params;
  const post = await getPost(slug);
  return {
    openGraph: { images: [ogImageUrl({ title: post.title, author: post.author })] },
    twitter: { card: "summary_large_image" },
  };
}

Nuxt

Page components also run in the browser, so sign in a server route and fetch the URL. useFetch sends the result in the page payload, so the browser never recomputes it.

// server/api/og/[slug].get.ts
import { ogImageUrl } from "~~/lib/og";

export default defineEventHandler(async (event) => {
  const post = await getPost(getRouterParam(event, "slug"));
  if (!post) throw createError({ statusCode: 404 });
  return { url: ogImageUrl({ title: post.title, author: post.author }) };
});
// pages/blog/[slug].vue, <script setup lang="ts">
const route = useRoute();
const { data: og } = await useFetch(`/api/og/${route.params.slug}`);
useSeoMeta({
  ogImage: () => og.value?.url,
  twitterCard: "summary_large_image",
  twitterImage: () => og.value?.url,
});

Astro

Astro frontmatter runs at build time (or on the server), never in the browser:

---
// src/layouts/Post.astro
import { ogImageUrl } from "../lib/og";
const { title, author } = Astro.props;
const og = ogImageUrl({ title, author });
---
<head>
  <meta property="og:image" content={og} />
  <meta name="twitter:card" content="summary_large_image" />
  <meta name="twitter:image" content={og} />
</head>

Plain HTML, Webflow, Ghost, Shopify

No server code at all: run the bulk script once (or mint a single link from the template's URL tab), then paste each URL into the page's custom OG image or head code field.

<meta property="og:image" content="https://bannx.com/r/TEMPLATE_ID?author=Ada&title=Pricing%20that%20scales&sig=SIGNATURE">
<meta property="og:image:width" content="1200">
<meta property="og:image:height" content="630">
<meta name="twitter:card" content="summary_large_image">

One card, every platform

The OG card is usually not the only size you need. The same template can render other sizes without saving anything, by passing size:

curl -X POST https://bannx.com/api/v1/templates/TEMPLATE_ID/render \
  -H "Authorization: Bearer $BANNX_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"format":"png","size":"story","fit":"reflow","variables":{"title":"Pricing that scales"},"raw":true}' \
  -o story.png
  • size takes a preset id (og, story, instagram-post, leaderboard, …), a "1200x630" string, or { "width", "height" }.
  • fit: "reflow" (the default) re-lays the design out the way resizing the artboard in the editor does: layers pinned with constraints keep their margins, and auto-layout frames rewrap. fit: "scale" shrinks the whole design to fit and letterboxes it, which is the safer choice for a template built with fixed pixel positions.
  • size and fit work on GET renders (?size=og&fit=scale) and are signed options on signed URLs too.
  • If you've saved design variations on the template (a dark version, a square layout), pass variation with the saved id.

Details in rendering at another size.

Running cards for several brands? Pass brand (a brand id, name or website URL from your space) and the same template renders in that brand's colours, logo and fonts, for that render only. On a signed URL, the brand is part of what's signed. An agency can keep one card design for every client.

Caching, speed and republishing

What to expect once it's live:

  • First open renders, every later open is a file. A signed URL renders the first time a crawler or browser fetches it, then streams the stored image with Cache-Control: public, max-age=31536000, immutable and an ETag. GET renders with a key are cached for 60 seconds.
  • The first open is the slow one. A render has to queue, possibly start a worker, load fonts and images, draw and encode. Every render response carries a standard Server-Timing header (and x-render-ms) with those phases, so your browser's devtools show exactly where the time went. If you want the first crawler hit to be instant, open each new URL once when you publish the page.
  • Republishing updates existing cards. Publish a new version of the template and existing signed URLs pick up the new design on their next open, rendering once more.
  • Changing a title changes the URL. A new title is a new query string, so it's a new image. Platforms also cache previews by URL, which works in your favour: a new URL is a fresh fetch.
  • Unpublished templates return 404 on signed URLs, so publish before the page goes live.

Is bannx the right fit?

It fits when the card is a design problem more than a code problem: you want a designer to own the layout, brand colours to stay in sync, and engineering to own a single helper function. It also fits when your site runs on a platform where you can set a meta tag but can't deploy a function.

It's not the right fit if you want the card layout defined in HTML and CSS inside your repo. bannx renders from a design canvas, not from markup.

To try it, start from an OG template on bannx.com, change the headline, and copy the signed link from the template's URL tab. The API tab has the same render as a POST request if you would rather call it from a server.

FAQ

Vercel OG or Satori, or a template API?

Vercel OG and Satori turn JSX and a subset of CSS into an image inside your own function. They're a good choice if your team wants the layout in code and you're already on a framework and host that support them. A template API moves the layout into an editor and the integration into a URL, so it works on any stack, including ones with no server code at all. The trade is control in code versus less code to own.

What happens when a page title changes?

The URL changes with it, so the next share fetches a new image. The old URL still works and still returns the old card from cache, which is harmless.

How do I test the card before sharing?

Open the image URL in a browser first: if it shows the card, the render works. Then run the page through each platform's own post inspector (LinkedIn and Facebook both have one) to check it reads the tags and to refresh a stale preview.

What size should the template be?

1200 × 630. The OG image size guide has the per-platform breakdown.

Can I use WebP?

Signed URLs render png (the default) or webp. PNG is the safest choice for og:image, since not every platform's crawler accepts WebP.