Skip to content

Lesson 16 of 27Full-stack

Metadata and Images

Ship titles, OG images, sitemaps and robots rules, and load images and fonts fast enough to pass Core Web Vitals.

22 min read0/7 questions

Two things decide whether people find and stay on your site: what search engines and link previews show, and how fast the page feels. Next.js has built-in tools for both: the Metadata API for <head> tags, special files for OG images, sitemaps and robots rules, and next/image plus next/font for loading assets without hurting performance scores.

The Metadata API

Instead of writing <head> tags by hand, you export metadata from a layout.tsx or page.tsx, and Next.js renders the tags. For fixed values, export a metadata object:

app/layout.tsx
import type { Metadata } from "next";
 
export const metadata: Metadata = {
  metadataBase: new URL("https://acme.dev"), // turns relative URLs into absolute ones
  title: { template: "%s | Acme", default: "Acme" },
  description: "Tools for small coffee roasters.",
  openGraph: { siteName: "Acme", type: "website" },
};

When metadata depends on data, export an async generateMetadata function instead. It receives the same params and searchParams Promises as the page:

app/blog/[slug]/page.tsx
import type { Metadata } from "next";
import { notFound } from "next/navigation";
import { getPost } from "@/lib/posts"; // wrapped in React.cache, so this does not query twice
 
export async function generateMetadata(props: PageProps<"/blog/[slug]">): Promise<Metadata> {
  const { slug } = await props.params;
  const post = await getPost(slug);
  if (!post) return {};
  return {
    title: post.title,                         // becomes "Post title | Acme"
    description: post.summary,
    alternates: { canonical: `/blog/${slug}` },
    openGraph: { title: post.title, description: post.summary, type: "article" },
  };
}
 
export default async function PostPage(props: PageProps<"/blog/[slug]">) {
  const { slug } = await props.params;
  const post = await getPost(slug);
  if (!post) notFound();
  return <article><h1>{post.title}</h1></article>;
}

Metadata exports only work in Server Components. Next.js always adds the charset and viewport tags for you.

One query for the page and its metadata

Look again at the example above. generateMetadata and the page both call getPost(slug). Without help, that is two database queries for one page view. Next.js removes the duplicate in two ways, and you should know which one you are relying on:

  • fetch is memoized automatically. The same URL with the same options, called from generateMetadata, generateStaticParams, layouts, pages and Server Components during one render, hits the network once.
  • Everything else needs React.cache. An ORM call, an SDK call or a file read is not a fetch, so wrap the loader once, in your data layer, as you saw in Data Fetching and Caching.
lib/posts.ts
import "server-only";
import { cache } from "react";
import { db } from "@/lib/db";
 
export const getPost = cache(async (slug: string) => {
  return db.post.findUnique({ where: { slug } });
});

The catch that bites people: this memo lives for one request only. The opengraph-image.tsx for the same post is a separate request to a separate route, so it starts with an empty memo and queries again. So does the next visitor. Run the simulation to see the count:

TypeScriptrequest-memo.ts
let queries = 0; // A tiny stand-in for React.cache: one Map per requestfunction makeCache() { const seen = new Map<string, Promise<{ slug: string; title: string }>>(); return (slug: string) => { if (!seen.has(slug)) { queries++; seen.set(slug, Promise.resolve({ slug, title: "Hello" })); } return seen.get(slug)!; };} async function handleRequest(name: string, calls: number) { const getPost = makeCache(); // a fresh cache for every request for (let i = 0; i < calls; i++) await getPost("hello"); console.log(name.padEnd(22), "queries so far:", queries);} async function main() { await handleRequest("page + generateMetadata", 2); await handleRequest("opengraph-image", 1); await handleRequest("page again (new visit)", 2);}main();
Output
Press Run (⌘ Enter) to see what happens.

To share the result across requests, cache the loader itself with "use cache" and a cacheTag so a Server Action can invalidate it when the post is edited. Then the page, its metadata and its OG image all read the same cached entry. Cache Components in Depth covers lifetimes and tags in detail. One rule to remember here: with Cache Components on, generateMetadata follows the same rules as any component. If it reads params, cookies() or uncached data while the rest of the page is fully static, the build stops and asks you to choose: cache the data with "use cache", or mark the page as intentionally dynamic.

