Skip to main content

Web frameworks · Intermediate · 22 min

Add metadata, a sitemap and Open Graph images in Next.js 16

By Padding · Updated 18 Nov 2026
Next.js 16.4.6 · React 19.3.1 · Node.js 26 LTS (node:26 image)

You will give a small Next.js 16 site page titles, descriptions, canonical URLs, JSON-LD, a generated share image for every page, a sitemap and a robots.txt, and check each one in the built HTML with curl.

On this page

A page can look fine in the browser and still be invisible or ugly everywhere else. Search engines read its <title>, description and canonical link. Chat apps and social networks read its Open Graph tags to build a preview card. Crawlers find pages through sitemap.xml and learn what to skip from robots.txt. Structured data in JSON-LD tells a search engine that a page is a recipe, an event or a product, not only a block of text.

Next.js 16 builds all of this from code you put in the app/ folder: a metadata export, a generateMetadata function, and special files named sitemap.ts, robots.ts and opengraph-image.tsx. You will build a three-recipe site called Shared Table, add each piece, and after each one run a production build and read what Next.js wrote with curl. Link-preview bots and many crawlers do not run your JavaScript, and those that do may read the page before it runs, so the HTML that curl sees is the HTML to get right.

The tutorial assumes the App Router ideas from the first Next.js 16 tutorial. It starts from an empty folder so every file is in front of you.

Step 1 · Create a small recipe site

Make a project folder and a package.json, then install Next.js, React and TypeScript at exact versions so your build matches this tutorial:

Bash
mkdir -p ~/recipe-meta-demo
cd ~/recipe-meta-demo
cat > package.json <<'JSON'
{
  "name": "recipe-meta-demo",
  "private": true,
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start"
  }
}
JSON
npm install --save-exact next@16.4.6 react@19.3.1 react-dom@19.3.1
npm install --save-exact --save-dev typescript@5.9.3 @types/react@19.3.0 @types/react-dom@19.3.0 @types/node@26.6.6

The create-next-app 16 template pins TypeScript 5, and 5.9.3 is the current 5.x release, so it is used here.

Add a tsconfig.json with an @/ import alias, and two small modules: one with the site's name and public address, and one with the recipe data. In a real project the recipes would come from a database or a CMS; the metadata code does not change.

Bash
cat > tsconfig.json <<'JSON'
{
  "compilerOptions": {
    "target": "ES2022",
    "lib": ["dom", "dom.iterable", "esnext"],
    "strict": true,
    "noEmit": true,
    "module": "esnext",
    "moduleResolution": "bundler",
    "jsx": "react-jsx",
    "skipLibCheck": true,
    "isolatedModules": true,
    "esModuleInterop": true,
    "resolveJsonModule": true,
    "incremental": true,
    "plugins": [{ "name": "next" }],
    "paths": { "@/*": ["./*"] }
  },
  "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
  "exclude": ["node_modules"]
}
JSON
mkdir -p lib app 'app/recipes/[slug]'
cat > lib/site.ts <<'TS'
export const siteName = "Shared Table";
export const siteUrl = process.env.SITE_URL ?? "http://localhost:3000";
TS
cat > lib/recipes.ts <<'TS'
export type Recipe = {
  slug: string;
  title: string;
  summary: string;
  ingredients: string[];
  minutes: number;
  updated: string;
};

const recipes: Recipe[] = [
  {
    slug: "jollof-rice",
    title: "Jollof rice",
    summary: "Rice cooked in a tomato and pepper base until every grain is coated.",
    ingredients: ["Long-grain rice", "Tomatoes", "Red peppers", "Onion", "Stock"],
    minutes: 75,
    updated: "2026-11-02",
  },
  {
    slug: "chapati",
    title: "Chapati",
    summary: "Soft, layered flatbread rolled with oil and cooked on a dry pan.",
    ingredients: ["Flour", "Warm water", "Oil", "Salt"],
    minutes: 50,
    updated: "2026-10-21",
  },
  {
    slug: "shakshuka",
    title: "Shakshuka",
    summary: "Eggs poached in a spiced tomato and pepper sauce, served in the pan.",
    ingredients: ["Eggs", "Tomatoes", "Peppers", "Cumin", "Paprika"],
    minutes: 30,
    updated: "2026-11-10",
  },
];

export function getRecipes(): Recipe[] {
  return recipes;
}

export function getRecipe(slug: string): Recipe | undefined {
  return recipes.find((recipe) => recipe.slug === slug);
}
TS

