Custom OG Image Generator with Vercel’s Satori
Published: 2022-12-07
If you’re using Nextjs then you can leverage Vercel’s edge functions to create an OG image generator.
But what if you’re not using Nextjs? And what if you don’t want to use Vercel?
Well you’re in luck because I was trying to find a solution for OG image generation for a site (tinkering around in Astro)
Here’s the code to get started.
npm install satori satori-html sharp
Note: You can use other svg to png converters, however this one has few dependencies so it can be compiled with Esbuild. But you’re free to use whatever you like.
import satori from "satori";
import { html as toReactElement } from "satori-html";
import sharp from "sharp";
const fontFile = await fetch(
"https://og-playground.vercel.app/inter-latin-ext-700-normal.woff"
);
const fontData: ArrayBuffer = await fontFile.arrayBuffer();
const height = 630;
const width = 1200;
export const get = async ({ request }: any) => {
const html = toReactElement(
`<div>Hello World!</div>`
);
const svg = await satori(html, {
fonts: [
{
name: "Inter Latin",
data: fontData,
style: "normal",
},
],
height,
width,
});
const png = await sharp(Buffer.from(svg)).webp().toBuffer();
return new Response(png, {
headers: {
"content-type": "image/png",
},
});
};
There you go! All done, now you can use this on any cloud worker that supports node / sharp. This will work in Astro and it should work for any other node apps.
You’re free to try this out and see if it works for you!
I deployed my site on Vercel and it works perfectly with their Serverless functions (despite not being Nextjs)
See it for yourself here
If you’re interested in seeing how this all works keep reading.
Breakdown:
Vercel’s Satori library uses JSX/React to render SVGs. What we’ll do is convert that SVG into a .webp file so that it can be used for other purposes (like SEO og:image)
We can also pass in custom fonts. This example uses one that’s loaded from Vercel themselves. But you could load them from your site’s public folder for example.
I’ve also made the svg endpoint available if you’re interested, so you can see exactly how it works. Who knows, maybe with this library some new SVG SaaS could pop up?
Hope you enjoyed and got value from this. There are a lack of non-Nextjs tutorials for this library.
There’s also the free playground using Satori hosted by Vercel