Two more habits from production code. First, call notFound() in the page, not in generateMetadata; returning {} (or a "Post not found" title) from metadata is fine because the page will throw to the 404 boundary anyway. Second, never put secrets or per-user data in metadata. It is rendered into public HTML and often cached for everyone.

Streaming metadata and bots

Since Next.js 15.2, generateMetadata does not hold up the page. The server sends the first HTML straight away and appends the metadata tags to <body> when the function resolves. Browsers and crawlers that run JavaScript and read the full DOM, such as Googlebot, handle this correctly.

Some bots only read the raw HTML: link unfurlers like facebookexternalhit, chat apps and many SEO tools. Next.js detects these HTML-limited bots from the User-Agent header and, for them only, waits for metadata and puts it in <head> as before.

Same page, two kinds of visitor
BrowserNext.jsLink unfurlerGET /blog/helloshell HTML now<title>, og tags (in body)GET /blog/helloHTML with tags in <head>

A normal browser request. The User-Agent does not match the HTML-limited bot list.

1/5

You can extend the bot list with the htmlLimitedBots regex in next.config.ts, or set it to /.*/ to turn streaming off for everyone. The default is right for nearly every app. If a share preview is missing, check two things before blaming streaming: open the raw HTML with curl -A "facebookexternalhit/1.1" and confirm the tags are there, and confirm the image URL is absolute (that is what metadataBase is for).

How metadata merges

Metadata is collected from the root layout down to the page. Each level shallowly merges into the one above: a key the page sets replaces the parent's value for that key, and keys it does not set are inherited. A layout's title.template applies to titles defined below it.

Resolving metadata for /blog/hello
  1. app/layout.tsxtitle.template "%s | Acme", description, openGraph.siteName
  2. app/blog/layout.tsxdescription: "Notes from the roastery"
  3. app/blog/[slug]/page.tsxgenerateMetadata: title "Hello", openGraph.title
  4. Final <head><title>Hello | Acme</title>, blog description, page openGraph

The root layout sets defaults for the whole site, including the title template.

1/4
TypeScripttitle-template.ts
type LayoutTitle = string | { template: string; default: string }; function resolveTitle(layout: LayoutTitle, page?: string | { absolute: string }) { if (page && typeof page === "object") return page.absolute; if (typeof page === "string") return typeof layout === "object" ? layout.template.replace("%s", page) : page; return typeof layout === "object" ? layout.default : layout;} const root = { template: "%s | Acme", default: "Acme" };console.log(resolveTitle(root, "Pricing"));console.log(resolveTitle(root));console.log(resolveTitle(root, { absolute: "Acme: coffee tools for roasters" }));
Output
Press Run (⌘ Enter) to see what happens.
Predict the outputTypeScript

What does this print?

const template = "%s · Docs";
const titles = ["Routing", "Caching"];
console.log(titles.map((t) => template.replace("%s", t)).join(" / "));
Need a nudge? Hints walk you through it.
Quick check
A page file starts with "use client" and also exports metadata. What happens?
Need a nudge? A hint rules out a wrong answer.

OG images, sitemaps and robots

Some metadata is a whole file. Next.js recognises special file names in app/:

  • favicon.ico, icon.png, apple-icon.png: site icons.
  • opengraph-image.png (or .jpg): the preview image when a link is shared. Put one in a route folder to override it for that route.
  • opengraph-image.tsx: generate the image with code, using ImageResponse from next/og, which turns JSX and a subset of CSS (flexbox, not grid) into a PNG.
app/blog/[slug]/opengraph-image.tsx
import { ImageResponse } from "next/og";
import { getPost } from "@/lib/posts";
 
export const size = { width: 1200, height: 630 };
export const contentType = "image/png";
 
export default async function OgImage({ params }: { params: Promise<{ slug: string }> }) {
  const { slug } = await params;
  const post = await getPost(slug);
  return new ImageResponse(
    <div style={{ display: "flex", width: "100%", height: "100%", alignItems: "center", padding: 80, fontSize: 64, background: "#111", color: "#fff" }}>
      {post?.title ?? "Acme blog"}
    </div>,
    size,
  );
}

What ImageResponse can and cannot do

