Generating OG Images for Zero Dollars
You can generate OG images for hundreds of articles without paying for an API.
I use Playwright to screenshot HTML templates. It gives you full CSS control and requires no external keys.
If you run a static site, this is the best way to handle batch image generation.
Here is the breakdown of my approach.
Why I chose Playwright over other options:
- Cloudinary: Costs money for custom fonts and has complex URL syntax.
- Vercel OG: Works for dynamic sites, but I use static sites on Cloudflare.
- Node-canvas: Hard to set up in CI because of C++ dependencies.
- Pillow: Hard to use for complex CSS layouts or flexbox.
The Playwright method is simple. I build an HTML string with CSS. I pass it to a headless browser. I take a screenshot.
The browser handles everything: fonts, gradients, and flexbox.
Key technical details:
- Accent Colors: My script uses regex to pick colors based on article tags. An "AI" tag picks purple. A "Webdev" tag picks blue.
- Dynamic Sizing: The script adjusts font size based on title length to prevent overflow.
- Avoiding Font Issues: I use wait_until="networkidle". This ensures Google Fonts load before the screenshot fires. Without this, the image uses a generic system font.
- Speed Optimization: I open one browser instance and reuse the page object for all articles. This saves significant time in the CI pipeline.
The workflow:
- The script generates the PNG.
- The script writes the image URL back into the article frontmatter.
- The CI pipeline commits the image.
- The site deploys.
This ensures the image is live before the article publishes to platforms like Dev.to or Hashnode.
When to avoid this:
Do not use this for on-demand generation. Playwright takes about 2 seconds per image. It requires a heavy browser binary. It is too slow for a live request.
Use this for batch builds where you control the timing.