Search engines and share cards need absolute URLs, so the site needs to know its public address. It reads it from SITE_URL. Next.js loads .env.production during next build and next start, so put the address there. A public URL is not a secret, so a committed file is fine. Replace https://recipes.example.com with your own domain when you deploy:

Bash
printf 'SITE_URL=https://recipes.example.com\n' > .env.production
cat .env.production

Check it worked

Run npm ls next react and you see next@16.4.6 and react@19.3.1. ls -a shows package.json, tsconfig.json, .env.production, node_modules, lib and app, and cat .env.production prints the SITE_URL line.

Bash
npm ls next react

Step 2 · Set site-wide metadata in the root layout

The root layout is the place for metadata every page shares. Three fields there do most of the work, and a fourth belongs on each page:

  • metadataBase turns relative URLs in other metadata fields into absolute ones. Without it, a relative canonical or image URL is a build error.
  • title.template wraps the title of every page below the layout. %s is replaced by the page's own title. title.default is used when a page sets no title.
  • alternates.canonical writes <link rel="canonical">, the address you want search engines to treat as the real one when a page is reachable at several. It is set per page, not in the layout, so here it goes in app/page.tsx.
  • openGraph sets the og: tags that preview cards read.
Bash
cat > app/layout.tsx <<'TSX'
import type { Metadata } from "next";
import { siteName, siteUrl } from "@/lib/site";

export const metadata: Metadata = {
  metadataBase: new URL(siteUrl),
  title: {
    default: `${siteName}: recipes for everyday cooking`,
    template: `%s | ${siteName}`,
  },
  description: "Tested home recipes with clear steps and short ingredient lists.",
  openGraph: {
    siteName,
    type: "website",
    locale: "en_GB",
  },
};

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en-GB">
      <body style={{ fontFamily: "system-ui, sans-serif", maxWidth: 640, margin: "2rem auto", padding: "0 1rem" }}>
        {children}
      </body>
    </html>
  );
}
TSX
cat > app/page.tsx <<'TSX'
import type { Metadata } from "next";
import Link from "next/link";
import { getRecipes } from "@/lib/recipes";

export const metadata: Metadata = {
  alternates: { canonical: "/" },
};

export default function HomePage() {
  return (
    <main>
      <h1>Shared Table</h1>
      <ul>
        {getRecipes().map((recipe) => (
          <li key={recipe.slug}>
            <Link href={`/recipes/${recipe.slug}`}>{recipe.title}</Link>
          </li>
        ))}
      </ul>
    </main>
  );
}
TSX

Do not put a canonical in a layout: every page below it inherits that address unless it sets its own alternates, so a page you add later would tell search engines that its real address is the home page, and it can drop out of the index.

metadata and generateMetadata only work in Server Components. A file that starts with "use client" cannot export them.

Build the site, then start the production server in your second terminal:

Bash
npm run build
Bash
npm run start

Read the tags back from the home page:

Bash
curl -s http://localhost:3000/ | grep -oE '<title>[^<]*</title>|<meta name="description"[^>]*>|<link rel="canonical"[^>]*>|<meta property="og:[^>]*>'

Check it worked

The build prints - Environments: .env.production near the top, which tells you SITE_URL was read. It may also say it adjusted tsconfig.json; that is Next.js adding settings it needs. The curl command prints the title Shared Table: recipes for everyday cooking, the description, <link rel="canonical" href="https://recipes.example.com"/> and og: tags for the title, description, site name, locale and type. The home page uses title.default, because the template only applies to pages below the layout.

Stop the server with Ctrl+C before the next step. Every change below needs a new build, because the production server serves what the last build produced.

Step 3 · Generate metadata for each recipe page

A recipe page needs its own title, description and canonical URL, built from the recipe data. generateMetadata receives the same params as the page and returns a Metadata object. generateStaticParams lists the slugs, so all three pages and their metadata are built ahead of time, not on each request.

Bash
cat > 'app/recipes/[slug]/page.tsx' <<'TSX'
import type { Metadata } from "next";
import { notFound } from "next/navigation";
import { getRecipe, getRecipes } from "@/lib/recipes";
import { siteName } from "@/lib/site";

export function generateStaticParams() {
  return getRecipes().map((recipe) => ({ slug: recipe.slug }));
}