ImageResponse is not a browser. It uses Satori to turn your JSX into SVG and Resvg to turn that into a PNG, so it supports a deliberately small slice of the web platform. The limits you will hit:

  • Layout is flexbox and absolute positioning only. display: grid, float and most modern CSS are ignored. Every <div> with more than one child needs display: "flex" set explicitly, or the render fails.
  • Inline styles, no class names from your CSS. Tailwind classes and your global stylesheet are not loaded. Some setups support a tw prop, but plain style objects are the portable choice.
  • Fonts are ttf, otf or woff only, passed as raw bytes in the fonts option. woff2 does not work. Read the file once at module scope so every render reuses it, and load only the weights you use.
  • A 500 KB bundle limit covering your JSX, fonts, images and other assets. A couple of full font families pushes you over. Subset fonts, or fetch large assets at render time.
  • Size caps from the platforms. The build fails if a static opengraph-image is over 8 MB, or a twitter-image is over 5 MB. Aim for well under 1 MB anyway; unfurlers time out on slow images.
  • No emoji font of your own. Emoji are drawn from a hosted set chosen with the emoji option.

Caching matters too. An opengraph-image.tsx is a special Route Handler. By default it is generated at build time and cached, unless it reads request-time APIs or uncached data. For a blog post that is ideal: one image per post, created once. If it reads a database per request, every share of a popular link regenerates the PNG, which is slow and costs compute. Cache the data loader, as above, so regeneration stays cheap.

Also export an alt string next to size and contentType. It becomes og:image:alt, which screen readers in some apps announce. For several images from one file (for example, square and wide), use generateImageMetadata.

Quick check
Your OG image renders a two-column layout with display: grid. In the generated PNG everything is stacked or missing. Why?
Need a nudge? A hint rules out a wrong answer.

sitemap.ts and robots.ts return plain objects, and Next.js serves /sitemap.xml and /robots.txt:

app/sitemap.ts
import type { MetadataRoute } from "next";
import { getAllPosts } from "@/lib/posts";
 
export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
  const posts = await getAllPosts();
  return [
    { url: "https://acme.dev", lastModified: new Date() },
    ...posts.map((p) => ({ url: `https://acme.dev/blog/${p.slug}`, lastModified: p.updatedAt })),
  ];
}
app/robots.ts
import type { MetadataRoute } from "next";
 
export default function robots(): MetadataRoute.Robots {
  return {
    rules: { userAgent: "*", allow: "/", disallow: ["/dashboard/", "/api/"] },
    sitemap: "https://acme.dev/sitemap.xml",
  };
}

Here is roughly what a search result and a share card are built from. Edit the object and watch the preview:

Reactlink-preview.tsx
const meta = { title: "Hello | Acme", description: "How we roast small batches without burning the first crack.", url: "https://acme.dev/blog/hello", ogImage: "https://picsum.photos/seed/acme/600/315",}; export default function App() { return ( <div style={{ fontFamily: "system-ui", display: "grid", gap: 16, maxWidth: 420 }}> <div> <div style={{ fontSize: 12, color: "#4d5156" }}>{meta.url}</div> <div style={{ fontSize: 18, color: "#1a0dab" }}>{meta.title}</div> <div style={{ fontSize: 13, color: "#4d5156" }}>{meta.description}</div> </div> <div style={{ border: "1px solid #ddd", borderRadius: 8, overflow: "hidden" }}> <img src={meta.ogImage} alt="" width={420} height={220} style={{ display: "block", objectFit: "cover" }} /> <div style={{ padding: 8, fontWeight: 600 }}>{meta.title}</div> </div> </div> );}

Structured data with JSON-LD

Meta tags tell a search engine what a page is called. Structured data tells it what the page is: a product with a price and stock level, an article with an author and a publish date, a job posting with a salary range, an FAQ. Search engines use it for rich results (stars, prices, breadcrumbs), and AI search tools read it to understand entities. The standard format is JSON-LD: a JSON object using the schema.org vocabulary, inside a <script type="application/ld+json"> tag.

There is no special metadata key for it. You render the script tag yourself, in a layout or page, from the same data the page shows:

app/blog/[slug]/page.tsx
import type { BlogPosting, WithContext } from "schema-dts"; // types only, zero runtime cost
 
