Boost Social Media Engagement with Dynamic OG Images Using Puppeteer

Aug 6, 2024

Boost Social Media Engagement with Dynamic OG Images Using Puppeteer

Learn how to boost social media engagement by dynamically generating custom Open Graph images using Puppeteer and an Express server for personalized user sharing.

Author

Madhav Bansal
Madhav BansalSenior Software Engineer - I

Creating dynamic Open Graph (OG) images and tags for your web applications can significantly enhance social sharing and user engagement. This tutorial will guide you through setting up an Express server that dynamically generates user-specific OG images using Puppeteer. We’ll use a custom HTML template, generate screenshots, and use these for social media previews.

What is an Open Graph (OG)?

Open Graph (OG) is a protocol that transforms web pages into rich, engaging content when shared on social media platforms. For example, when a link is shared on Facebook, OG tags dictate how it appears, including its title, description, and associated image. By tailoring these tags, you can make your shared links more appealing and interactive.

Prerequisites

  • Node.js installed
  • Puppeteer for Node.js

Step 1: Setting Up the Express Server


First, let’s create a new Express server.

mkdir dynamic-og-image
cd dynamic-og-image
npm init -y
npm install express puppeteer

Create a file named server.js and set up a basic Express server:

const express = require('express');
const puppeteer = require('puppeteer');
const path = require('path');

const app = express();
const PORT = process.env.PORT || 3000;

app.use('/screenshots', express.static(path.join(__dirname, 'screenshots')));

Step 2: Creating the Route Handler

Next, create a route that will handle the generation of the OG image. This route will generate an HTML template with dynamic data and use Puppeteer to take screenshots. In a real application, you might fetch user data from a database like SQL, Firebase, or MongoDB. For simplicity, we’ll hardcode the user data in this example.

app.get('/generate-og/:userId', async (req, res) => {
  const userId = req.params.userId;

  const userData = {
    name: `User ${userId}`,
    imageUrl: '<https://via.placeholder.com/150>' // Replace with actual image URL
  };

  const htmlContent = generateHtmlTemplate(userData);
  const imagePath = await generateOgImage(htmlContent, userId);

  res.send(`
    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8" />
      <meta name="viewport" content="width=device-width, initial-scale=1.0" />    
	  <meta property="og:title" content="Join Our App" />
      <meta property="og:type" content="website" />
      <meta property="og:url" content="<https://your-app-link.com>" />
      <meta property="og:description" content="Your friend ${userData.name} has invited you to join!" />
      <meta property="og:image" content="${imagePath}" />
      <meta property="og:image:alt" content="Invite Image" />
      <meta http-equiv="refresh" content="2;url=https://your-app-link.com" />
    </head>
    <body>
      <h1>Redirecting you to our app...</h1>
    </body>
    </html>
  `);
});

Step 3: Generating HTML Template

Now, let’s create a function to generate an HTML template with dynamic user data. This template will be used to create the OG image.

function generateHtmlTemplate(userData) {
  return `
    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <style>
        body {
          display: flex;
          justify-content: center;
          align-items: center;
          height: 100vh;
          margin: 0;
        }
        .container {
          text-align: center;
          font-family: Arial, sans-serif;
        }
        img {
          width: 100px;
          height: 100px;
          border-radius: 50%;
        }
      </style>
    </head>
    <body>
      <div class="container">
        <img src="${userData.imageUrl}" alt="User Image">
        <h1>${userData.name}</h1>
      </div>
    </body>
    </html>
  `;
}

Step 4: Capturing the OG Image with Puppeteer

We need a function to generate an OG image using Puppeteer. This function will render the HTML template and take a screenshot, saving it locally.

