Maintain an Elegant Open Graph System
A scalable, consistent architecture for Open Graph metadata optimized for the messaging-first share economy.
- Path
- blueprints/Maintain-an-Elegant-Open-Graph-System.md
- Authors
- Michael Staton
- Augmented with
- Claude Code
- Tags
- Open-Graph · SEO · Metadata · Social-Sharing · Messaging
[!note] Share images: tall first, per page, built in the site (updated 2026-11-19) We assume a link is shared through iMessage or WhatsApp, so the tall 1080×1440 card is the default
og:imageon every site. The wide 1200×630 card goes intwitter:imagefor X, and can be routed to LinkedIn, Bluesky and Discord at the edge (see Which Image Each Platform Gets). Never twoog:imagetags. For building the cards themselves, see [[Share-Every-Page-and-Section-With-Its-Own-OG-Image]]: every page gets its own card, rendered at build time from its content. Live on cathode-site, edviro-blog and fullstack-vc.
Why This Matters: The Messaging-First Share Economy
The world runs on share buttons. When someone taps “Share” on mobile and sends a link via iMessage, WhatsApp, LinkedIn DM, Slack, or Discord, the link preview that appears IS your brand’s first impression.
This is now more important than traditional SEO for many businesses:
- iMessage/WhatsApp are how people share interesting content with friends, family, and colleagues
- LinkedIn is where B2B relationships form and professional content spreads
- Slack/Discord are where teams discover tools and resources
- Email clients increasingly render rich link previews
A broken or missing preview means your content looks unprofessional, untrustworthy, or simply gets ignored. A compelling preview drives clicks.
This blueprint ensures every page on every site produces rich, accurate, platform-optimized previews.
Objectives
- Implement an elegant, understandable, usable system for codifying and improvising Open Graph metadata at a per-page or per-collection or per-shareable-content level (any level the developers or marketers need).
- Optimize for messaging apps first (WhatsApp, iMessage, LinkedIn), not just traditional social.
- Centralize defaults while allowing clean per-page overrides.
- Keep metadata rendering consistent in one place (layout), not scattered.
- Support dynamic routes, content collections, and multi-brand needs.
- Integrate structured data (JSON-LD) alongside Open Graph.
- Enable optional dynamic OG image generation without complicating most pages.
Guiding Principles
- One source of truth for defaults and types
- Small, composable helpers that return ready-to-render meta tags
- Pages provide only the minimum context (title/description/image/url); everything else is inferred
- Layout owns actual
<meta>and canonical rendering for consistency - Always use absolute URLs — messaging apps require them; relative paths break previews
- Respect character limits — platforms truncate aggressively
Override Hierarchy
The system should be approachable at every level of the organization:
| Level | Who Uses It | What They Do |
|---|---|---|
| Site defaults | Developer (once) | Set SITE_SEO config and forget — 80% of pages are covered automatically |
| Collection defaults | Developer | Define defaults per content type (blog posts get article type, team pages get profile type) |
| Page overrides | Developer or Marketer | High-value landing pages get custom titles, descriptions, images via props or frontmatter |
| Frontmatter fields | Marketer or Content Author | Specify banner_tall_image, banner_image, description directly in markdown — no code changes needed |
The goal: A marketer should be able to control share previews by editing frontmatter. A developer should be able to set sensible defaults and walk away. Neither should need to understand the other’s domain.
Platform-Specific Considerations
Different platforms render previews differently. Design for the lowest common denominator, then enhance.
- Primary concern: Aggressive caching. WhatsApp caches previews for extended periods.
- Image: Uses
og:image. Gets the tall card. Small previews crop a square from its middle (see below). - Title: Uses
og:title. Truncates around 65 characters - Description: Uses
og:description. Truncates around 100 characters - Cache busting: Nearly impossible. Change the URL or wait. Adding query params like
?v=2can help force re-fetch. - Requirement:
og:imageMUST be an absolute URL with HTTPS - File size: Keep
og:imagewell under 300 KB. Over that, WhatsApp commonly shows the card with no image at all, and nothing tells you why. A 1200x630 PNG of a photographic background easily passes it (humain-web’s was 367 KB); the same image as JPEG at quality ~85 is ~45 KB. - Small previews crop to a centred square. Keep the wordmark and headline in the middle third so the thumbnail still reads.
iMessage (iOS/macOS)
- Image: Uses
og:image. Large preview on iOS 17+ - Title: Uses
og:title - Description: Uses
og:description - Behavior: Generally respects meta tags well; caches moderately
- Fallback: Will attempt to generate preview from page content if OG tags missing
- Testing: Previews are cached per conversation. To see a changed image, paste the link into a conversation it has never been sent to.
- Primary use case: B2B content, professional sharing, company pages
- Image: Uses
og:image. Displays at 1200x627 (crops to 1.91:1). Images smaller than 200x200 may not display. - Title: Uses
og:title. Truncates around 70 characters - Description: Uses
og:description. Truncates around 100 characters in feed - No LinkedIn-specific image tag. There is no
linkedin:image(unlike X’stwitter:image). LinkedIn reads only theog:*tags, so the only way to give it a different image from iMessage is the edge routing in Which Image Each Platform Gets. - Special tags: Recognizes
article:author,article:published_time - Cache: Caches aggressively. Use Post Inspector to force refresh.
Slack
- Image: Uses
og:image. Unfurls with large preview - Title: Uses
og:title - Description: Uses
og:description - Special: Recognizes
twitter:label1/twitter:data1for additional metadata display - Fallback: Falls back to page scraping if OG missing
Discord
- Image: Uses
og:image. Embeds with preview - Title: Uses
og:title - Description: Uses
og:description - Color: Recognizes
theme-colormeta tag for embed accent color - Special: Shows site name from
og:site_name
Twitter/X
- Card types:
summary,summary_large_image,player,app - Image: Uses
twitter:image(falls back toog:image) - Title: Uses
twitter:title(falls back toog:title). Max 70 chars - Description: Uses
twitter:description(falls back toog:description). Max 200 chars - Required:
twitter:cardto specify card type
- Image: Uses
og:image. Recommended 1200x630. Min 200x200, ideal 600x315+ - Title: Uses
og:title - Description: Uses
og:description - Special: Full OG protocol support including arrays and structured properties
Which Image Each Platform Gets
Every site keeps four share images. The frontmatter keys match the ones this blueprint’s own frontmatter uses:
| Variant | Key | Size | Where it goes |
|---|---|---|---|
| Tall banner | banner_tall_image |
1080×1440 (3:4) | og:image. The default for every page. |
| Banner | banner_image |
1200×630 (1.91:1) | twitter:image. Also the image routed to LinkedIn, Bluesky and Discord (below). |
| Square | square_image |
1200×1200 | No tag by default. Use it as twitter:image only on a page that sets twitter:card to summary. |
| Portrait | portrait_image |
1200×1500 (4:5) | No tag. It’s the image people post as an image (WhatsApp status, Instagram, a chat), so offer it as a download or on /brand-kit. |
Where the images come from depends on the page ([[Share-Every-Page-and-Section-With-Its-Own-OG-Image#Two kinds of share: content and site]]):
- Content pages and their sections use the cards the site renders from their metadata, tall and wide.
- Site and generic pages (home, about, collection indexes) can use an Ideogram illustration set, all four variants generated from one prompt.
The routing below is the same either way; only the images differ. So far the banner, and sometimes the square in on-site thumbnails, are the variants in regular use.
What plain HTML can and can’t do
A static page has two image slots, not four:
og:imageis read by iMessage, WhatsApp, LinkedIn, Bluesky, Discord, Slack and Facebook.twitter:imageis read by X, which falls back toog:imagewithout it.
So with static HTML alone, X gets the banner and everyone else gets the tall
banner. That’s right for iMessage and WhatsApp, which we design for. It’s a
compromise on LinkedIn, which crops og:image to 1.91:1. A tall card loses its
top and bottom there, so the middle band of the tall card has to carry the
title (the design rules in
[[Share-Every-Page-and-Section-With-Its-Own-OG-Image]] already put it there).
Don’t fix this with a second og:image. Clients pick an image and the size
tags inconsistently, and iMessage has been seen mixing the two into one broken
card ([[iPhone-Share-Previews-Conflate-the-Tall-and-Wide-Banners]]).
Routing the banner to LinkedIn, Bluesky and Discord (edge)
To give each platform its own image, decide at request time: look at the
crawler’s User-Agent and rewrite the og:image tags before the HTML goes
out. This needs an edge layer, either Vercel Routing Middleware or a Netlify
Edge Function. A GitHub Pages splash can’t do it and stays on the two static
slots.
| Crawler | Matches on | Gets |
|---|---|---|
| iMessage | facebookexternalhit and Twitterbot in the same string |
Tall banner (leave the HTML alone) |
WhatsApp/ |
Tall banner (leave the HTML alone) | |
| X | Twitterbot (without facebookexternalhit) |
Banner, via twitter:image (no rewrite needed) |
LinkedInBot |
Banner | |
| Bluesky | Cardyb |
Banner |
| Discord | Discordbot |
Banner |
| Anything else | Tall banner |
Rules:
- Test for iMessage first. Apple’s preview fetcher has sent a user agent
that contains both
facebookexternalhitandTwitterbot. A rule that checksTwitterbotfirst treats iMessage as X. - Rewrite the whole image block. Swap
og:image,og:image:width,og:image:height,og:image:typeandog:image:alttogether. A wide image declared as 1080×1440 is the same mismatch the second-og:imagerule avoids. - Keep the default HTML tall. Middleware touches only the crawlers in the table. Anything it doesn’t recognise, including people, gets the static page.
- Don’t cache the rewritten page for everyone. Send
Vary: User-Agent, or skip the CDN cache for bot requests, so a LinkedIn-shaped page never reaches iMessage. - Prove it before you trust it. Fetch the page with each user agent and
check the tags:
curl -sA 'LinkedInBot/1.0' https://site/page | grep og:image. Then post a real link in each app. LinkedIn’s Post Inspector shows its result directly.
[!warning] Not built yet (2026-11-19) No Astro Knots site runs this routing yet. The user-agent strings above come from public reports and need checking against our own access logs, and Bluesky’s and Discord’s use of a wide versus tall image needs a real post to confirm. The bot-detection list in [[Maintain-Confidential-Access-with-Persistent-Sessions-and-Auth-Telemetry]] is a starting point for the matcher.
Character Limits Reference
Design content to look good when truncated:
| Property | Safe Length | Platform Notes |
|---|---|---|
og:title |
60 chars | LinkedIn/Twitter truncate ~70, but 60 is safe everywhere |
og:description |
155 chars | WhatsApp ~100, LinkedIn ~100 in feed, Twitter ~200 |
og:site_name |
30 chars | Usually displayed in full |
Recommendation: Helper functions should warn or truncate when limits exceeded.
Recommended Structure
Project-level defaults and helpers
src/
├── config/
│ └── seo.ts # Site defaults, types, character limits
├── utils/
│ ├── og.ts # OG/Twitter meta tag builder
│ └── structured-data.ts # JSON-LD schema builders
└── layouts/
└── BaseLayout.astro # Renders meta, canonical, JSON-LD
Monorepo shared package (optional, as sites grow)
packages/seo/
├── types.ts # Shared interfaces
├── defaults.ts # Default builder factory
├── og.ts # OG helper
├── structured-data.ts # JSON-LD helpers
└── index.ts # Barrel export
Sites import from @knots/seo (following the copy-pattern workflow).
Site Defaults (Config)
Define one config object to drive defaults across pages.
// src/config/seo.ts
export interface SiteSEO {
siteName: string;
siteUrl: string; // REQUIRED: absolute URL for production (e.g., 'https://example.com')
twitterHandle?: string;
linkedInCompany?: string; // Company page URL for attribution
defaultTitle: string;
defaultDescription: string;
defaultImageTall: string; // og:image, 1080×1440. Absolute URL or path under /public
defaultImageWide: string; // twitter:image, 1200×630
defaultImageAlt: string;
themeColor?: string; // For Discord embeds, PWA, etc.
locale?: string; // e.g., 'en_US'
}
export interface ShareMetaInput {
title?: string;
description?: string;
imageTall?: string; // og:image (banner_tall_image)
imageWide?: string; // twitter:image (banner_image)
imageAlt?: string;
url?: string;
type?: 'website' | 'article' | 'profile' | 'product' | string;
// Article-specific (for blog posts, news)
publishedTime?: string; // ISO 8601
modifiedTime?: string; // ISO 8601
author?: string;
section?: string; // e.g., 'Technology', 'Business'
tags?: string[];
}
// Character limits for safety
export const CHAR_LIMITS = {
title: 60,
description: 155,
siteName: 30,
} as const;
export const SITE_SEO: SiteSEO = {
siteName: 'Your Site Name',
siteUrl: 'https://example.com', // Set from env in production
defaultTitle: 'Your Site Name',
defaultDescription: 'Your compelling site description under 155 characters.',
// Fallbacks only; prefer per-page cards (Share-Every-Page-and-Section-With-Its-Own-OG-Image)
defaultImageTall: '/og-default-tall.jpg',
defaultImageWide: '/og-default.jpg',
defaultImageAlt: 'Your Site Name logo and tagline',
twitterHandle: '@yourhandle',
themeColor: '#1a1a2e',
locale: 'en_US',
};
Helper API (Meta Composition)
Keep helpers small, predictable, and defensive about character limits.
// src/utils/og.ts
import { SITE_SEO, CHAR_LIMITS } from '../config/seo';
import type { ShareMetaInput } from '../config/seo';
interface MetaTag {
name?: string;
property?: string;
content: string;
}
/**
* Truncates string to limit, adding ellipsis if needed
*/
function truncate(str: string, limit: number): string {
if (str.length <= limit) return str;
return str.slice(0, limit - 1).trim() + '…';
}
/**
* Ensures URL is absolute. Prepends siteUrl if relative.
*/
function ensureAbsoluteUrl(url: string, siteUrl: string): string {
if (url.startsWith('http://') || url.startsWith('https://')) {
return url;
}
// Handle leading slash
const path = url.startsWith('/') ? url : `/${url}`;
return `${siteUrl.replace(/\/$/, '')}${path}`;
}
/**
* Builds Open Graph and Twitter meta tags from input.
* Falls back to site defaults for any missing values.
*/
export function buildOgMeta(input: ShareMetaInput = {}): MetaTag[] {
const siteUrl = SITE_SEO.siteUrl;
const title = truncate(input.title ?? SITE_SEO.defaultTitle, CHAR_LIMITS.title);
const description = truncate(input.description ?? SITE_SEO.defaultDescription, CHAR_LIMITS.description);
const imageTall = ensureAbsoluteUrl(input.imageTall ?? SITE_SEO.defaultImageTall, siteUrl);
const imageWide = ensureAbsoluteUrl(input.imageWide ?? SITE_SEO.defaultImageWide, siteUrl);
const imageAlt = input.imageAlt ?? SITE_SEO.defaultImageAlt;
const url = input.url ? ensureAbsoluteUrl(input.url, siteUrl) : undefined;
const type = input.type ?? 'website';
const meta: MetaTag[] = [
// Basic meta
{ name: 'description', content: description },
// Open Graph (primary - used by most platforms)
{ property: 'og:type', content: type },
{ property: 'og:site_name', content: SITE_SEO.siteName },
{ property: 'og:title', content: title },
{ property: 'og:description', content: description },
// One og:image only: the tall card, for iMessage and WhatsApp.
// Never add a second og:image; see "Which Image Each Platform Gets".
{ property: 'og:image', content: imageTall },
{ property: 'og:image:type', content: 'image/jpeg' },
{ property: 'og:image:width', content: '1080' },
{ property: 'og:image:height', content: '1440' },
{ property: 'og:image:alt', content: imageAlt },
];
// URL (required for proper canonical reference)
if (url) {
meta.push({ property: 'og:url', content: url });
}
// Locale
if (SITE_SEO.locale) {
meta.push({ property: 'og:locale', content: SITE_SEO.locale });
}
// Article-specific properties (for blog posts, news articles)
if (type === 'article') {
if (input.publishedTime) {
meta.push({ property: 'article:published_time', content: input.publishedTime });
}
if (input.modifiedTime) {
meta.push({ property: 'article:modified_time', content: input.modifiedTime });
}
if (input.author) {
meta.push({ property: 'article:author', content: input.author });
}
if (input.section) {
meta.push({ property: 'article:section', content: input.section });
}
if (input.tags?.length) {
input.tags.forEach(tag => {
meta.push({ property: 'article:tag', content: tag });
});
}
}
// Twitter Card: X reads twitter:image, so it gets the wide banner
meta.push({ name: 'twitter:card', content: 'summary_large_image' });
if (SITE_SEO.twitterHandle) {
meta.push({ name: 'twitter:site', content: SITE_SEO.twitterHandle });
}
meta.push({ name: 'twitter:title', content: title });
meta.push({ name: 'twitter:description', content: description });
meta.push({ name: 'twitter:image', content: imageWide });
meta.push({ name: 'twitter:image:alt', content: imageAlt });
// Theme color (for Discord embeds, PWA, browser chrome)
if (SITE_SEO.themeColor) {
meta.push({ name: 'theme-color', content: SITE_SEO.themeColor });
}
return meta;
}
/**
* Builds canonical URL from pathname
*/
export function buildCanonical(pathname: string): string {
return ensureAbsoluteUrl(pathname, SITE_SEO.siteUrl);
}
JSON-LD Structured Data
Why JSON-LD matters: While OG tags control social previews, JSON-LD/Schema.org structured data powers:
- Google rich results (breadcrumbs, FAQ, articles, products)
- Knowledge panels
- Voice assistant answers
- Future AI-powered search (GEO - Generative Engine Optimization)
Relationship to OG: They’re complementary. OG tags = social sharing. JSON-LD = search engines and AI.
// src/utils/structured-data.ts
import { SITE_SEO } from '../config/seo';
interface WebSiteSchema {
'@context': 'https://schema.org';
'@type': 'WebSite';
name: string;
url: string;
description?: string;
publisher?: OrganizationSchema;
}
interface OrganizationSchema {
'@context'?: 'https://schema.org';
'@type': 'Organization';
name: string;
url: string;
logo?: string;
sameAs?: string[]; // Social profiles
}
interface ArticleSchema {
'@context': 'https://schema.org';
'@type': 'Article' | 'BlogPosting' | 'NewsArticle';
headline: string;
description?: string;
image?: string | string[];
datePublished?: string;
dateModified?: string;
author?: PersonSchema | OrganizationSchema;
publisher?: OrganizationSchema;
mainEntityOfPage?: string;
}
interface PersonSchema {
'@type': 'Person';
name: string;
url?: string;
}
interface BreadcrumbSchema {
'@context': 'https://schema.org';
'@type': 'BreadcrumbList';
itemListElement: {
'@type': 'ListItem';
position: number;
name: string;
item?: string;
}[];
}
/**
* Builds WebSite schema (use on homepage)
*/
export function buildWebSiteSchema(): WebSiteSchema {
return {
'@context': 'https://schema.org',
'@type': 'WebSite',
name: SITE_SEO.siteName,
url: SITE_SEO.siteUrl,
description: SITE_SEO.defaultDescription,
};
}
/**
* Builds Organization schema
*/
export function buildOrganizationSchema(options: {
logo?: string;
socialProfiles?: string[];
} = {}): OrganizationSchema {
return {
'@context': 'https://schema.org',
'@type': 'Organization',
name: SITE_SEO.siteName,
url: SITE_SEO.siteUrl,
...(options.logo && { logo: options.logo }),
...(options.socialProfiles?.length && { sameAs: options.socialProfiles }),
};
}
/**
* Builds Article schema (for blog posts, news)
*/
export function buildArticleSchema(options: {
type?: 'Article' | 'BlogPosting' | 'NewsArticle';
headline: string;
description?: string;
image?: string;
datePublished?: string;
dateModified?: string;
authorName?: string;
authorUrl?: string;
url: string;
}): ArticleSchema {
const schema: ArticleSchema = {
'@context': 'https://schema.org',
'@type': options.type ?? 'Article',
headline: options.headline,
mainEntityOfPage: options.url,
};
if (options.description) schema.description = options.description;
if (options.image) schema.image = options.image;
if (options.datePublished) schema.datePublished = options.datePublished;
if (options.dateModified) schema.dateModified = options.dateModified;
if (options.authorName) {
schema.author = {
'@type': 'Person',
name: options.authorName,
...(options.authorUrl && { url: options.authorUrl }),
};
}
schema.publisher = {
'@type': 'Organization',
name: SITE_SEO.siteName,
url: SITE_SEO.siteUrl,
};
return schema;
}
/**
* Builds Breadcrumb schema
*/
export function buildBreadcrumbSchema(items: { name: string; url?: string }[]): BreadcrumbSchema {
return {
'@context': 'https://schema.org',
'@type': 'BreadcrumbList',
itemListElement: items.map((item, index) => ({
'@type': 'ListItem',
position: index + 1,
name: item.name,
...(item.url && { item: item.url }),
})),
};
}
/**
* Serializes schema to JSON-LD script tag content
*/
export function serializeSchema(schema: object): string {
return JSON.stringify(schema);
}
Layout Responsibilities
The base layout renders all meta tags, canonical, and JSON-LD consistently.
---
// src/layouts/BaseLayout.astro
import { buildOgMeta, buildCanonical } from '../utils/og';
import { buildWebSiteSchema, serializeSchema } from '../utils/structured-data';
import type { ShareMetaInput } from '../config/seo';
interface Props {
title: string;
meta?: ShareMetaInput;
jsonLd?: object | object[];
noIndex?: boolean;
}
const { title, meta = {}, jsonLd, noIndex = false } = Astro.props;
// Build OG meta tags
const ogMeta = buildOgMeta({
...meta,
url: meta.url ?? Astro.url.pathname,
});
// Build canonical URL
const canonical = buildCanonical(Astro.url.pathname);
// Prepare JSON-LD (array support for multiple schemas)
const schemas = jsonLd
? (Array.isArray(jsonLd) ? jsonLd : [jsonLd])
: [];
---
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>{title}</title>
<!-- Canonical -->
<link rel="canonical" href={canonical} />
<!-- Robots -->
{noIndex && <meta name="robots" content="noindex, nofollow" />}
<!-- OG and Twitter Meta -->
{ogMeta.map((m) => (
m.property
? <meta property={m.property} content={m.content} />
: <meta name={m.name} content={m.content} />
))}
<!-- JSON-LD Structured Data -->
{schemas.map((schema) => (
<script type="application/ld+json" set:html={serializeSchema(schema)} />
))}
<slot name="head" />
</head>
<body>
<slot />
</body>
</html>
Image Fallback Chain
Resolve the tall and the wide image separately, each with the same cascade:
- Page frontmatter —
banner_tall_image(tall) orbanner_image(wide) - The page’s generated card —
/og/tall/{key}.jpgor/og/wide/{key}.jpg, from [[Share-Every-Page-and-Section-With-Its-Own-OG-Image]] - Collection default — e.g. a blog-wide tall and wide pair
- Site default —
SITE_SEO.defaultImageTall/SITE_SEO.defaultImageWide
Never fall back to a hero photo: it’s rarely the right shape, size or format for a share card.
// Example: resolving images in a content page
const imageTall =
post.data.banner_tall_image ?? // Explicit override
cardUrl('tall', key) ?? // Generated per-page card
COLLECTION_DEFAULTS.blog.imageTall ??
SITE_SEO.defaultImageTall;
const imageWide =
post.data.banner_image ??
cardUrl('wide', key) ??
COLLECTION_DEFAULTS.blog.imageWide ??
SITE_SEO.defaultImageWide;
Tip: Create collection-specific defaults in your config:
// src/config/seo.ts
export const COLLECTION_DEFAULTS = {
blog: {
imageTall: '/og-blog-default-tall.jpg',
imageWide: '/og-blog-default.jpg',
type: 'article' as const,
},
team: {
imageTall: '/og-team-default-tall.jpg',
imageWide: '/og-team-default.jpg',
type: 'profile' as const,
},
// ...
};
Asset Guidance
Dimensions
The four variants and where each goes are in Which Image Each Platform Gets. In short:
- Tall banner (
og:image, the default): 1080×1440 (3:4). Keep the title in the middle band, because WhatsApp’s small preview and LinkedIn both crop from the middle. - Banner (
twitter:image): 1200×630 (1.91:1). - Square: 1200×1200. Only for a page using
twitter:cardsummary. - Portrait: 1200×1500 (4:5). Never a meta tag: it’s the version people post as an image. Render it from the same template as the others.
- Minimum: 600×315. Below that, some platforms show no image.
Format
- JPEG, always. Not WebP: some unfurlers don’t read it, and an image CDN that negotiates formats can serve a PNG several times larger (see the
open-graph-share-seo-geoskill). Not PNG: transparency renders as black on some platforms, and photo PNGs blow the size limit. og:image:typemust sayimage/jpegand match the bytes actually served.- File size: under 300 KB for WhatsApp (see above). Platforms accept up to 5 MB, but the messaging apps are the binding constraint.
Location
- Store in
public/for stable, predictable URLs - Use fingerprinted filenames for cache busting:
og-homepage-v2.jpg
Naming Convention
public/
├── og-default-tall.jpg # Site-wide fallback, og:image
├── og-default.jpg # Site-wide fallback, twitter:image
├── og-blog-default-tall.jpg # Blog collection default (tall)
├── og-blog-default.jpg # Blog collection default (wide)
└── og-[page-name]-tall.jpg # Hand-made page override, with its -wide pair
Generated per-page cards are served from build-time endpoints, not
public/: /og/tall/{key}.jpg and /og/wide/{key}.jpg.
Page Usage Patterns
Static Page
---
import BaseLayout from '../layouts/BaseLayout.astro';
import { SITE_SEO } from '../config/seo';
import { buildWebSiteSchema } from '../utils/structured-data';
const title = 'About Us | Your Company';
const description = 'Learn about our mission, team, and values.';
---
<BaseLayout
title={title}
meta={{
title,
description,
imageTall: '/og-about-tall.jpg',
imageWide: '/og-about.jpg',
}}
jsonLd={buildWebSiteSchema()}
>
<!-- page content -->
</BaseLayout>
Dynamic Route (Blog Post)
---
import { getEntry } from 'astro:content';
import BaseLayout from '../../layouts/BaseLayout.astro';
import { buildArticleSchema } from '../../utils/structured-data';
import { SITE_SEO, COLLECTION_DEFAULTS } from '../../config/seo';
const { slug } = Astro.params;
const post = await getEntry('blog', slug);
const title = post.data.title;
const description = post.data.description ?? post.data.excerpt;
// Resolved as in "Image Fallback Chain"
const imageTall = post.data.banner_tall_image ?? cardUrl('tall', `blog/${slug}`);
const imageWide = post.data.banner_image ?? cardUrl('wide', `blog/${slug}`);
const url = new URL(`/blog/${slug}`, SITE_SEO.siteUrl).toString();
const articleSchema = buildArticleSchema({
type: 'BlogPosting',
headline: title,
description,
image: imageWide,
datePublished: post.data.publishedDate?.toISOString(),
dateModified: post.data.updatedDate?.toISOString(),
authorName: post.data.author,
url,
});
---
<BaseLayout
title={`${title} | ${SITE_SEO.siteName}`}
meta={{
title,
description,
imageTall,
imageWide,
url,
type: 'article',
publishedTime: post.data.publishedDate?.toISOString(),
modifiedTime: post.data.updatedDate?.toISOString(),
author: post.data.author,
tags: post.data.tags,
}}
jsonLd={articleSchema}
>
<!-- post content -->
</BaseLayout>
Content Collection Frontmatter Standard
Standardize frontmatter across collections for predictable metadata:
---
title: "Your Post Title"
description: "A compelling description under 155 characters."
publishedDate: 2025-01-15
updatedDate: 2025-01-20
author: "Author Name"
heroImage: "/images/posts/my-post-hero.jpg" # On-page art, not a share image
# Optional overrides; without them the page uses its generated cards
banner_tall_image: "https://ik.imagekit.io/.../my-post_banner_tall.jpg" # og:image
banner_image: "https://ik.imagekit.io/.../my-post_banner.jpg" # twitter:image
square_image: "https://ik.imagekit.io/.../my-post_square.jpg"
portrait_image: "https://ik.imagekit.io/.../my-post_portrait.jpg"
tags:
- technology
- web development
---
Absolute URLs and Canonical
Configuration
// astro.config.mjs
export default defineConfig({
site: 'https://your-domain.com',
});
Before the domain points at the new site. A rebuild often goes live on a *.vercel.app address while the real domain still serves the old site. Hardcoding site: 'https://real-domain.com' then makes every og:image point at a domain that doesn’t have the file, so every preview shows no image. Derive it instead (humain-web’s astro.config.mjs):
site:
process.env.SITE_URL ??
(process.env.VERCEL_ENV === 'production' && process.env.VERCEL_PROJECT_PRODUCTION_URL
? `https://${process.env.VERCEL_PROJECT_PRODUCTION_URL}`
: 'https://www.real-domain.com'),
VERCEL_PROJECT_PRODUCTION_URL is the project’s shortest production domain, so once the custom domain is attached the tags follow it with no code change. SITE_URL overrides both.
Usage
// Always compute absolute URLs for OG tags
const canonical = new URL(Astro.url.pathname, Astro.site).toString();
const ogImage = new URL('/og-image.jpg', Astro.site).toString();
Critical: Messaging apps (especially WhatsApp) REQUIRE absolute HTTPS URLs. Relative paths will break previews.
Dynamic OG Image Generation
The Problem with Custom Images
Custom image overrides exist — marketers can always specify banner_tall_image and banner_image in frontmatter to use a bespoke graphic. But this approach doesn’t scale:
- Creating custom OG images for every blog post, team member, or product page is time-consuming
- Designers become bottlenecks
- Quality becomes inconsistent
- Many pages simply go without proper images
The GitHub Approach: Branded Templates + Dynamic Text
GitHub solved this elegantly. Every repository has a recognizable OG image:
- Consistent branded layout — same border, colors, typography
- Dynamic text — repo name, description, stats pulled in automatically
- Instantly recognizable — you know it’s a GitHub link before reading
This is the model to follow. Design 2-3 branded templates, then generate images dynamically by injecting page-specific text. The result:
- Every page gets a proper OG image automatically
- Brand consistency across hundreds of pages
- Zero designer involvement for routine content
- Custom overrides still available for hero campaigns
Implementation Approaches
| Approach | When to Use | Tools |
|---|---|---|
| Build-time | Finite, known content (blog, docs) | satori, @vercel/og, puppeteer |
| Runtime API | Dynamic/user-generated content | /api/og?title=... endpoint |
| Hybrid | Pre-generate key pages, runtime for long-tail | Combination |
Hero-Derived Share Images (headless Chrome, site-wide)
For a site that needs one excellent share card rather than one per page (a firm’s site, a landing page, a fund), the fastest route to on-brand is to render the hero itself: same background art, gradient, shade, wordmark and headline. It needs no new dependency, because it’s an HTML page photographed by the Chrome already on the machine.
Reference: sites/humain-web/scripts/share-image/.
scripts/share-image/
├── template.html # the hero, restated at fixed pixel sizes; #banner / #tall / #portrait pick the layout
└── render.sh # headless Chrome → PNG → ImageMagick → JPEG in public/og/
public/og/
├── share-tall.jpg # 1080x1440 — the og:image on every page
├── share-banner.jpg # 1200x630 — twitter:image
└── share-portrait.jpg # 1200x1500 — for posting as an image, never a meta tag
humain-web was built before tall-first: it ships the banner as
og:imageand its 1200×1500 “tall” is the portrait. Follow the layout above, not its current tags.
render() { # name width height
"$CHROME" --headless=new --disable-gpu --hide-scrollbars --force-device-scale-factor=1 \
--allow-file-access-from-files --virtual-time-budget=5000 \
--window-size="$2,$3" --screenshot="$TMP/$1.png" "$TEMPLATE#$1"
magick "$TMP/$1.png" -strip -quality 86 -sampling-factor 4:2:0 -interlace JPEG "public/og/share-$1.jpg"
}
render tall 1080 1440
render banner 1200 630
render portrait 1200 1500
Why Chrome rather than Satori here. Satori supports a subset of CSS: no mask, no color-mix(), limited background-size: cover, no layered absolutely-positioned art. A hero is usually exactly those things. Chrome renders the real CSS, so the template can reuse the hero’s own rules almost verbatim and the card can’t drift from the page. Satori stays the right tool for per-page cards generated at build or request time (below).
Rules that made it work:
- One template, a hash per layout.
template.html#bannerand#tallset a class on<body>; each size gets its own type scale. Two files would drift. - The wordmark as a mask, loaded from the site’s own SVG in
public/marks/, painted in the hero’s foreground colour. Same file the header uses. - Reference the site’s assets by relative path (
../../public/images/hero-bg.png) and pass--allow-file-access-from-files, so the card always uses the current art. - Fonts: load the brand faces from Google Fonts with
display=block, and give Chrome--virtual-time-budgetso they arrive before the screenshot. A fallback face in a share card is the most common silent failure. - JPEG out, for the 300 KB WhatsApp limit. humain-web’s are 44 KB and 93 KB.
- Centre everything. WhatsApp’s small preview is a centred square crop of the tall card.
- Show all three in
/brand-kitwith the regenerate command, so the next person changing the tagline knows the cards exist.
Wire the tall card in as og:image and the banner as twitter:image, with absolute URLs and the size hints, which let platforms lay out the card before downloading the image:
<meta property="og:image" content={shareTall} />
<meta property="og:image:secure_url" content={shareTall} />
<meta property="og:image:type" content="image/jpeg" />
<meta property="og:image:width" content="1080" />
<meta property="og:image:height" content="1440" />
<meta property="og:image:alt" content="Brand: headline." />
<meta name="twitter:card" content="summary_large_image" />
<meta name="twitter:image" content={shareBanner} />
Template Philosophy
Design templates that work with just a title. Everything else is optional enhancement:
┌─────────────────────────────────────────────────────────────────┐
│ │
│ [LOGO] [SITE NAME] │
│ │
│ ┌─────────────────────────────────────────────────────────┐ │
│ │ │ │
│ │ {{TITLE}} │ │
│ │ A Dynamic Title That Can Span Multiple Lines │ │
│ │ │ │
│ │ {{DESCRIPTION}} (optional, truncated) │ │
│ │ │ │
│ └─────────────────────────────────────────────────────────┘ │
│ │
│ {{AUTHOR}} · {{DATE}} · {{CATEGORY}} [BRAND MARK] │
│ │
└─────────────────────────────────────────────────────────────────┘
Practical Template: Branded Card (Satori/Vercel OG)
// src/pages/api/og.ts
import { ImageResponse } from '@vercel/og';
import type { APIRoute } from 'astro';
// Load fonts (do this once, cache the result)
const interBold = fetch(
new URL('../../assets/fonts/Inter-Bold.ttf', import.meta.url)
).then((res) => res.arrayBuffer());
const interRegular = fetch(
new URL('../../assets/fonts/Inter-Regular.ttf', import.meta.url)
).then((res) => res.arrayBuffer());
export const GET: APIRoute = async ({ request }) => {
const url = new URL(request.url);
// Extract params with sensible defaults
const title = url.searchParams.get('title') ?? 'Untitled';
const description = url.searchParams.get('description') ?? '';
const author = url.searchParams.get('author') ?? '';
const date = url.searchParams.get('date') ?? '';
const category = url.searchParams.get('category') ?? '';
const type = url.searchParams.get('type') ?? 'default'; // 'default' | 'article' | 'profile'
// Truncate for safety
const truncatedTitle = title.length > 80 ? title.slice(0, 77) + '...' : title;
const truncatedDesc = description.length > 120 ? description.slice(0, 117) + '...' : description;
// Load fonts
const [boldFont, regularFont] = await Promise.all([interBold, interRegular]);
return new ImageResponse(
(
<div
style={{
width: '100%',
height: '100%',
display: 'flex',
flexDirection: 'column',
padding: '60px',
backgroundColor: '#0f172a', // slate-900
color: '#f8fafc', // slate-50
fontFamily: 'Inter',
}}
>
{/* Header: Logo + Site Name */}
<div
style={{
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
marginBottom: '40px',
}}
>
{/* Replace with your logo - use base64 encoded SVG or hosted URL */}
<div
style={{
width: '48px',
height: '48px',
borderRadius: '8px',
backgroundColor: '#3b82f6', // blue-500
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
fontSize: '24px',
fontWeight: 700,
}}
>
L
</div>
<div
style={{
fontSize: '20px',
color: '#94a3b8', // slate-400
}}
>
yoursite.com
</div>
</div>
{/* Main Content Card */}
<div
style={{
flex: 1,
display: 'flex',
flexDirection: 'column',
justifyContent: 'center',
padding: '40px',
backgroundColor: '#1e293b', // slate-800
borderRadius: '16px',
border: '1px solid #334155', // slate-700
}}
>
{/* Category Badge (optional) */}
{category && (
<div
style={{
display: 'flex',
marginBottom: '20px',
}}
>
<span
style={{
padding: '6px 16px',
backgroundColor: '#3b82f6',
borderRadius: '9999px',
fontSize: '14px',
fontWeight: 600,
textTransform: 'uppercase',
letterSpacing: '0.05em',
}}
>
{category}
</span>
</div>
)}
{/* Title */}
<h1
style={{
fontSize: truncatedTitle.length > 50 ? '42px' : '56px',
fontWeight: 700,
lineHeight: 1.2,
margin: 0,
marginBottom: description ? '20px' : '0',
}}
>
{truncatedTitle}
</h1>
{/* Description (optional) */}
{truncatedDesc && (
<p
style={{
fontSize: '24px',
color: '#94a3b8',
lineHeight: 1.4,
margin: 0,
}}
>
{truncatedDesc}
</p>
)}
</div>
{/* Footer: Author, Date, Brand Mark */}
<div
style={{
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
marginTop: '30px',
}}
>
<div
style={{
display: 'flex',
gap: '16px',
fontSize: '18px',
color: '#64748b', // slate-500
}}
>
{author && <span>{author}</span>}
{author && date && <span>·</span>}
{date && <span>{date}</span>}
</div>
{/* Brand mark or tagline */}
<div
style={{
fontSize: '16px',
color: '#475569', // slate-600
}}
>
Your Brand Tagline
</div>
</div>
</div>
),
{
// The wide variant. Render the tall one (1080×1440) from a tall layout,
// not by stretching this one.
width: 1200,
height: 630,
fonts: [
{ name: 'Inter', data: boldFont, weight: 700 },
{ name: 'Inter', data: regularFont, weight: 400 },
],
}
);
};
Using the Template in Pages
// In your buildOgMeta helper or page
const ogImageUrl = new URL('/api/og', SITE_SEO.siteUrl);
ogImageUrl.searchParams.set('title', post.data.title);
ogImageUrl.searchParams.set('description', post.data.description ?? '');
ogImageUrl.searchParams.set('author', post.data.author ?? '');
ogImageUrl.searchParams.set('date', formatDate(post.data.publishedDate));
ogImageUrl.searchParams.set('category', post.data.category ?? '');
// Use ogImageUrl.toString() as the og:image value
Template Variants
Create multiple templates for different content types:
| Template | Use Case | Key Elements |
|---|---|---|
| Default | Homepage, landing pages | Logo, tagline, brand colors |
| Article | Blog posts, news | Title, author, date, category badge |
| Profile | Team pages, author pages | Photo placeholder, name, role |
| Product | Product pages | Product name, price, key feature |
Font Loading Best Practices
// Option 1: Bundle fonts (recommended for Vercel/Edge)
const font = fetch(new URL('./fonts/Inter-Bold.ttf', import.meta.url))
.then((res) => res.arrayBuffer());
// Option 2: Use system fonts (no loading required)
// 'system-ui', 'Segoe UI', 'Roboto', 'Helvetica Neue', 'Arial'
// Option 3: Google Fonts via URL (slower, may have CORS issues)
const font = fetch('https://fonts.gstatic.com/s/inter/v13/...')
.then((res) => res.arrayBuffer());
Dependencies
For dynamic OG image generation, you’ll need:
| Package | Purpose | Install |
|---|---|---|
satori |
Converts HTML/CSS-like structures to SVG | pnpm add satori |
sharp or @resvg/resvg-js |
Converts SVG to PNG/JPEG | pnpm add sharp or pnpm add @resvg/resvg-js |
@vercel/og (optional) |
All-in-one wrapper (includes satori + resvg) | pnpm add @vercel/og |
For Astro SSG (build-time generation):
pnpm add satori @resvg/resvg-js
Note on JSX vs Plain Objects: The code examples in this blueprint use JSX syntax (common in documentation) for readability. Satori accepts either:
- JSX (requires React/Preact or a JSX transform)
- Plain JavaScript objects (no dependencies beyond satori itself)
For Astro without React, use the plain object form:
// Plain object — no JSX compiler needed
const element = {
type: 'div',
props: {
style: { display: 'flex', background: '#0f172a', width: '100%', height: '100%' },
children: {
type: 'h1',
props: {
style: { color: 'white', fontSize: '48px' },
children: title
}
}
}
};
const svg = await satori(element, { width: 1200, height: 630, fonts });
const png = await sharp(Buffer.from(svg)).png().toBuffer();
Requirements & Best Practices
- Cache aggressively — CDN with 24hr+ TTL; same inputs = same output
- Fallback gracefully — If generation fails, fall back to static default image
- Keep it fast — Edge runtime preferred; avoid heavy computation
- Test across platforms — Validate with Facebook, LinkedIn, Twitter before launch
- Deterministic output — Same params must produce identical image (for caching)
Custom Override Escape Hatch
The dynamic system handles 95% of cases, but sometimes you need bespoke:
---
title: "Product Launch Announcement"
description: "Introducing our revolutionary new feature"
banner_tall_image: "/og/campaigns/product-launch-2025-tall.jpg" # Custom og:image
banner_image: "/og/campaigns/product-launch-2025.jpg" # Custom twitter:image
---
When banner_tall_image or banner_image is present in frontmatter, use it directly instead of the generated card. Supply both, or the page shows a custom card on one platform and the generated one on the rest. This gives marketers the escape hatch they need for hero campaigns without requiring it for every page.
Validation & Debugging
Debugging Checklist
- View page source — Confirm meta tags are in
<head> - Check absolute URLs — All
og:image,og:urlmust be absolute HTTPS - Verify image accessibility — Can you open the OG image URL directly?
- Test with validators — Use platform-specific tools below
Platform Validators
| Platform | Validator URL | Notes |
|---|---|---|
| https://developers.facebook.com/tools/debug/ | Also clears Facebook cache | |
| https://www.linkedin.com/post-inspector/ | Forces re-scrape | |
| Twitter/X | https://cards-dev.twitter.com/validator | Preview card appearance |
| Generic | https://metatags.io | Preview across platforms |
| Schema.org | https://validator.schema.org | Validate JSON-LD |
| Google Rich Results | https://search.google.com/test/rich-results | Test structured data |
Cache Busting
When previews show stale data:
- Facebook: Use Sharing Debugger “Scrape Again” button
- LinkedIn: Post Inspector “Refresh” button
- Twitter: Validator automatically re-fetches
- WhatsApp: Hardest to bust. Options:
- Wait (caches for hours/days)
- Change URL (add
?v=2query param) - Change
og:imageURL
CI/Automated Checks
Consider adding checks to catch missing metadata:
// Example: Playwright test for OG tags
test('homepage has required OG tags', async ({ page }) => {
await page.goto('/');
const ogTitle = await page.getAttribute('meta[property="og:title"]', 'content');
const ogImage = await page.getAttribute('meta[property="og:image"]', 'content');
const ogDesc = await page.getAttribute('meta[property="og:description"]', 'content');
expect(ogTitle).toBeTruthy();
expect(ogImage).toMatch(/^https:\/\//);
expect(ogDesc?.length).toBeLessThanOrEqual(155);
});
Performance & Caching
- Static images: Long
Cache-Control(1 year) with fingerprinted filenames - Dynamic endpoints: Short TTL (5min-1hr) with
stale-while-revalidate - CDN: Ensure OG images are served via CDN for fast unfurling
- Server-side only: Never compute OG meta on client; it must be in initial HTML
Governance & Maintenance
- Ownership: One team/component owns
SITE_SEOconfig and helpers - Review: OG metadata should be part of PR review for new pages
- Testing: Include preview testing in QA checklist
- Documentation: Keep this blueprint updated as platforms evolve
Migration Plan
- Audit current state — Check existing pages for OG coverage
- Introduce
SITE_SEOconfig — Centralize defaults - Add
buildOgMeta()helper — Replace scattered meta tag logic - Add
structured-data.ts— Implement JSON-LD for key pages - Update
BaseLayout.astro— Centralize rendering - Set
siteinastro.config.mjs— Enable absolute URLs - Add validation tests — CI checks for OG presence
- Test with validators — Verify all platforms render correctly
- Document per-collection defaults — Ensure consistent fallbacks
Checklist
Setup
-
SITE_SEOconfig defined with all required fields -
siteUrlset correctly for production environment -
buildOgMeta()helper implemented with truncation -
structured-data.tshelpers for JSON-LD -
BaseLayout.astrorenders meta, canonical, and JSON-LD
Per-Page
- Title under 60 characters
- Description under 155 characters
- Exactly one
og:image: the tall 1080×1440 JPEG, with matchingog:image:type, width and height -
twitter:imageis the wide 1200×630 JPEG - Both images under 300 KB
- Image URLs are absolute HTTPS
-
og:urlset to canonical URL - JSON-LD schema appropriate for content type
Content Collections
- Frontmatter schema includes
title,description, and optionalbanner_tall_image,banner_image,square_image,portrait_image - Collection defaults defined for fallback images
- Article metadata (dates, author) mapped to OG and JSON-LD
Validation
- Tested with Facebook Sharing Debugger
- Tested with LinkedIn Post Inspector
- Tested with Twitter Card Validator
- JSON-LD validated with Schema.org validator
- WhatsApp preview manually checked
-
og:imageunder 300 KB (JPEG) - iMessage checked in a conversation the link has never been sent to
Production
-
siteconfigured inastro.config.mjs, derived from the Vercel production domain until the real domain points at the site - OG images served via CDN with proper caching
- CI checks for OG tag presence (optional but recommended)