Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
April 16, 2024 07:00 am GMT

Creating an OG image using React and Netlify Edge Functions

Open Graph (OG) images are a must if you're sharing content on the Internet. From sites like X/Twitter, to Slack or Discord, a great OG image makes your link share pop.

Examples

I recently built out a couple of OG images for Open Sauced for a couple of features we've rolled out over the past couple of months, Workspaces and Repository pages. They're great features that I encourage you to check out, and I encourage you to share them on socials so our beautiful OG images pop.

For example, here's an OG image for a workspace for jsr. JSR is the new JavaScript registry from the folks from Deno.

OG image for the OpenSauced workspace for jsr

And here's the OG image for a repository page for huggingface/transformers.

OG image for the huggingface/transformers repository

Looking at the image for the jsr workspace, there is a template for the image, but there are several dynamic portions to the image.

All the sections denoted by green outlined squares are dynamic.

OG image for the OpenSauced workspace for jsr with sections outline in green squares denoting dynamic portions of the image

This dynamic info gets pulled in for the most part from the OpenSauced API.

GitHub logo open-sauced / api

API built in NestJS and SupaBase designed to remove client complexity and provide a structured graph of all @open-sauced integrations


Open Sauced

Open Sauced Insights API

The path to your next Open Source contribution

DigitalOcean Referral Badge

GitHub code size in bytes GitHub commit activity GitHub issues GitHub Release Discord Twitter

Live release environments

Prerequisites

In order to run the project we need the following software binaries installed on our development machines:

  • node>=16.7.0
  • npm>=8.0.0
  • docker>=20.10.12

Local development

Setting Up Your Supabase Instance

Before setting up your local PostgreSQL database, a Supabase instance should be created. To do this, follow these steps:

1. Create a new Supabase project: Visit Supabase and create a new project.

2. Set Environment Variables in .env file: Once your project is created, Supabase will provide a URL and an API key. Set these in your project's .env file:

SUPABASE_URL=your_supabase_urlSUPABASE_API_KEY=your_supabase_api_keySUPABASE_JWT_SECRET=your_supabase_jwt_secretAPI_DOMAIN=your_api_domain

Replace your_supabase_url, your_supabase_api_key, your_supabase_jwt_secret, and your_api_domain with the actual values provided by Supabase and your project's settings.

Setting Up A PostgreSQL Database Locally

A PostgreSQL Docker container has been set up




Other parts are pulled in from the URL, like 30 for the day range, and the description comes from the query string in the OG image URL.

browser dev tools view of the metadata section of the <head> with OG image URLs outlined by green squares

React to generate an image

So, how do we use React to generate an image?

We're using og_edge from my old co-worker Matt Kane (@ascorbic), but og_edge is a direct port of @vercel/og that works on Deno and Netlify Edge Functions which run on Deno.

GitHub logo ascorbic / og-edge

Generate Open Graph images with Deno and Netlify Edge Functions, no framework needed.

Open Graph Image Generation

Generate Open Graph images with Deno and Netlify Edge Functions, no frameworkneeded. This is a fork of the awesome@vercel/og, ported to run on Deno.

Usage

To use on Netlify, create the following Edge Function:

// /netlify/edge-functions/og.tsximport React from "https://esm.sh/[email protected]";import { ImageResponse } from 'https://deno.land/x/og_edge/mod.ts'export default async function handler(req: Request) {    return new ImageResponse(    (      <div        style={{          width: '100%',          height: '100%',          display: 'flex',          alignItems: 'center',          justifyContent: 'center',          fontSize: 128,          background: 'lavender',        }}      >        Hello!      </div>    )  )}

Then create a netlify.toml file with the following:

[[edge_functions]]function = "og"path = "/og"

Make sure you have the latest version ofthe Netlify CLI installed.Then runnetlify

Under the hood, og_edge and @vercel/og use the Satori library.

Satori: Enlightened library to convert HTML and CSS to SVG.

GitHub logo vercel / satori

Enlightened library to convert HTML and CSS to SVG

Satori

Satori: Enlightened library to convert HTML and CSS to SVG.

Note

To use Satori in your project to generate PNG images like Open Graph images and social cards, check out our announcement and Vercels Open Graph Image Generation

To use it in Next.js, take a look at the Next.js Open Graph Image Generation template

Overview