export async function generateMetadata({ params }: PageProps<"/recipes/[slug]">): Promise<Metadata> {
  const { slug } = await params;
  const recipe = getRecipe(slug);
  if (!recipe) return {};

  return {
    title: recipe.title,
    description: recipe.summary,
    alternates: { canonical: `/recipes/${recipe.slug}` },
    openGraph: {
      siteName,
      type: "article",
      locale: "en_GB",
      title: recipe.title,
      description: recipe.summary,
      url: `/recipes/${recipe.slug}`,
      modifiedTime: recipe.updated,
    },
  };
}

export default async function RecipePage({ params }: PageProps<"/recipes/[slug]">) {
  const { slug } = await params;
  const recipe = getRecipe(slug);
  if (!recipe) notFound();

  return (
    <main>
      <h1>{recipe.title}</h1>
      <p>{recipe.summary}</p>
      <p>Ready in {recipe.minutes} minutes.</p>
      <ul>
        {recipe.ingredients.map((item) => (
          <li key={item}>{item}</li>
        ))}
      </ul>
    </main>
  );
}
TSX

Two details matter here. First, metadata from the layout and the page is merged one level deep only. Because the page sets openGraph, it replaces the layout's whole openGraph object, which is why siteName and locale are repeated. If you leave them out, the recipe pages lose og:site_name. Second, canonical and url are relative: metadataBase from the layout turns them into full addresses.

PageProps<"/recipes/[slug]"> is a type Next.js generates from your routes during the build, so you do not import it.

Bash
npm run build
Bash
npm run start
Bash
curl -s http://localhost:3000/recipes/jollof-rice | grep -oE '<title>[^<]*</title>|<link rel="canonical"[^>]*>|<meta property="og:(url|site_name|type)"[^>]*>'
curl -s -o /dev/null -w '%{http_code}\n' http://localhost:3000/recipes/pancakes

Check it worked

The build's route table lists /recipes/jollof-rice, /recipes/chapati and /recipes/shakshuka under /recipes/[slug], marked as prerendered. The first curl prints <title>Jollof rice | Shared Table</title>, the canonical https://recipes.example.com/recipes/jollof-rice, the same address as og:url, og:site_name and og:type set to article. The second prints 404: an unknown slug reaches notFound(), so search engines are not shown an empty page with a 200 status.

Stop the server with Ctrl+C.

Step 4 · Describe each recipe with JSON-LD

JSON-LD is structured data in a <script type="application/ld+json"> tag, using the vocabulary from schema.org. Next.js has no metadata field for it: you render the script tag yourself in the page. Replace the recipe page with this version, which adds a Recipe object and renders it at the top of <main>:

Bash
cat > 'app/recipes/[slug]/page.tsx' <<'TSX'
import type { Metadata } from "next";
import { notFound } from "next/navigation";
import { getRecipe, getRecipes } from "@/lib/recipes";
import { siteName, siteUrl } from "@/lib/site";

export function generateStaticParams() {
  return getRecipes().map((recipe) => ({ slug: recipe.slug }));
}

export async function generateMetadata({ params }: PageProps<"/recipes/[slug]">): Promise<Metadata> {
  const { slug } = await params;
  const recipe = getRecipe(slug);
  if (!recipe) return {};

  return {
    title: recipe.title,
    description: recipe.summary,
    alternates: { canonical: `/recipes/${recipe.slug}` },
    openGraph: {
      siteName,
      type: "article",
      locale: "en_GB",
      title: recipe.title,
      description: recipe.summary,
      url: `/recipes/${recipe.slug}`,
      modifiedTime: recipe.updated,
    },
  };
}

export default async function RecipePage({ params }: PageProps<"/recipes/[slug]">) {
  const { slug } = await params;
  const recipe = getRecipe(slug);
  if (!recipe) notFound();

  const jsonLd = {
    "@context": "https://schema.org",
    "@type": "Recipe",
    name: recipe.title,
    description: recipe.summary,
    recipeIngredient: recipe.ingredients,
    totalTime: `PT${recipe.minutes}M`,
    dateModified: recipe.updated,
    url: new URL(`/recipes/${recipe.slug}`, siteUrl).toString(),
  };

  return (
    <main>
      <script
        type="application/ld+json"
        dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd).replace(/</g, "\\u003c") }}
      />
      <h1>{recipe.title}</h1>
      <p>{recipe.summary}</p>
      <p>Ready in {recipe.minutes} minutes.</p>
      <ul>
        {recipe.ingredients.map((item) => (
          <li key={item}>{item}</li>
        ))}
      </ul>
    </main>
  );
}
TSX