export default async function PostPage(props: PageProps<"/blog/[slug]">) {
  const { slug } = await props.params;
  const post = await getPost(slug);
  if (!post) notFound();
 
  const jsonLd: WithContext<BlogPosting> = {
    "@context": "https://schema.org",
    "@type": "BlogPosting",
    headline: post.title,
    datePublished: post.publishedAt.toISOString(),
    author: { "@type": "Person", name: post.author.name },
    image: `https://acme.dev/blog/${slug}/opengraph-image`,
  };
 
  return (
    <article>
      <script
        type="application/ld+json"
        dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd).replace(/</g, "\\u003c") }}
      />
      <h1>{post.title}</h1>
    </article>
  );
}

Two details in that snippet are the ones reviewers look for.

The .replace(/</g, "\\u003c") is a security fix, not decoration. JSON.stringify does not escape <. If a post title (or a product name from a seller, or a user's display name) contains </script>, the HTML parser closes your script tag early and runs whatever follows. That is a stored XSS hole in your SEO code. Replacing every < with the JSON escape < keeps the data identical once parsed, but the HTML parser never sees a tag. Run it:

TypeScriptjsonld-escape.ts
const post = { title: "Roasting tips</script><script>alert(1)</script>", author: "Sam" }; const jsonLd = { "@context": "https://schema.org", "@type": "BlogPosting", headline: post.title, author: { "@type": "Person", name: post.author },}; const unsafe = JSON.stringify(jsonLd);const safe = unsafe.replace(/</g, "\\u003c"); console.log("unsafe closes the tag:", unsafe.includes("</script>"));console.log("safe closes the tag: ", safe.includes("</script>"));console.log("same data after parse:", JSON.parse(safe).headline === post.title);
Output
Press Run (⌘ Enter) to see what happens.

It is a plain <script>, not next/script. next/script exists to load and run JavaScript with a strategy. JSON-LD is data that never executes, so a native tag rendered on the server is correct, and it is in the initial HTML where crawlers read it.

Keep the structured data honest: it must describe content that is visible on the page. Marking up reviews or prices the user cannot see breaks search engine guidelines and can cost you rich results for the whole site. Validate with Google's Rich Results Test or the Schema Markup Validator, and treat a broken schema like a broken test: put a check in CI for your key templates. Typing the object with schema-dts catches misspelled properties before they ship.

Predict the outputTypeScript

What does this print?

const s = JSON.stringify({ name: "a</b" }).replace(/</g, "\\u003c");
console.log(s);
console.log(JSON.parse(s).name);
Need a nudge? Hints walk you through it.

Fast images with next/image

Images are usually the heaviest thing on a page. The <Image> component from next/image wraps <img> and handles the hard parts:

  • Right size per device. It generates a srcset of widths and serves resized, compressed copies (WebP by default; add AVIF with images.formats in next.config.ts).
  • No layout shift. width and height (or a static import, which fills them in) reserve the space before the image loads.
  • Lazy by default. Off-screen images wait until the user scrolls near them.
app/page.tsx
import Image from "next/image";
import hero from "./hero.jpg"; // static import: width, height and blur placeholder are automatic
 
export default function Home() {
  return (
    <>
      <Image src={hero} alt="Roasted beans cooling in a tray" placeholder="blur" preload sizes="100vw" />
      <div className="grid grid-cols-1 md:grid-cols-3">
        <div className="relative aspect-square">
          <Image src="https://cdn.acme.dev/bag.png" alt="Bag of beans" fill sizes="(max-width: 768px) 100vw, 33vw" />
        </div>
      </div>
    </>
  );
}

The props that matter most:

  • sizes tells the browser how wide the image will be on screen at each breakpoint. Without it, the browser assumes 100vw and may download a far larger file than a 33%-wide grid tile needs. Always set it with fill or responsive CSS.
  • preload (new in Next.js 16, replacing the deprecated priority) adds a preload link in <head> for the hero image, the one most likely to be your Largest Contentful Paint. Use it on one image above the fold, or use loading="eager" or fetchPriority="high".
  • Remote images need their host allowed in next.config.ts with images.remotePatterns, so nobody can use your server to resize arbitrary images.

How does the browser pick from the srcset? It multiplies the slot width by the screen's pixel density and takes the smallest candidate that is big enough:

TypeScriptpick-width.ts
const widths = [640, 750, 828, 1080, 1200, 1920, 2048, 3840]; // Next.js default deviceSizes function pick(slotVw: number, viewport: number, dpr: number) { const needed = Math.ceil((viewport * slotVw) / 100 * dpr); return { needed, chosen: widths.find((w) => w >= needed) ?? widths.at(-1) };} console.log("phone, full width:", pick(100, 390, 3));console.log("laptop, 1/3 grid: ", pick(33, 1440, 2));console.log("no sizes (100vw): ", pick(100, 1440, 2));
Output
Press Run (⌘ Enter) to see what happens.

The last line is the cost of forgetting sizes: a grid tile downloads a 3840 px image instead of a 1080 px one.

Quick check
A product grid shows images with fill at one third of the screen width on desktop, with no sizes prop. What is the likely problem?
Need a nudge? A hint rules out a wrong answer.

Locking down next/image

The image optimizer is a server endpoint (/_next/image?url=...&w=...&q=...) that downloads a source image, resizes it, re-encodes it and caches the result on disk. Anyone on the internet can call it with any parameters. Its configuration is therefore an allowlist, and a loose one is an open door: people can use your server to resize their images on your bill, fill your disk cache with every combination of width and quality, or, worst case, make your server fetch URLs on your private network (server-side request forgery). Securing a Next.js App covers SSRF in general; here are the image-specific settings.

next.config.ts
import type { NextConfig } from "next";
 
const config: NextConfig = {
  images: {
    remotePatterns: [
      new URL("https://cdn.acme.dev/products/**"), // exact protocol, host and path prefix
      { protocol: "https", hostname: "images.ctfassets.net", pathname: "/space-id/**", search: "" },
    ],
    qualities: [60, 75],         // the only quality values the optimizer will produce
    formats: ["image/avif", "image/webp"],
    maximumRedirects: 0,         // do not follow a redirect to an unvetted host
    minimumCacheTTL: 60 * 60 * 4,
  },
};
 
export default config;

What each guard does:

  • remotePatterns should be as narrow as you can make it. Any part you leave out (protocol, port, pathname, search) is treated as a wildcard. { hostname: "storage.googleapis.com" } allows every bucket of every customer on that shared host, so pin the path to your own bucket. * matches one subdomain or path segment, ** matches many but only at the start of a hostname or the end of a path. A src that does not match gets a 400.
  • Redirects bypass the allowlist. The optimizer follows up to 3 redirects by default, and the redirect target is not checked against remotePatterns. If an allowed host can be made to redirect (an open redirect, a user-controlled short link), set maximumRedirects: 0.
  • Private IPs are blocked. dangerouslyAllowLocalIP defaults to false, so the optimizer refuses to fetch from internal addresses. Only turn it on for a self-hosted app inside a private network, and understand that it reopens the SSRF risk.
  • qualities is required from Next.js 16. The default is [75]. Every value you add is another variant per width that an attacker can make you compute and store. A quality prop outside the list is coerced to the closest allowed value, with a warning in development, so quality={80} silently becomes 75 until you add it.
  • SVG is off by default. An SVG can contain script. If you must serve SVGs through the optimizer, dangerouslyAllowSVG should go with the default contentDispositionType: "attachment" and a strict contentSecurityPolicy such as "default-src 'self'; script-src 'none'; sandbox;". Most teams simply add unoptimized to SVG images instead: they are already vector and do not benefit from resizing.
  • images.domains is deprecated. It cannot restrict protocol, port or path. If you see it in an older codebase, migrating it to remotePatterns is a quick, worthwhile security PR.

Finally, the optimizer has no cache invalidation. An optimized image lives for the larger of minimumCacheTTL and the upstream Cache-Control max-age. If you replace a file at the same URL, users may see the old one until it expires. Static imports avoid this because their URLs contain a content hash. For remote images that change, version the URL (?v=2, and allow that search value) instead of setting a huge TTL. Large sites often skip the built-in optimizer and use a loader that points at an image CDN; Performance and Bundle Size in Next.js discusses when that pays off.

Quick check
next.config.ts has remotePatterns: [{ hostname: "storage.example-cloud.com" }] and nothing else. Which request will the optimizer accept?
Need a nudge? A hint rules out a wrong answer.

Fonts with next/font

Loading a web font from Google Fonts at runtime adds a request to another domain and can make text jump when the font swaps in. next/font downloads the font at build time, self-hosts it with your other assets, and sets fallback metrics so the swap does not shift layout.

app/layout.tsx
import { Geist, Geist_Mono } from "next/font/google";
 
const sans = Geist({ subsets: ["latin"], variable: "--font-sans" });
const mono = Geist_Mono({ subsets: ["latin"], variable: "--font-mono" });
 
export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en" className={`${sans.variable} ${mono.variable}`}>
      <body className="font-sans">{children}</body>
    </html>
  );
}

