Custom Font Example - Vercel OG Image template

This template shows how to load multiple custom fonts for your template. By default, only the Noto Sans font (regular weight) is included. This is the font used for all other examples so you can easily copy/paste the code.

You can download any font from Google Fonts (or anywhere else) and paste the font file in your codebase.

Note that an edge function can’t be larger than 1MB, so be careful not to import too many font weights for your template.

Create a new API endpoint:

// pages/api/og/custom-font.jsx

import React from "react";
import { ImageResponse } from "@vercel/og";

export const config = {
  runtime: "experimental-edge",
};

// Make sure the font exists in the specified path:
const interRegularFontP = fetch(
  new URL("../../../public/Inter-Regular.ttf", import.meta.url)
).then((res) => res.arrayBuffer());

const interBoldFontP = fetch(
  new URL("../../../public/Inter-Bold.ttf", import.meta.url)
).then((res) => res.arrayBuffer());

export default async function handler(req) {
  try {
    const [interRegularFont, interBoldFont] = await Promise.all([
      interRegularFontP,
      interBoldFontP,
    ]);

    const boldText = "Bold Text";
    const regularText = "Regular Text";

    return new ImageResponse(
      (
        <div tw="h-full w-full flex flex-col justify-center items-center bg-gray-50 p-20">
          <p tw="text-7xl font-bold">{boldText}</p>
          <p tw="text-7xl font-regular">{regularText}</p>
        </div>
      ),
      {
        width: 1200,
        height: 627,
        fonts: [
          {
            name: "Inter",
            data: interRegularFont,
            style: "normal",
            weight: 400,
          },
          {
            name: "Inter",
            data: interBoldFont,
            style: "normal",
            weight: 700,
          },
        ],
      }
    );
  } catch (e) {
    console.log(`${e.message}`);
    return new Response(`Failed to generate the image`, {
      status: 500,
    });
  }
}

You can then call the API endpoint:

return <img src="/api/og/custom-font" />;

// or

return (
  <meta property="og:image" content="www.yourdomain.com/api/og/custom-font" />
);

You can also read Vercel’s documentation on how to set up a custom font. The example above is very similar to the one from the docs, but it also shows you how to load multiple fonts/font weights.

More Vercel OG templates

Receive an email when we publish a new template

Max 1-2x times per month.