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
Building a Real-Time Photo Sync Video Experience Using 100ms SDK and Reactive State Management
Oct 15, 2026

Building a Real-Time Photo Sync Video Experience Using 100ms SDK and Reactive State Management

This blog explains how to build a real-time video experience with synchronized photo sharing, chat, and reactive state management using the 100ms SDK.

Insight
Taming Elasticsearch at Scale
Oct 13, 2026

Taming Elasticsearch at Scale

Optimize Elasticsearch for millions of records with better pagination, leaner payloads, efficient filtering, faster ingestion, and frontend techniques that keep search responsive with increase in data.

Insight
Deep Linking for Mobile Apps(React Native) with NestJs, AWS CloudFront, S3 & ALB: A Complete Guide
Oct 13, 2026

Deep Linking for Mobile Apps(React Native) with NestJs, AWS CloudFront, S3 & ALB: A Complete Guide

Build a self-hosted deep linking and referral system for React Native without a third-party SDK. This guide covers Android App Links, iOS Universal Links, an S3 and CloudFront setup, and a NestJS backend that routes users to the right app store.

Insight
How We Engineered a Three-Path Reward Processing System for a Real-Time Sports Platform
Oct 12, 2026

How We Engineered a Three-Path Reward Processing System for a Real-Time Sports Platform

This blog explains how a real-time sports platform uses synchronous, asynchronous, and scheduled processing paths to handle rewards without slowing down the player experience.

Insight
Building an MCP-Powered QA Agent
Oct 12, 2026

Building an MCP-Powered QA Agent

Build an MCP QA agent that runs Playwright tests, validates APIs, and analyzes failures through a controlled, auditable tool layer with human approval.

Insight
From Test Failure to Root Cause: Building an AI-Assisted Playwright Failure Analysis Pipeline
Oct 9, 2026

From Test Failure to Root Cause: Building an AI-Assisted Playwright Failure Analysis Pipeline

This blog explains how an AI-assisted Playwright pipeline can analyze test failure evidence, identify probable root causes, and support human-validated debugging.

Insight
The Model Context Protocol: From First Call to Production
Oct 8, 2026

The Model Context Protocol: From First Call to Production

This blog explains how Model Context Protocol (MCP) works, from tool discovery and execution to OAuth authorization, security controls, and production deployment.

Footer

The Right Conversation Can

Save You Six Months.

Book a Call