Automate Social Images using Next.js and Puppeteer

Because I hate making the same images by hand using Figma.

SurabayaJS

Saturday, 24 October 2020

 

https://twitter.com/griko_nibras

henlo

slide deets

  • Design social image layout using Next.js

  • Create API route for "rendering" social image using Puppeteer

  • Integrate with Next.js head components

  • Future usage

but first

  • Basic understanding of React, Next.js, Chakra UI, and Puppeteer

  • Only a proof-of-concept and not optimized for large production usage

  • Other approaches are better (more on that later)

have you ever wonder...

halo mbak eka (: 

 
<meta property="og:title" content="201 Created" />
<meta property="og:type" content="website" />
<meta property="og:url" content="https://http.cat/201" />
<meta property="og:image" content="https://http.cat/201.jpg" />

<meta property="og:image:type" content="image/jpeg" />
<meta property="og:image:width" content="750" />
<meta property="og:image:height" content="600" />
<meta property="og:image:alt" content="201 Created" />

Example open graph impl. using https://http.cat/201.jpg

Preview of https://surabayajs.org on Discord and Telegram

social image location

  1. Root location on same directory (/social.jpg)

  2. Inside some directory (/images/social.jpg)

  3. Other external source (https://somewhere.io/social.jpg)

Important note: social image path must be absolute ⚠️

  • https://surabayajs.org/social.jpg ✅
  • surabayajs.org/social.jpg ❌
  • /social.jpg

but that's for static images, how about...

✨ d y n a m i c   i m a g e s ✨

"but i don't want to use paid services"

Now introducing...                           

                                 ✨ puppeteer ✨

const puppeteer = require('puppeteer');

(async () => {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();
  await page.goto('https://example.com');
  await page.screenshot({ path: 'example.png' });

  await browser.close();
})();

Example puppeteer usage

Screenshot example.com and save to example.png

  • Create page for social image template
  • Run puppeteer to open template page
  • Save and serve image

generate social image flow

some examples

example #1: og-image

example #2: nextplate

example #3: covid19-api

demo time!

question time?

kthxbai

Automate Social Images using Next.js and Puppeteer

By Griko Nibras

Automate Social Images using Next.js and Puppeteer

Because I hate making the same images by hand using Figma

  • 2,092