async function generateOgImage(htmlContent, userId) {
  const browser = await puppeteer.launch({
    args: [
      "--no-sandbox",
      "--font-render-hinting=medium",
      "--disable-dev-shm-usage",
    ],
  });

  const page = await browser.newPage();
  await page.setViewport({ width: 900, height: 1525 });
  await page.setContent(htmlContent, { waitUntil: 'networkidle0' });

  const screenshotPath = path.join(__dirname, 'screenshots', `${userId}.png`);
  await page.screenshot({ path: screenshotPath });

  await page.close();
  await browser.close();

  return `/screenshots/${userId}.png`;
}

Step 5: Setting Up the Server Listener

Finally, we set up the server to listen on the specified port.

app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});

Usage

To use this setup, make a GET request to the /generate-og/:userId route, replacing :userId with the actual user ID you want to generate an OG image for. The server will generate a dynamic HTML template, capture an image with Puppeteer, and return an HTML response with the appropriate OG tags.

For example:
GET <http://localhost:3000/generate-og/12345>

This will generate an OG image for the user with ID 12345, save it locally, and return an HTML page with the OG tags ready for sharing.

Notes

  • Dynamic Data: While this example hardcodes user data, in a real-world application, you would fetch this data from a database such as SQL, Firebase, or MongoDB.
  • OG Tags: Open Graph tags are essential for ensuring your content is displayed correctly when shared on social media platforms.

Conclusion

By following these steps, you can dynamically generate OG images and tags tailored to individual users, enhancing the sharing experience and boosting engagement on social media platforms. This setup leverages the power of Puppeteer to create a seamless and efficient user experience. 

Subscribe to Our Newsletter

More from the engineering frontline.

Dive deep into our research and insights on design, development, and the impact of various trends to businesses.
Insight
Why Legacy Systems Make Business Growth More Expensive: Navigate A Smarter Path to Legacy Modernization
Sep 23, 2026

Why Legacy Systems Make Business Growth More Expensive: Navigate A Smarter Path to Legacy Modernization

Learn how legacy systems make business growth more expensive and how edge-first modernization can remove constraints without replacing the existing system.

Insight
SSO, Audit Logs and RBAC: The Enterprise Features AI Prototyping Tools Do Not Cover | Sarika Gautam
Sep 23, 2026

SSO, Audit Logs and RBAC: The Enterprise Features AI Prototyping Tools Do Not Cover | Sarika Gautam

Why AI-generated prototypes fail enterprise review: the context behind SSO, the cost of skipping audit logs, and how role explosion makes RBAC a product of its own.

Insight
Feature Flags as Technical Debt: The Cleanup Nobody Schedules
Sep 21, 2026

Feature Flags as Technical Debt: The Cleanup Nobody Schedules

This blog explains how unmanaged feature flags create technical debt and how teams can detect, manage, and remove them safely.

Insight
Building AI-First Enterprises: Why System Design Matters More Than AI Adoption
Sep 21, 2026

Building AI-First Enterprises: Why System Design Matters More Than AI Adoption

This blog explores how system design, architecture, and validation shape AI-first enterprises, while examining AI’s impact on software engineering and human decision-making.

Insight
The Product Studio in the AI Era: What Actually Changes | Sarika Gautam
Sep 21, 2026

The Product Studio in the AI Era: What Actually Changes | Sarika Gautam

What changes in product development when AI writes the code: the shift to architecture, the token cost of unplanned builds, and why juniors still matter.

Insight
AI and the Future of Digital Customer Experience: Where Technology Meets Human Creativity
Sep 18, 2026

AI and the Future of Digital Customer Experience: Where Technology Meets Human Creativity

A discussion on how AI, human creativity, research, and cross-functional collaboration are shaping the future of digital customer experience.

Insight
Scaling Down Before Scaling Up: Why Bigger Servers Don’t Fix Bad Architecture
Sep 17, 2026

Scaling Down Before Scaling Up: Why Bigger Servers Don’t Fix Bad Architecture

This blog explores how inefficient backend architecture can cause performance issues even under low traffic, covering practical ways to reduce database load, API latency, and resource usage before scaling infrastructure.

The Right Conversation Can

Save You Six Months.

Book a call