Creating dynamic Open Graph images for your blogs!

2022-05-11 -- views 5 min read


If you are into writing articles or into SEO stuff, you might know about the meta tags.

One of them is the Open Graph meta tag. It is used to display a thumbnail of the article sites like Twitter, Discord and many more.

1<meta property="og:image" content="http://example.com/image.jpg" />

We’ll need to handle the following:

  • Styling

  • Font family

  • Responsiveness

There are many image manipulation libraries like Jimp or Sharp, but they can’t handle the above points.

You know what can handle it? It’s HTML!

So we will be using Puppeteer that would spin up a headless browser and take a screenshot of the html page.

We will be using the following libraries:

  • Express - For spinning up the server

  • Puppeteer - For spinning up the browser

  • Handlerbars - For rendering the html

  • Tailwind CSS - For styling the html

And all this would be deployed on Vercel. This way we could use the Serverless Functions.

Let’s get started.

Here is the file structure:

File Structure

1. 2|-- api 3| `-- index.ts 4|-- package.json 5|-- src 6| `-- templates 7| |-- basic 8| | `-- index.hbs 9| `-- fancy 10| `-- index.hbs 11|-- tailwind.config.js 12|-- tree.txt 13|-- vercel.json 14`-- yarn.lock

Creating the HTML/HBS Template

The HTML code could be anything, that’s up to you. For sake of this blog, we are using a simple template.

I am using Tailwind CDN for styling. Utility Classes FTW!

Head of the HTML

We are importing fonts, and using TailwindCSS CDN for styling.

1<!-- templates/basic/index.hbs --> 2 3<html lang="en"> 4 <head> 5 <meta charset="UTF-8" /> 6 <meta http-equiv="X-UA-Compatible" content="IE=edge" /> 7 <meta name="viewport" content="width=device-width, initial-scale=1.0" /> 8 <title>{{title}}</title> 9 <link rel="preconnect" href="https://fonts.googleapis.com" /> 10 <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin /> 11 <link href="https://fonts.googleapis.com/css2?family=Karla&display=swap" rel="stylesheet"> 12 <script src="https://cdn.tailwindcss.com?plugins=line-clamp"></script> 13 </head> 14 <!-- body ... --> 15</html>

Body of the HTML

Nothing much here apart from Tailwind CSS classes, just a title and date that handlebars would dynamically update.

1<!-- templates/basic/index.hbs --> 2 3<body 4 class="image relative bg-black font-bold w-[2240px] h-[1260px] p-32 font-[Karla]"> 5 <h1 class="text-gray-300 text-4xl">SV.</h1> 6 <h1 7 class="text-white my-32 py-2 leading-[80px] text-6xl line-clamp-3 font-medium"> 8 {{title}} 9 </h1> 10 <h1 class="text-white font-normal my-32 text-3xl line-clamp-3"> 11 {{date}} | by Shubham Verma 12 </h1> 13 14 <div class="bg-inherit w-full h-full absolute -z-10"></div> 15 16 <h1 class="text-gray-300 mb-32 absolute bottom-0 text-4xl">shbm.fyi</h1> 17</body>

Creating the Server and the Handlerbars Template.

Imports

1// api/index.ts 2import chromium from 'chrome-aws-lambda'; // required for deploying on Vercel 3import express, { Request, Response } from 'express'; 4import { readFileSync } from 'fs'; 5import Handlebars from 'handlebars'; 6import path from 'path'; 7 8const app = express();

Creating the get Route

Overview of the get route:

  • We spin up the puppeteer browser.

  • Get the title and date from the query string.

  • Compile the hbs template and pass in the title and date.

  • Render the html.

  • Take a screenshot of the html.

  • Close the browser.

  • Return the screenshot as a response.

In the very end we are adding this line

module.exports = app;

This is for Vercel to deploy a serverless function.

1app.get('/', async (req: Request, res: Response) => { 2 try { 3 // All these configurations are required for puppeteer, if you are deploying on Vercel! 4 // https://github.com/vercel/community/discussions/124 5 const browser = await chromium.puppeteer.launch({ 6 args: [...chromium.args, '--hide-scrollbars', '--disable-web-security'], 7 defaultViewport: chromium.defaultViewport, 8 executablePath: await chromium.executablePath, 9 headless: true, 10 ignoreHTTPSErrors: true, 11 }); 12 // const browser = await chromium.puppeteer.launch() 13 const [page] = await browser.pages(); 14 15 const { template = 'basic', title, date } = req.query; 16 17 // Reading the template 18 const _template = readFileSync( 19 path.join(process.cwd(), `src/templates/${template}/index.hbs`), 20 'utf8' 21 ); 22 23 // Compiling the template 24 const html = Handlebars.compile(_template)({ 25 title, 26 // get date in this format - 21st April 2020 27 date: 28 date ?? 29 new Date().toLocaleDateString('en-GB', { 30 day: 'numeric', 31 month: 'long', 32 year: 'numeric', 33 }), 34 }); 35 36 // Rendering the html and taking a screenshot 37 await page.setContent(html); 38 const take = await page.$('.image'); 39 const ss = await take.screenshot(); 40 await browser.close(); 41 42 // Returning the buffer of the screenshot. 43 res.setHeader('Content-Type', 'image/png'); 44 res.setHeader('Cache-Control', 's-max-age=1, stale-while-revalidate'); 45 res.send(ss); 46 } catch (err) { 47 console.error(err); 48 res.send('Error'); 49 } 50}); 51 52// Required if you are deplying Express on Vercel as a Serverless Function. 53module.exports = app;

Deploying on Vercel

Create a vercel.json and add the following:

1// vercel.json 2 3{ 4 "rewrites": [ 5 { 6 "destination": "/api", 7 "source": "/(.*)" 8 } 9 ] 10}

All set! You can now deploy the server on Vercel.

You can try it out by going to https://og.shubhamverma.me/?title=Hey there .It will take time to load up, because first it’s serverless and second we are spinning up puppeteer.

Please don’t over do it. I’ve got Vercel Serverless Limits 😅


References:

I have Open Sourced the code for this project on Github.

Here is the Repo link - https://github.com/ShubhamVerma1811/open-graph-api


If you found this blog helpful, then do share it with your friends.


Found this blog helpful? Share it with your friends!