Skip to content

Instantly share code, notes, and snippets.

@fgcoelho
Last active January 31, 2025 19:09
Show Gist options
  • Select an option

  • Save fgcoelho/5f30cb30afc7ecb6ced32aadd7d77aef to your computer and use it in GitHub Desktop.

Select an option

Save fgcoelho/5f30cb30afc7ecb6ced32aadd7d77aef to your computer and use it in GitHub Desktop.
How to properly load/handle custom fonts in Next.js Open Graph (OG) images (new ImageResponse).

How to properly load/handle custom fonts in Next.js Open Graph (OG) images (new ImageResponse).

// load-google-fonts.ts

import { ImageResponseOptions } from "next/server";

type FontOptions = ImageResponseOptions["fonts"];

async function loadGoogleFont(font: string, weight: number) {
  const url = `https://fonts.googleapis.com/css2?family=${font}:wght@${weight}`;
  const css = await (await fetch(url)).text();
  const resource = css.match(
    /src: url\((.+)\) format\('(opentype|truetype)'\)/
  );

  if (resource) {
    const response = await fetch(resource[1]);
    if (response.status == 200) {
      return {
        buffer: await response.arrayBuffer(),
        font: { family: font, weight: weight },
      };
    }
  }

  throw new Error("❌ Failed to load font data!");
}

export const getFonts = async () => {
  const fonts = await Promise.all([
    loadGoogleFont("Inter", 400),
    loadGoogleFont("Inter", 600),
    loadGoogleFont("Inter", 700),
  ]);

  return fonts.map(({ font, buffer }) => ({
    name: font.family,
    data: buffer,
    style: "normal",
    weight: font.weight,
  })) as FontOptions;
};
// image.tsx

import { getFonts } from "./load-google-fonts";

const Image = new ImageResponse(
    (
      <div></div>
    ),
    {
      width: 1200,
      height: 630,
      fonts: await getFonts()
    }
  )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment