Ana içeriğe atla

Open Graph (OG) Image Generation

Open Graph images can be used to display previews of pages when shared on social media sites such as Twitter/X, LinkedIn, Facebook, etc. Analog supports generating Open Graph images using API Routes.

Setup

First, install the necessary satori dependencies:

npm install satori satori-html sharp --save
info

sharp is a native module with platform-specific binaries. Analog automatically externalizes it during SSR and prerendering so that it resolves from node_modules at runtime instead of being bundled. Make sure sharp is installed as a project dependency (as shown above) when using image processing in server routes or prerendered pages.

Setting Up An API Route

Next, define an API route in the src/server/routes/api directory.

// src/server/routes/api/v1/og-images.ts
import { ImageResponse } from '@analogjs/content/og';
import { defineHandler } from 'h3';

export default defineHandler(async (event) => {
const fontFile = await fetch(
'https://og-playground.vercel.app/inter-latin-ext-700-normal.woff',
);
const fontData: ArrayBuffer = await fontFile.arrayBuffer();
const title = event.url.searchParams.get('title') ?? 'Hello World';

const template = `
<div tw="bg-gray-50 flex w-full h-full items-center justify-center">
<div tw="flex flex-col md:flex-row w-full py-12 px-4 md:items-center justify-between p-8">
<h2 tw="flex flex-col text-3xl sm:text-4xl font-bold tracking-tight text-gray-900 text-left">
<span>${title}</span>
</h2>
</div>
</div>
`;

return new ImageResponse(template, {
fonts: [
{
name: 'Inter Latin',
data: fontData,
style: 'normal',
},
],
});
});
  • The API route uses the ImageResponse class from the @analogjs/content/og sub-package.
  • Provide HTML that is rendered to a PNG.
  • Tailwind classes are supported, and optional.

Adding Open Graph Metadata

Open Graph images are registered through meta tags inside the HTML head tag.

<html>
<head>
<meta
property="og:image"
content="https://your-url.com/api/v1/og-images?title=Developer"
/>
<meta
name="twitter:image"
content="https://your-url.com/api/v1/og-images?title=Developer"
key="twitter:image"
/>
...
</head>
</html>

The meta tags can be set manually in the index.html or dynamically using Route Metadata