Satori supports the JSX syntax, which makes it very straightforward to use. Heres an overview of the basic usage:

// api.jsximport satori from 'satori'const svg = await satori(  <div style={{ color: 'black' }}>hello, world</div>,  {    width: 600,    height: 400,    fonts: [      {        name: 'Roboto',        // Use `fs` (Node.js only) or `fetch` to read the font as Buffer/ArrayBuffer and provide `data` here.        data: robotoArrayBuffer,        weight: 400,

The API for the og_edge module is pretty straightforward. It exposes an ImageResponse constructor with the following options and that's it.

new ImageResponse(  element: ReactElement,  options: {    width?: number = 1200    height?: number = 630    emoji?: 'twemoji' | 'blobmoji' | 'noto' | 'openmoji' | 'fluent' | 'fluentFlat' = 'twemoji',    fonts?: {      name: string,      data: ArrayBuffer,      weight: number,      style: 'normal' | 'italic'    }[]    debug?: boolean = false    // Options that will be passed to the HTTP response    status?: number = 200    statusText?: string    headers?: Record<string, string>  },)

Code snippet above care of the official og_edge API reference.

To build out these OG images, we have a background image, some icons, like a star and fork icon, and we also pull in the repository organization or user's avatar. With a bit of vanilla CSS, we can position things just right. We also pull in the Inter font as that's what we use at OpenSauced.

As far as I know, og_edge does not support Tailwind like @vercel/og does. Not a dealbreaker at all, but just something to be mindful of.

One other thing we do is set cache headers as these are dynamic images where the data changes over time. Having said that, some social networks cache OG images very aggressively.

      headers: {        // cache for 2 hours        "cache-control": "public, s-maxage=7200",        "content-type": "image/png",      },

Show me the code

Here's the pull requests for the initial work on these two OG images.

GitHub logo feat: workspace OG image #2939

Description

Now if you share a workspace dashboard link, it will generate a preview image when shared on socials, Slack etc. Repository statistics have easier to read numbers and also save on real estate, e.g. 1100 becomes 1.1k. If the title is too long it's truncated and has ... at the end. Same for the description.

What type of PR is this? (check all applicable)

  • [x] Feature
  • [ ] Bug Fix
  • [ ] Documentation Update
  • [ ] Style
  • [ ] Code Refactor
  • [ ] Performance Improvements
  • [ ] Test
  • [ ] Build
  • [ ] CI
  • [ ] Chore (Release)
  • [ ] Revert

Related Tickets & Documents

Closes #2932

Mobile & Desktop Screenshots/Recordings

image

Steps to QA

  1. go to any public workspace's dashboard in the deploy preview.
  2. Copy the URL.
  3. Paste it on socials, Discord, or Slack.
  4. The OG image unfurls showing the social card.

Added to documentation?

  • [ ] README.md
  • [ ] docs.opensauced.pizza
  • [ ] dev.to/opensauced
  • [ ] storybook
  • [x] no documentation needed

[optional] Are there any post-deployment tasks we need to perform?

[optional] What gif best describes this PR or how it makes you feel?

GitHub logo feat: created the OG image for repository pages #3117

Description

Implements the open graph (OG) image for repository pages.

Related Tickets & Documents

Closes #3098

Mobile & Desktop Screenshots/Recordings

image

Steps to QA

  1. Go to e.g. https://deploy-preview-3117--oss-insights.netlify.app/s/kubernetes/kubernetes
  2. The repository page loads.
  3. In Slack or some social network, paste that URL.
  4. When the post or message is published, an OG image appears.

CleanShot 2024-04-04 at 11 50 15

Tier (staff will fill in)

  • [ ] Tier 1
  • [x] Tier 2
  • [ ] Tier 3
  • [ ] Tier 4

[optional] Are there any post-deployment tasks we need to perform?

[optional] What gif best describes this PR or how it makes you feel?

Wrapping up

Beautiful and dynamic OG images are a must if you're looking to stand out when sharing links on socials, and og_edge and @vercel/og are great options if you also want to leverage your existing React skill set.

Now go out and build your own OG images!

Stay saucy peeps!

If you would like to know more about my work in open source, follow me on OpenSauced.


Original Link: https://dev.to/opensauced/creating-an-og-image-using-react-and-netlify-edge-functions-563a

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To