Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

OG Images from Database Records with Playwright

· 5 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

This guide shows you how to generate dynamic Open Graph (OG) images directly from your database records using Playwright. Instead of manually designing an image for every product, article, or user, you’ll build a template that pulls live data and renders it as a PNG. This approach is perfect for social sharing, where a compelling, accurate preview can significantly boost click-through rates. Before starting, you’ll need a Node.js project with Playwright installed, access to your database (we’ll use a simple JSON array for demonstration), and a basic HTML/CSS template.

What You'll Need

  • Node.js (v16 or later) and npm installed.
  • Playwright installed: npm install playwright and then npx playwright install chromium.
  • A database connection (e.g., PostgreSQL, MySQL, MongoDB) or a simple data source like a JSON file.
  • A basic understanding of JavaScript, HTML, and CSS.
  • A template design for your OG image (e.g., a 1200x630px canvas with placeholders for title, description, and image).

Step-by-Step

  1. Set up your project. Create a new directory, initialize npm (npm init -y), and install Playwright (npm install playwright). Also install a database driver if needed (e.g., pg for PostgreSQL).
  2. Prepare your data. Write a function that fetches the record you want to generate an image for. For this example, we’ll use a simple array of objects representing products. In a real app, you’d query your database.
  3. Create an HTML template. Design an HTML file (e.g., template.html) that represents your OG image. Use placeholder elements with IDs for dynamic content. For example: <h1 id="title">Product Title</h1> and <p id="description">Product description</p>. Set the body width and height to 1200x630 pixels (the standard OG image size) and style it with CSS.
  4. Load the template in Playwright. In your Node.js script, launch a Chromium browser instance and open a new page. Use page.setContent() to load the HTML template with the data injected. You can use template literals to replace placeholder values with actual record data.
  5. Inject data into the template. Before rendering, replace the placeholder text with the record’s values. For example: . Alternatively, use page.evaluate() to set the text content of elements by ID.
  6. Set viewport size. Ensure the viewport matches your template dimensions: await page.setViewportSize({ width: 1200, height: 630 }). This ensures the screenshot captures the full canvas.
  7. Wait for fonts and images. If your template uses web fonts or external images, wait for them to load to avoid blank areas. Use await page.evaluate(() => document.fonts.ready) and await page.waitForLoadState('networkidle').
  8. Take a screenshot. Use page.screenshot({ path: 'og-image.png', type: 'png' }) to capture the element or the full page. For a specific element, use page.locator('#og-container').screenshot().
  9. Save the image. Store the generated PNG file in a public directory (e.g., /images/og/) so it can be accessed by your web server. You can also upload it to a CDN or cloud storage.
  10. Use the image in your HTML. In your web page’s <head>, add the OG meta tags: <meta property="og:image" content="https://yoursite.com/images/og/og-image.png" />. Ensure the URL is absolute and accessible.

Common Mistakes

  • Incorrect viewport size: Forgetting to set the viewport to 1200x630 leads to images that are too small or cropped.
  • Not waiting for resources: If fonts or images load after the screenshot, they’ll appear broken or missing.
  • Using relative paths for images: If your template references images with relative paths, Playwright may not resolve them correctly. Use absolute URLs or embed images as base64.
  • Not sanitizing data: Directly injecting database content into HTML can break the layout if the data contains special characters. Use textContent instead of innerHTML to avoid XSS and rendering issues.
  • Overlooking caching: Generating a new image for every request is slow. Cache the generated images by record ID and regenerate only when the data changes.

Tips

  • Use a template engine: For complex templates, consider using a templating library like Handlebars or EJS to manage dynamic content more cleanly.
  • Optimize for readability: Ensure text contrast is high and font sizes are legible at small sizes, as social platforms often display OG images as thumbnails.
  • Test on multiple platforms: Use tools like the Facebook Sharing Debugger or Twitter Card Validator to preview how your image looks on different networks.
  • Batch generation: If you have many records, generate images in a batch script rather than on-the-fly to save resources.
  • Use a headless browser: Playwright runs headless by default, which is perfect for server-side generation. You don’t need a visible browser window.

Troubleshooting

  • Blank or black images: This usually happens when the page hasn’t finished rendering. Increase the wait time or use page.waitForTimeout(1000) as a fallback. Also check that your viewport is set correctly.
  • Fonts not loading: If you’re using Google Fonts, ensure the page has internet access. Alternatively, embed the font as base64 in your CSS.
  • Images not showing: If your template references external images, make sure they are accessible from the server. CORS issues can also block loading; use a proxy or embed images as base64.
  • Playwright not installed: If you get an error about missing browsers, run npx playwright install to download the Chromium binary.
  • Memory issues with large batches: If generating many images in a loop, close the browser after each generation (await browser.close()) or reuse a single browser instance but create new pages.

Frequently Asked Questions

Can I generate OG images for dynamic pages without a database?

Yes, you can use the same technique with any data source, such as an API response or a configuration file. The key is to feed the data into the HTML template before rendering.

What is the ideal size for an OG image?

The recommended size is 1200x630 pixels (a 1.91:1 aspect ratio). This works well across most social platforms like Facebook, Twitter, and LinkedIn.

How do I cache the generated images?

Store the image file with a filename that includes the record ID (e.g., product-123.png). Before generating, check if the file already exists and is not stale. You can also use a CDN with cache headers.

Can I use this for video thumbnails?

Yes, the same method works for generating video thumbnails or any other custom image. Just adjust the template dimensions and content.

Is Playwright the only tool for this?

No, you can use Puppeteer or other headless browsers. Playwright is popular because it’s fast, reliable, and supports multiple browsers.

What if my database contains sensitive data?

Only include data that is safe to display publicly in the OG image. Never include personal or confidential information in the template.