Fumadocs
Integrations

Metadata Image (Next.js)

Usage with Next.js Metadata API.

Introduction

Make sure to read their Metadata section for the fundamentals of Metadata API.

For docs pages, Fumadocs has a built-in metadata image generator.

You will need a route handler to get started.

app/docs-og/[...slug]/route.tsx
import { generateOGImage } from 'fumadocs-ui/og';
import { source } from '@/lib/source';
import { notFound } from 'next/navigation';

export async function GET(
  _req: Request,
  { params }: RouteContext<'/docs-og/[...slug]'>,
) {
  const { slug } = await params;
  const page = source.getPage(slug.slice(0, -1));
  if (!page) notFound();

  return generateOGImage({
    title: page.data.title,
    description: page.data.description,
    site: 'My App',
  });
}

export function generateStaticParams() {
  return source.generateParams().map((page) => ({
    ...page,
    slug: [...page.slug, 'image.png'],
  }));
}

We need to append image.png to the end of slugs so that we can access it via /docs-og/my-page/image.png.

In your docs page, add the image to metadata.

app/docs/[[...slug]]/page.tsx
import { notFound } from 'next/navigation';
import { source } from '@/lib/source';

export async function generateMetadata({
  params,
}: {
  params: Promise<{ slug?: string[] }>;
}) {
  const { slug = [] } = await params;
  const page = source.getPage(slug);
  if (!page) notFound();

  const image = ['/docs-og', ...slug, 'image.png'].join('/');
  return {
    title: page.data.title,
    description: page.data.description,
    openGraph: {
      images: image,
    },
    twitter: {
      card: 'summary_large_image',
      images: image,
    },
  };
}

Other Presets

There's other available styles on Fumadocs CLI, such as mono:

npx @fumadocs/cli@latest add og/mono

Replaced your old generateOGImage with the installed one.

Customisations

You can specify options for Satori, like adding fonts:

import { generateOGImage } from 'fumadocs-ui/og';

generateOGImage({
  fonts: [
    {
      name: 'Roboto',
      // Use `fs` (Node.js only) or `fetch` to read the font as Buffer/ArrayBuffer and provide `data` here.
      data: robotoArrayBuffer,
      weight: 400,
      style: 'normal',
    },
  ],
});

How is this guide?

Last updated on