Prefer variable fonts (one file covers every weight). For your own files, use localFont from next/font/local. Load fonts once, in the root layout.

Core Web Vitals

Google's Core Web Vitals are three field metrics that affect search ranking and how fast a site feels:

MetricMeasuresGood
LCP (Largest Contentful Paint)When the biggest element (often the hero image) appearsunder 2.5 s
INP (Interaction to Next Paint)How quickly the page responds to clicks and typingunder 200 ms
CLS (Cumulative Layout Shift)How much content jumps around while loadingunder 0.1
Match the pairs0/4 matched

Match each problem to the Next.js fix.

Choose an item, then its match on the other side.
ChallengeEasy

Resolve a page title with a template

A layout can export title: { template: "%s | Acme", default: "Acme" }. Child pages then set just their own name. Write resolveTitle(layoutTitle, pageTitle) that returns the final <title> text.

layoutTitle is null, a string, or { template, default }. pageTitle is null, a string, or { absolute }.

  • Page has { absolute }: use it as is.
  • Page has a string and the layout has a template: replace %s in the template with the page title.
  • Page has a string otherwise: use the page title.
  • Page has no title: use the layout's default (or the layout's string), or "" if there is nothing.
resolveTitle({ template: "%s | Acme", default: "Acme" }, "Blog")  → "Blog | Acme"
resolveTitle({ template: "%s | Acme", default: "Acme" }, null)    → "Acme"
TypeScript
type LayoutTitle = null | string | { template: string; default: string };type PageTitle = null | string | { absolute: string }; function resolveTitle(layout: LayoutTitle, page: PageTitle): string { return "";}
ChallengeMedium

