Next.js OG image: automatic share images for every post
A Next.js OG image for your blog: draw a 1200x630 share image with ImageResponse, embed a font, handle long titles and check it all with tests.
An OG image is the picture that appears when someone pastes the link of a post into Facebook, Slack or a chat app. In Next.js you create it for every post with an opengraph-image.tsx file and ImageResponse, drawing the title in JSX. Want the links of your blog to look better? Let's build it.
What happens when a link has no image on Facebook?
In the previous post, the blog got metadata, a sitemap and JSON-LD so Google understands every post. But visitors of a blog do not only come from Google. A friend pastes the link into a group chat, and if the post has no image, the app shows only a bare blue line of text that is very easy to scroll past.
The app takes that picture from the tag <meta property="og:image"> in the <head> of the page. The "og" stands for Open Graph, a standard introduced by Facebook that many other messaging apps also read. The standard is described at ogp.me.
The quickest way is to make one single image for the whole blog. That works, but every post pasted anywhere looks exactly the same, so the viewer cannot tell what each post is about. To get one image per post with its own title, without designing each one by hand, I let code draw the image. Next.js has a built-in tool for this, ImageResponse in next/og, and you can read its documentation for all the options.
A first try with the default font
I want you to be able to follow along without building a whole Next.js app, so I run ImageResponse directly with Node.js and write a PNG file that I can open. You need Node.js 22.18 or newer. Create a folder og-blog with the layout below (I cover the two files in the assets/fonts folder in a later section):
og-blog/
package.json
tsconfig.json
first-try.tsx
draw-images.tsx
assets/fonts/BeVietnamPro-SemiBold.ttf
assets/fonts/BeVietnamPro-ExtraBold.ttf
src/titles.ts
src/share-card.tsx
src/png.ts
src/share-card.test.ts{
"name": "blog-mini-10-og-image",
"private": true,
"type": "module",
"scripts": { "test": "vitest run" },
"dependencies": { "next": "16.4.4", "react": "19.3.1", "react-dom": "19.3.1" },
"devDependencies": { "@types/react": "^19.3.0", "tsx": "4.23.15", "vitest": "5.1.0" }
}tsx runs TypeScript files with JSX, and it needs to know which JSX style to use, so I add a small tsconfig.json. Then run npm install.
{
"compilerOptions": {
"jsx": "react-jsx",
"module": "esnext",
"moduleResolution": "bundler",
"target": "es2022",
"strict": true,
"skipLibCheck": true,
"allowImportingTsExtensions": true,
"noEmit": true
}
}I need three test titles. The first two are ordinary titles. The third is unusually long (209 characters), like when someone pastes a whole description into the title box, and that is the kind of input that breaks the design in the later sections.
// Three test titles: short, medium, and an unusually long one (209 characters, like when someone pastes a whole description into the title box).
export const TITLES = {
short: "Build a personal blog for $0",
medium: "Compress images before upload: from 8 MB to 400 KB",
long: "The complete guide from A to Z on building a personal blog with Next.js and Supabase, with author login, a safe editor, automatic image compression, a sitemap for Google and a share image for every single post",
};My first approach is as minimal as it can be: one div, text size 72, weight 800, and no embedded font.
// First attempt: no font embedded, a fixed font size. Run: npx tsx first-try.tsx
import { mkdir, writeFile } from "node:fs/promises";
import { ImageResponse } from "next/og";
import { TITLES } from "./src/titles.ts";
await mkdir("out", { recursive: true });
const image = new ImageResponse(
(
<div style={{ display: "flex", width: "100%", height: "100%", padding: "64px 72px", background: "#fff9f0", color: "#1b1433", fontSize: 72, fontWeight: 800, lineHeight: 1.12 }}>
{TITLES.medium}
</div>
),
{ width: 1200, height: 630 },
);
await writeFile("out/1-first-try.png", Buffer.from(await image.arrayBuffer()));
console.log("Wrote out/1-first-try.png");npx tsx first-try.tsxWrote out/1-first-try.pngOpen out/1-first-try.png and you see two things. First, the text looks thin even though I set fontWeight: 800. The default font of ImageResponse has only one weight, so other weights are ignored. Second, the image holds only the title: no blog name, no category, it looks like a blank sheet of paper.
There is one thing to put right. In the code of the Tech Notes blog there is a note that says the default font does not have Vietnamese diacritics, and that note easily makes a reader think this is the reason to embed a font. When I tried again for the Vietnamese edition of this post (13 November 2026, Next.js 16.4.4), I found that the default font draws even the stacked marks such as "ế", "ệ", "ữ" and "ặ" without any error. So that note needed correcting. The real reason to embed a font here is the weight and the identity of the blog, not the diacritics.
Embed a font and draw a complete card
I use Be Vietnam Pro, a font designed for Vietnamese that has the SIL Open Font License, so it can be used and bundled freely. You download the two files BeVietnamPro-SemiBold.ttf and BeVietnamPro-ExtraBold.ttf into the folder assets/fonts. ImageResponse accepts the formats ttf, otf and woff, and the documentation recommends ttf or otf because they are parsed faster than woff.
The file below is the main part of the post. It takes the title, a category label and a footer line, and returns an ImageResponse. There are three things to notice.
The font is read once at module level, because it does not depend on any request (the Next.js documentation does the same). Every div has display: "flex", because ImageResponse only supports flexbox and part of the CSS properties, so display: grid does not work. And the function titleFontSize makes the text smaller when the title is long, which I explain right after:
// The 1200x630 share image (Open Graph) of a post, drawn with ImageResponse of Next.js.
// Same idea as src/lib/og/render.tsx of the Tech Notes blog; in the real blog, this function is called from the file opengraph-image.tsx.
import { readFile } from "node:fs/promises";
import { join } from "node:path";
import { ImageResponse } from "next/og";
export const OG_SIZE = { width: 1200, height: 630 };
// The fonts do not depend on the request, so they are read once at module level (the way the Next.js documentation recommends).
const bold = await readFile(join(process.cwd(), "assets/fonts/BeVietnamPro-ExtraBold.ttf"));
const semibold = await readFile(join(process.cwd(), "assets/fonts/BeVietnamPro-SemiBold.ttf"));
/** The longer the title, the smaller the text, so it always fits in about three to five lines. */
export function titleFontSize(title: string): number {
if (title.length <= 40) return 72;
if (title.length <= 70) return 60;
return 50;
}
export type ShareCard = { title: string; label: string; footer: string };
export function drawShareCard({ title, label, footer }: ShareCard, fontSize: number = titleFontSize(title)) {
return new ImageResponse(
(
<div style={{ display: "flex", flexDirection: "column", justifyContent: "space-between", width: "100%", height: "100%", padding: "64px 72px", background: "#fff9f0", color: "#1b1433", fontFamily: "Be Vietnam Pro" }}>
<div style={{ display: "flex", flexDirection: "column", gap: 28 }}>
<div style={{ display: "flex", fontSize: 30, fontWeight: 800, color: "#6d4aff" }}>{label}</div>
<div style={{ display: "flex", fontSize, fontWeight: 800, lineHeight: 1.12, letterSpacing: -2 }}>{title}</div>
</div>
<div style={{ display: "flex", justifyContent: "space-between", fontSize: 28, fontWeight: 600 }}>
<div style={{ display: "flex", fontWeight: 800 }}>Tech Notes</div>
<div style={{ display: "flex", color: "#5b5470" }}>{footer}</div>
</div>
</div>
),
{
...OG_SIZE,
fonts: [
{ name: "Be Vietnam Pro", data: semibold, weight: 600, style: "normal" },
{ name: "Be Vietnam Pro", data: bold, weight: 800, style: "normal" },
],
},
);
}Now I have one function that draws the card. Next I try it with the three titles.
What does the image look like with a long title?
The script below draws three titles with the function above. To show why titleFontSize is needed, I deliberately add one run that forces size 72 on the long title. Each time it draws, the script prints the image size, the file size and the time. To check the dimensions without an image library, I read the start of the PNG file directly, where it records the width and the height:
// Read the width and the height from the start of a PNG file: 8 bytes of signature, then the IHDR chunk (width and height, 4 bytes each, big-endian).
const PNG_SIGNATURE = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
export function readPngSize(image: Buffer): { width: number; height: number } {
if (image.length < 24 || !image.subarray(0, 8).equals(PNG_SIGNATURE)) throw new Error("Not a PNG file");
return { width: image.readUInt32BE(16), height: image.readUInt32BE(20) };
}// Draw the share card for three titles, plus one forced 72px font size for the long title to show the problem. Run: npx tsx draw-images.tsx
import { mkdir, writeFile } from "node:fs/promises";
import { readPngSize } from "./src/png.ts";
import { TITLES } from "./src/titles.ts";
import { drawShareCard, titleFontSize } from "./src/share-card.tsx";
await mkdir("out", { recursive: true });
const info = (title: string) => ({ title, label: "WEB IN PRACTICE · Intermediate", footer: "9 min read" });
const targets = [
{ file: "2-short", title: TITLES.short, fontSize: titleFontSize(TITLES.short) },
{ file: "3-medium", title: TITLES.medium, fontSize: titleFontSize(TITLES.medium) },
{ file: "4-long-forced-72", title: TITLES.long, fontSize: 72 }, // wrong on purpose: the font size does not change with the length
{ file: "5-long", title: TITLES.long, fontSize: titleFontSize(TITLES.long) },
];
for (const { file, title, fontSize } of targets) {
const start = performance.now();
const image = Buffer.from(await drawShareCard(info(title), fontSize).arrayBuffer());
const ms = Math.round(performance.now() - start);
await writeFile(`out/${file}.png`, image);
const { width, height } = readPngSize(image);
console.log(`out/${file}.png`.padEnd(28), `${String(title.length).padStart(3)} chars, text ${fontSize}px, ${width}x${height}, ${(image.length / 1024).toFixed(1)} KB, ${ms} ms`);
}npx tsx draw-images.tsxout/2-short.png 28 chars, text 72px, 1200x630, 39.6 KB, 318 ms
out/3-medium.png 50 chars, text 60px, 1200x630, 47.5 KB, 27 ms
out/4-long-forced-72.png 209 chars, text 72px, 1200x630, 89.7 KB, 37 ms
out/5-long.png 209 chars, text 50px, 1200x630, 83.6 KB, 38 msAll four images are 1200x630 and weigh under 100 KB. The first draw took 318 ms because the renderer has to start up; the later ones took only 27 to 38 ms. The images themselves are what is worth looking at. out/2-short.png and out/3-medium.png look good: a purple category label at the top, a bold title, and the blog name and reading time at the bottom.
The image out/4-long-forced-72.png is a small disaster. A 209-character title at size 72 takes more than six lines, runs off the bottom edge of the image, cuts the last visible line in half, and pushes the footer with the name "Tech Notes" completely out of the picture. An image like that would sit on somebody's Facebook.
The function titleFontSize fixes this in the simplest way: a title up to 40 characters uses size 72, up to 70 characters uses size 60, and anything longer uses 50. At size 50, the same 209-character title fits in five lines in out/5-long.png, and the footer is intact. The thresholds 40 and 70 are numbers I tuned by eye for this card layout, not any standard. If you change the font or the margins, you should try again.
There is another way, which is to cut the title at a maximum length and add "…". I have not chosen it, because in my opinion a title cut off in the middle looks worse than a title in smaller text.
How do you attach it in Next.js?
In a Next.js app you do not call drawShareCard from a script; you put a file named opengraph-image.tsx next to the post page. According to the documentation of opengraph-image, Next.js adds the og:image tags to the <head> of the page by itself, with the width, the height, the image type and the description if you export alt. In Next.js 16, params is a Promise, so you must await it. The code below lives in the Next.js app, not in the demo folder, and I assume that a function getPost(slug) fetches the post from wherever you store it (Supabase, Markdown files...):
import { OG_SIZE, drawShareCard } from "@/lib/share-card";
import { getPost } from "@/lib/posts"; // depends on where you store posts
export const alt = "Share image of the post";
export const size = OG_SIZE;
export const contentType = "image/png";
export default async function Image({ params }: { params: Promise<{ slug: string }> }) {
const { slug } = await params;
const post = await getPost(slug);
return drawShareCard({ title: post.title, label: post.topic, footer: `${post.readingMinutes} min read` });
}Also according to the documentation, the image is generated at build time and stored (statically optimized), unless you use data or APIs that are only available at request time. That means each post costs one draw instead of being redrawn for every viewer. In the Tech Notes blog, this file also handles the case where the post is not found (it returns the default image of the whole blog), and it picks the color and icon by the category of the post.
The wrong assumptions of this very blog
The first two stories are in the Git history of this blog, and they resemble the lesson of the previous post: metadata from several levels is not merged the way we assume.
The first story is the commit 8ccc85d of 4 November 2026. Pages that set their own Open Graph data (such as the list page and the about page) made the default share image of the whole blog disappear, so at that moment only the posts had an image. The fix was for those pages to name the default image explicitly.
The second story is the commit 17a2d49 of 11 November 2026. The English version /en still used a default image that had only Vietnamese text. The fix was to take the text on the image from a dictionary per language, and every language other than Vietnamese has its own image address.
The third story is the font note above, which sat in the code for a while before anyone tested it again. Every story starts with an assumption that was not checked.
Check with tests, and only then trust
I wrote five tests for the functions in this post, and they run with vitest. The tests check that the font size changes exactly at the boundaries of 40 and 70 characters, that the returned image is a PNG, that every title (including the 209-character one) gives a 1200x630 image, that the image is lighter than 200 KB, and that the function that reads the size refuses data that is not a PNG. Here is the full version:
import { describe, expect, test } from "vitest";
import { readPngSize } from "./png.ts";
import { drawShareCard, titleFontSize } from "./share-card.tsx";
import { TITLES } from "./titles.ts";
const info = (title: string) => ({ title, label: "WEB IN PRACTICE · Intermediate", footer: "9 min read" });
const draw = async (title: string) => {
const response = drawShareCard(info(title));
return { response, image: Buffer.from(await response.arrayBuffer()) };
};
describe("titleFontSize", () => {
test("the longer the title, the smaller the text, changing exactly at 40 and 70 characters", () => {
expect([40, 41, 70, 71].map((n) => titleFontSize("a".repeat(n)))).toEqual([72, 60, 60, 50]);
});
});
describe("drawShareCard", () => {
test("returns a PNG with the right content type", async () => {
const { response } = await draw(TITLES.medium);
expect(response.status).toBe(200);
expect(response.headers.get("content-type")).toBe("image/png");
});
test("every title (including the 209-character one) gives a 1200x630 image", async () => {
for (const title of Object.values(TITLES)) {
const { image } = await draw(title);
expect(readPngSize(image)).toEqual({ width: 1200, height: 630 });
}
});
test("the image is lighter than 200 KB (many times under the 8 MB limit of Facebook)", async () => {
for (const title of Object.values(TITLES)) {
const { image } = await draw(title);
expect(image.length).toBeLessThan(200 * 1024);
}
});
});
describe("readPngSize", () => {
test("rejects data that is not a PNG", () => {
expect(() => readPngSize(Buffer.from("this is not an image, just some text, okay"))).toThrow("Not a PNG file");
});
});npx vitest run Test Files 1 passed (1)
Tests 5 passed (5)These tests cannot see whether the image is beautiful, so I still have to open the PNG file and look, as I did in the sections above. They only keep what can be measured (size, file weight, font size) from getting worse after later edits.
There are two more limits you should know. First, the Next.js documentation says that ImageResponse has a bundle size limit of 500 KB, counting the JSX, the CSS, the fonts and the images. My two fonts weigh about 270 KB, so there is room left, but adding a few more fonts gets close.
Second, for an image that has already been shared, Facebook usually keeps the preview it fetched. According to the guides I read, their Sharing Debugger has a button to fetch the page information again (Scrape Again). I did not try this on a real blog in this post, so try it yourself with one of your links.
How do you know who is reading which post?
By now every post of the blog has its own picture when it is shared. But when links start travelling around chat apps and Facebook, I again do not know which posts are read a lot and which nobody opens. How to measure reads without tracking the readers is the job of the next posts.
You can follow the whole journey in Build a blog with Next.js + Supabase. If you want to remember the part about light images, the post on compressing images before upload has the measurements, and the questions about Next.js are in the interview question bank.