Next.js Discord

Discord Forum

use a google font in next/og?

Answered
Boreal Chickadee posted this in #help-forum
Open in Discord
Avatar
Boreal ChickadeeOP
anyone have a way of using a google font in next/og?
Answered by joulev
import { ImageResponse } from "next/server";

const [width, height] = [1200, 630];
const logoWidth = 96;

export async function getOpengraphImage({ title, subtitle }: { title: string; subtitle: string }) {
  return new ImageResponse(
    (
      <div>
        ...
      </div>
    ),
    {
      width,
      height,
      fonts: await Promise.all(
        ([400, 700] as const).map(async weight => {
          const fontRes = await fetch(
            `https://cdn.jsdelivr.net/fontsource/fonts/hanken-grotesk@latest/latin-${weight}-normal.woff`,
          );
          const font = await fontRes.arrayBuffer();
          return { name: "Hanken Grotesk", data: font, style: "normal", weight };
        }),
      ),
    },
  );
}
View full answer

15 Replies

Avatar
Western Tanager
dumb question... what is next/og and why it is used?(newbie here)
Avatar
Boreal ChickadeeOP
its an image generation library
generally used for opengraph-images but could generate any image you want
(think twitter image cards)
Avatar
you need to download the font to a buffer and then put it to the ImageResponse options https://github.com/vercel/satori?tab=readme-ov-file#fonts
quite a bit of work to be done to get it working
Avatar
Boreal ChickadeeOP
yeah curious if anyone has the code, I tried to write it but its seriously a pain. and v0 was no help
Avatar
import { ImageResponse } from "next/server";

const [width, height] = [1200, 630];
const logoWidth = 96;

export async function getOpengraphImage({ title, subtitle }: { title: string; subtitle: string }) {
  return new ImageResponse(
    (
      <div>
        ...
      </div>
    ),
    {
      width,
      height,
      fonts: await Promise.all(
        ([400, 700] as const).map(async weight => {
          const fontRes = await fetch(
            `https://cdn.jsdelivr.net/fontsource/fonts/hanken-grotesk@latest/latin-${weight}-normal.woff`,
          );
          const font = await fontRes.arrayBuffer();
          return { name: "Hanken Grotesk", data: font, style: "normal", weight };
        }),
      ),
    },
  );
}
Answer
Avatar
you have to find a .woff url for the font you choose
Avatar
Boreal ChickadeeOP
Oh nice fontsource has the font I need, thanks
was tough getting it out of google fonts
Avatar
yeah i think fontsource has all google fonts and a few others as well
Avatar
Boreal ChickadeeOP
tyvm!