Vercel Open Graph Card With No Framework

I was pretty excited when Vercel announced their library @vercel/og for dynamically generating Open Graph images. However I have immediately noticed that all the examples require installing either Next.js or transpiling your code with JSX. Luckily, JSX converts to plain javascript objects. With only few required in my case, there is no need to install any unnecessary libraries.

This (jsx):

<div style="color: orange">Hello!</div>

becomes this (plain javascript):

{
  type: 'div',
  props: {
    style: {
      color: 'orange',
    },
  },
}

The Example

Check out the Live Demo or fork and tweak the GitHub Repository yourself.

// api/card.js
import { ImageResponse } from '@vercel/og'

export const config = {
  runtime: 'edge',
}

export default async function () {
  return new ImageResponse(
    {
      type: 'div',
      props: {
        style: {
          width: '100%',
          height: '100%',
          display: 'flex',
          flexDirection: 'column',
          justifyContent: 'center',
          alignItems: 'center',
          padding: 64,
          color: '#040404',
          backgroundColor: '#f2f2f2',
          fontSize: 80,
          lineHeight: 1.125,
          letterSpacing: -1,
          textAlign: 'center',
        },
        children: 'Hello There 👋',
      },
    },
    {
      width: 1200,
      height: 630,
    }
  )
}

This is all the code you need to generate simple open graph card image. No redundant libraries, no code to transpile. Look at the dependencies:

{
  "type": "module",
  "dependencies": {
    "@vercel/og": "0.6.2"
  }
}

Even fonts and emojis work out of the box. Thank you Vercel!

The Localhost Problem

This code doesn't run on your local machine when running vercel dev. I remember having this issue a year back when I first started experimenting with this library. In both cases there were no issues when deployed to Vercel.

However a few months back, somewhere around version 0.5.x, the code started working on my local machine just fine. But... in time of writing this post, and creating the example above, I encountered another issue with no luck of running it locally. Bear this in mind when experimenting with it on your own. I have tired going back and forth with @vercel/og versions with no success. I am attaching my current stack for future reference. Sometimes you just have to wait a bit for issue tu resolve by itself. 🤷‍♂️

Node.js ...... 18.19.1
NPM .......... 10.5.0
Vercel CLI ... 33.5.5
@vercel/og .... 0.6.2

Posts