The .replace(/</g, "\\u003c") is not decoration. JSON.stringify leaves < alone, so a recipe title containing </script> would end the tag early and let the rest run as HTML. Replacing every < with its JSON escape keeps the data valid and the tag closed. totalTime uses the ISO 8601 duration format that schema.org expects: PT75M is 75 minutes.

Build, start the server, and pull the JSON-LD out of a page. Piping it into Node.js proves it parses as JSON:

Bash
npm run build
Bash
npm run start
Bash
curl -s http://localhost:3000/recipes/chapati \
  | grep -oE '<script type="application/ld\+json">[^<]*' \
  | sed 's/^[^>]*>//' \
  | node -e 'let s = ""; process.stdin.on("data", (d) => (s += d)).on("end", () => { const r = JSON.parse(s); console.log(r["@type"], "|", r.name, "|", r.recipeIngredient.length, "ingredients |", r.totalTime); })'

Check it worked

The command prints Recipe | Chapati | 4 ingredients | PT50M. If JSON.parse throws instead, the tag holds something that is not valid JSON. After you deploy, paste a recipe URL into Google's Rich Results Test or the Schema Markup Validator at validator.schema.org to see which fields they read and which they would like added, such as image or recipeInstructions.

Stop the server with Ctrl+C.

Step 5 · Generate an Open Graph image for every recipe

When someone shares a link, the preview card shows the og:image. A file named opengraph-image.tsx in a route folder generates that image with JSX, and Next.js adds the og:image tags to every page in that folder for you. ImageResponse from next/og turns the JSX into a PNG. It supports flexbox and a subset of CSS, not the whole language, so every div with more than one child needs display: "flex".

Bash
cat > 'app/recipes/[slug]/opengraph-image.tsx' <<'TSX'
import { ImageResponse } from "next/og";
import { getRecipe, getRecipes } from "@/lib/recipes";
import { siteName } from "@/lib/site";

export const alt = "Recipe title and cooking time on a dark card";
export const size = { width: 1200, height: 630 };
export const contentType = "image/png";

export function generateStaticParams() {
  return getRecipes().map((recipe) => ({ slug: recipe.slug }));
}

export default async function Image({ params }: { params: Promise<{ slug: string }> }) {
  const { slug } = await params;
  const recipe = getRecipe(slug);

  return new ImageResponse(
    (
      <div
        style={{
          width: "100%",
          height: "100%",
          display: "flex",
          flexDirection: "column",
          justifyContent: "space-between",
          padding: 80,
          background: "#0b0c0e",
          color: "#f1f2f4",
        }}
      >
        <div style={{ fontSize: 36, color: "#9ba1ac" }}>{siteName}</div>
        <div style={{ fontSize: 96 }}>{recipe?.title ?? "Recipe"}</div>
        <div style={{ fontSize: 40 }}>{recipe ? `Ready in ${recipe.minutes} minutes` : ""}</div>
      </div>
    ),
    size,
  );
}
TSX

1200 by 630 pixels is the size most preview cards are designed around. The alt, size and contentType exports become the og:image:alt, og:image:width, og:image:height and og:image:type tags. The image file's own generateStaticParams makes Next.js render all three images at build time, so no image is drawn on a request.

The built-in font covers Latin text. If your titles use another script, such as Ge'ez for Amharic or Arabic for Hausa written in Ajami, check the image: missing glyphs are dropped or drawn as boxes. Load a font file that covers them and pass it through the fonts option of ImageResponse.

Bash
npm run build
Bash
npm run start

See which image the page now points to, then download it and read its size from the PNG header:

Bash
curl -s http://localhost:3000/recipes/jollof-rice | grep -oE '<meta property="og:image[^>]*>'
curl -s -o og-jollof.png -w '%{http_code} %{content_type} %{size_download} bytes\n' http://localhost:3000/recipes/jollof-rice/opengraph-image
node -e 'const b = require("fs").readFileSync("og-jollof.png"); console.log(b.toString("ascii", 1, 4), b.readUInt32BE(16) + "x" + b.readUInt32BE(20));'

Check it worked

The first command prints tags like <meta property="og:image" content="https://recipes.example.com/recipes/jollof-rice/opengraph-image?29c94a1ce23a6f3d"/>, plus og:image:type, og:image:width, og:image:height and og:image:alt. The text after ? is a hash of the image route, which changes when the image does, so share caches fetch the new one. The second prints 200 image/png and the file size, and the third prints PNG 1200x630. Open http://localhost:3000/recipes/jollof-rice/opengraph-image in a browser to see the card: the site name at the top, Jollof rice in large type, and the cooking time at the bottom. Your build may also add twitter: tags that reuse the same image.

