@vercel/og cache in javascript

The @vercel/og package is used to generate open graph images dynamically. In order to cache the images, you can use a CDN like Vercel Edge Network.

Here's an example of how to cache using Vercel Edge Network:

index.tsx
import og from "@vercel/og";

export default async function handler(req, res) {
  const imagePath = "https://example.com/image.png";

  const image = await og(`https://example.com/image.png`, {
    viewport: "width=device-width, initial-scale=1.0",
  });
  
  res.set("Cache-Control", "s-maxage=86400, stale-while-revalidate"); // Set caching headers
  res.setHeader("Content-Type", "image/png");
  res.send(image);
};
419 chars
14 lines

By adding the Cache-Control header with a s-maxage of 86400 seconds (24 hours), you are instructing the CDN to cache the response for up to 24 hours. The stale-while-revalidate parameter allows the CDN to serve cached content while refreshing the cache in the background.

Note: The specific caching headers and values can be adjusted according to your needs.

related categories

gistlibby LogSnag