Generating Dynamic Open Graph Image in NextJs
A step-by-step guide to creating dynamic Open Graph images in Next.js, including custom fonts and styling.
When adding Open Graph metadata to your web pages, it's important to include images that align with your content. In this guide, we explore how Next.js allows us to generate these images on-the-fly with the help of . If you are wondering the capabilities of it, check out the /ogofficial og playground.
Installation and Setup
For those using Next.js, simply import { ImageResponse } from "next/og".
If not, run:
First, create an API route in the App Router. Under /app
, create /app/api/og/route.tsx
Creating a Basic GET Function
We start by setting up a basic GET function using ImageResponse
:
Adding Dynamic Title and Image
To make our image more relevant, we can pass a title and image URL as query parameters.
There you have it!
Play around with it to match your theme. Of course, there are more things you might wanna add or change. One that comes in to mind is the font, so let's also see how can we import fonts to the image generation.
Using Custom Fonts
For now, Next.js provides the most basic font to use. So we need to import a custom one.
Importing custom fonts might be very tricky, make sure you follow all the steps.
1. Download a Font
First, find a font that you want and download it. Nextjs suggest it to be .tff
, but .woff
should work just fine. I will be using InterDisplay-ExtraBold.ttf
from https://rsms.me/inter/.
Then, add the font file to your project directory, e.g., /assets/InterDisplay-ExtraBold.ttf
.
The structure should look like this:
2. Enable Edge Runtime
Ensure your API route uses the "edge"
runtime.
3. Fetch and Apply the Font