Which image does the browser download?

next/image generates a srcset of widths, and the sizes prop tells the browser how wide the image will be on screen. The browser then downloads the smallest candidate that is wide enough.

Write pickWidth(candidates, slotVw, viewport, dpr):

  • the image's slot is slotVw percent of the viewport width (viewport CSS pixels)
  • the screen has dpr device pixels per CSS pixel
  • the needed width is Math.ceil(viewport * slotVw / 100 * dpr)
  • return the smallest candidate that is at least the needed width, or the largest candidate if none is

candidates may be unsorted.

pickWidth([640, 750, 828, 1080, 1200, 1920], 50, 1280, 2)  → 1280 needed → 1920
pickWidth([640, 750, 828, 1080, 1200, 1920], 100, 390, 3)  → 1170 needed → 1200
TypeScript
function pickWidth(candidates: number[], slotVw: number, viewport: number, dpr: number): number { return 0;}
Key terms
generateMetadata
An async export from a page or layout that returns a Metadata object built from params or fetched data.
title.template
A layout title setting like "%s | Acme" that wraps the titles of pages below it.
opengraph-image
A special file (image or .tsx using ImageResponse) that sets the link preview image for a route.
sizes
An <Image> prop describing the rendered width per breakpoint, so the browser downloads an appropriately sized file.
LCP
Largest Contentful Paint: when the biggest above-the-fold element appears. Under 2.5 seconds is good.
CLS
Cumulative Layout Shift: how much visible content moves during load. Under 0.1 is good.
JSON-LD
Structured data in schema.org vocabulary, rendered in a script type="application/ld+json" tag so search engines understand what the page describes.
remotePatterns
The next/image allowlist of remote image URLs. Omitted fields act as wildcards, so keep each pattern narrow.
HTML-limited bot
A crawler or link unfurler that reads raw HTML without running JavaScript. Next.js blocks on metadata for these so tags land in <head>.