Custom Font Weights in Next OG Image Generation

While the basic setup for Next OG Image generation is straightforward. But, if you struggled with setting up multiple font weights like me, I am writing this guide for you. I'll walk you through implementing multiple custom font weights in your OG images.

I'll assume you are already working with next/og.

Prepare Your Font Files

First, you'll need to obtain the font files for different weights. For this example, we'll use Lato Regular and Lato Bold.

  1. Download the font files you want to use (I'm using Lato):
  • Lato-Regular.ttf
  • Lato-Bold.ttf I grabbed these from Google Fonts.
  1. Place these files in your project, preferably in an assets folder:
/assets/Lato-Regular.ttf
/assets/Lato-Bold.ttf

Create the OG Image API Route

Create a new file at /app/API/og/route.tsx (for App Router) or /pages/API/og.tsx (for Pages Router). In this example, we'll use the App Router approach.

Import Dependencies and Set Up Basic Configuration

At the top of your route.tsx file, import the necessary dependencies and set up some basic configuration:

import { ImageResponse } from "next/og";
import { NextRequest } from "next/server";

export const runtime = "edge";

const height = 630;
const width = 1200;

Load the Font Files

Create a function to load the font files asynchronously:

async function loadFonts() {
  const regularFontData = await fetch(
    new URL("@/assets/Lato-Regular.ttf", import.meta.url)
  ).then((res) => res.arrayBuffer());

  const boldFontData = await fetch(
    new URL("@/assets/Lato-Bold.ttf", import.meta.url)
  ).then((res) => res.arrayBuffer());

  return { regularFontData, boldFontData };
}

Create the GET Handler

Now, let's create the main GET handler function that will generate our OG image:

export async function GET(request: NextRequest) {
  try {
    const { regularFontData, boldFontData } = await loadFonts();

    return new ImageResponse(
      (
        <div
          style={{
            height: "100%",
            width: "100%",
            display: "flex",
            flexDirection: "column",
            alignItems: "center",
            justifyContent: "center",
            backgroundColor: "#1a1a1a",
            fontSize: 32,
            fontFamily: "Lato",
          }}
        >
          <h1 style={{ color: "white", fontSize: 64, fontFamily: "Lato-Bold" }}>
            Custom Font Weights
          </h1>
          <p style={{ color: "#cccccc" }}>
            This text uses Lato Regular
          </p>
          <p style={{ color: "#cccccc", fontFamily: "Lato-Bold" }}>
            This text uses Lato Bold
          </p>
        </div>
      ),
      {
        width,
        height,
        fonts: [
          {
            name: "Lato",
            data: regularFontData,
            style: "normal",
            weight: 400,
          },
          {
            name: "Lato-Bold",
            data: boldFontData,
            style: "normal",
            weight: 700,
          },
        ],
      }
    );
  } catch (error) {
    console.error("Failed to generate OG image:", error);
    return new Response("Failed to generate image", { status: 500 });
  }
}

Test Your OG Image

If I didn't paste some broken code you should be up and running.

Run your Next.js development server:

npm run dev

Navigate to http://localhost:3000/api/og in your browser.

You should see an image with text in different font weights.

Adjust the font files, styles, and content to match your needs. For even more customization, you can extend this example to include more font weights or even different font families.

Nextjs
Avatar for Niall Maher

Written by Niall Maher

Founder of Codú - The web developer community! I've worked in nearly every corner of technology businesses: Lead Developer, Software Architect, Product Manager, CTO, and now happily a Founder.

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.