Keep an eye on that byte count. Every chat app that shows a preview downloads the image, and many of your readers pay for those bytes on prepaid mobile data. Flat colours and text, as here, keep the file small; a full-bleed photo can make it many times larger.

The home page has no image yet. An opengraph-image.tsx in app/ itself would cover it, and the more specific file in app/recipes/[slug]/ would still win for recipe pages.

Stop the server with Ctrl+C.

Step 6 · Add a sitemap and robots.txt

app/sitemap.ts returns a list of URLs and Next.js serves it as /sitemap.xml. app/robots.ts returns crawl rules and serves /robots.txt. Both build from the same recipe data as the pages, so a new recipe appears in the sitemap without anyone editing it by hand. URLs in a sitemap must be absolute; metadataBase does not apply here, so build them from siteUrl.

Bash
cat > app/sitemap.ts <<'TS'
import type { MetadataRoute } from "next";
import { getRecipes } from "@/lib/recipes";
import { siteUrl } from "@/lib/site";

export default function sitemap(): MetadataRoute.Sitemap {
  const recipes = getRecipes();
  const newest = recipes.map((recipe) => recipe.updated).sort().at(-1);

  return [
    { url: siteUrl, lastModified: newest },
    ...recipes.map((recipe) => ({
      url: new URL(`/recipes/${recipe.slug}`, siteUrl).toString(),
      lastModified: recipe.updated,
    })),
  ];
}
TS
cat > app/robots.ts <<'TS'
import type { MetadataRoute } from "next";
import { siteUrl } from "@/lib/site";

export default function robots(): MetadataRoute.Robots {
  return {
    rules: { userAgent: "*", allow: "/", disallow: "/drafts/" },
    sitemap: new URL("/sitemap.xml", siteUrl).toString(),
  };
}
TS

lastModified uses each recipe's real update date. Setting it to new Date() on every build tells crawlers that every page changed every time you deploy, which teaches them to ignore the field. The /drafts/ rule is an example of a path to keep crawlers out of. robots.txt is a polite request, not access control: anything private still needs authentication.

Bash
npm run build
Bash
npm run start
Bash
curl -s http://localhost:3000/sitemap.xml
curl -s http://localhost:3000/robots.txt

Check it worked

The build's route table now lists /sitemap.xml and /robots.txt as static. The sitemap is a <urlset> with four <url> entries: the home page with <lastmod>2026-11-10</lastmod>, the newest recipe date, and one entry per recipe with its own date. robots.txt reads:

Text
User-Agent: *
Allow: /
Disallow: /drafts/

Sitemap: https://recipes.example.com/sitemap.xml

Every <loc> in the sitemap matches a canonical link from the earlier steps. If they differ, search engines get two answers to the question "which address is the real one".

Stop the server with Ctrl+C.

Step 7 · Check the site before you deploy it

Two things often go wrong after deployment, and both are quick to catch.

First, SITE_URL is read at build time for prerendered pages. If your host builds the site without it, every canonical link, og:url, image URL and sitemap entry says http://localhost:3000. On Vercel or any other host, either commit .env.production as here, or set SITE_URL in the host's environment settings for production builds. After a deploy, run a quick search of the live HTML for the wrong host:

Bash
curl -s https://your-domain.example/ | grep -c 'localhost:3000'

Replace your-domain.example with your domain. The count should be 0. You can run the same check now against the local build, where every address should already use https://recipes.example.com:

Bash
grep -rl 'localhost:3000' .next/server/app --include='*.html' --include='*.body' || echo "no localhost URLs in the build"

Second, preview cards are cached by the services that show them. Once the site is live, paste a recipe URL into a social network's preview or debugging tool, or send it to yourself in a chat app, and confirm the card shows the title, description and generated image. If you change the image later, the ? hash in og:image changes with it, which helps caches pick up the new version.

When you are finished with the demo, remove it:

Bash
cd ~
rm -rf ~/recipe-meta-demo

Check it worked

The local search prints no localhost URLs in the build. If it prints file names instead, the build ran without SITE_URL: check .env.production and build again. After the clean-up, ls ~/recipe-meta-demo reports that the folder does not exist.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.