Skip to content
Tutorials Center
My learning

Topics

Lesson 46 of 72 ยท Optimization and SEO

Metadata and SEO

Set titles, descriptions, Open Graph cards, canonical URLs, sitemaps, robots rules and JSON-LD in the Next.js App Router, and learn how metadata merges.

Search engines and social networks read the <head> of your page long before they care about your design. The title decides the blue link in search results. The description becomes the snippet. The Open Graph tags decide the picture and headline when someone pastes your URL into a chat. In a plain React app you would reach for a library to manage all this. The App Router has it built in: you describe the metadata as data, and Next.js writes the tags.

This lesson covers the two ways to describe metadata (a static object and a function), title templates, Open Graph and canonical URLs, how metadata from layouts and pages merges, and the crawler files sitemap.ts and robots.ts. It ends with structured data in JSON-LD. The framework itself cannot run on this site, so its code is read-only. Two Node stand-ins run the parts that are easy to get wrong: the merge rules and the safe serialization of JSON-LD.

Metadata, as data

metadata A static object exported from a layout or page.
generateMetadata A function when the values depend on data.
Tags written for you Title, description, Open Graph, robots.
1 / 2

The static metadata object

Export a constant named metadata from a layout.tsx or page.tsx. It must be a Server Component file, because metadata is produced on the server.

TSX
// app/layout.tsx (read-only)
import type { Metadata } from "next";

export const metadata: Metadata = {
  metadataBase: new URL("https://example.com"),
  title: {
    default: "Example Shop",
    template: "%s | Example Shop",
  },
  description: "Handmade ceramics shipped worldwide.",
  openGraph: {
    siteName: "Example Shop",
    type: "website",
  },
};

A few fields to know:

  • title is a string or an object. With the object form, default is used when a child route sets no title, and template is applied to the titles of child segments: %s is replaced by the child's title. A page that exports title: "Mugs" under this layout becomes Mugs | Example Shop. A layout's template does not change that same layout's own title.
  • title: { absolute: "Welcome" } ignores any template from parent layouts. Use it for the home page or a landing page that needs an exact title.
  • description is the snippet candidate. Aim for roughly 120 to 160 characters.
  • metadataBase is the base URL used to turn relative paths (in alternates, openGraph.images and so on) into absolute ones. Set it once in the root layout. Open Graph images must be absolute URLs, so skipping this is a common source of broken previews.

Dynamic metadata with generateMetadata

When the title depends on data, export an async function named generateMetadata. It receives the same route parameters as the page. In recent versions params is a promise, so you await it.

TSX
// app/products/[slug]/page.tsx (read-only)
import type { Metadata } from "next";
import { notFound } from "next/navigation";
import { getProduct } from "@/lib/data/products";

type Props = { params: Promise<{ slug: string }> };

export async function generateMetadata({ params }: Props): Promise<Metadata> {
  const { slug } = await params;
  const product = await getProduct(slug);
  if (!product) return { title: "Product not found" };
  return {
    title: product.name,
    description: product.summary,
    alternates: { canonical: `/products/${product.slug}` },
    openGraph: {
      title: product.name,
      images: [{ url: product.image, width: 1200, height: 630, alt: product.name }],
    },
  };
}

export default async function ProductPage({ params }: Props) {
  const { slug } = await params;
  const product = await getProduct(slug);
  if (!product) notFound();
  return <h1>{product.name}</h1>;
}

getProduct is called twice, once for the head and once for the body. That is fine: if the function uses fetch, identical requests are deduplicated within one render, and if it queries a database you can wrap it in React's cache as shown in Data Access Layers and ORMs. A segment can export metadata or generateMetadata, never both.

generateMetadata also receives a second argument, parent, a promise of the metadata resolved so far. It is handy to extend, not replace, a list such as Open Graph images:

TSX
// read-only
export async function generateMetadata({ params }: Props, parent: ResolvingMetadata): Promise<Metadata> {
  const previous = (await parent).openGraph?.images ?? [];
  return { openGraph: { images: ["/cover.png", ...previous] } };
}

Open Graph, Twitter and canonical URLs

Open Graph is a set of og: tags that Facebook, LinkedIn, Slack, Discord and many others read to build a link preview. The twitter field does the same for X. The alternates.canonical field creates <link rel="canonical">, which tells search engines which URL is the main one when the same content is reachable through several (query strings, tracking parameters, a www variant).

TSX
// read-only
export const metadata: Metadata = {
  alternates: { canonical: "/blog/seo-basics" },
  openGraph: {
    title: "SEO basics",
    type: "article",
    publishedTime: "2026-01-12T09:00:00Z",
    images: ["/og/seo-basics.png"],
  },
  twitter: { card: "summary_large_image" },
  robots: { index: true, follow: true },
};

To keep a page out of search results, set robots: { index: false }. You can also generate the image by code with an opengraph-image.tsx file, which was covered in Templates and Other Special Files.

How metadata merges

Metadata is collected from the root layout down to the page, and later segments win. The important detail is that the merge is shallow. Next.js replaces whole top-level fields; it does not merge inside them. If the root layout sets openGraph: { siteName, type } and a page sets openGraph: { title }, the page's object replaces the layout's, and siteName is gone from the final head. If you want both, repeat the shared values in the page.

The stand-in below implements these rules in a few lines: the title template, absolute, the shallow replacement, and how metadataBase resolves relative URLs. It is a model, and the real resolver handles many more fields, but the rules shown here are the real ones.

Node.js Merging metadata from layout to page

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Read the output carefully. The title came out as Blue mug | Example Shop because the root template applied to the page's string title. The description is the one from the products layout, because it was set later. And there is no og:site_name or og:type: the page's openGraph replaced the layout's whole object. The relative canonical and image paths became absolute because of metadataBase.

sitemap.ts and robots.ts

A sitemap lists the URLs you want crawled, and robots.txt tells crawlers where they may go. You saw the static forms already. In a real site the sitemap comes from your data:

TypeScript
// app/sitemap.ts (read-only)
import type { MetadataRoute } from "next";
import { listProducts } from "@/lib/data/products";

export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
  const products = await listProducts();
  return [
    { url: "https://example.com/", lastModified: new Date() },
    ...products.map((p) => ({
      url: `https://example.com/products/${p.slug}`,
      lastModified: p.updatedAt,
    })),
  ];
}
TypeScript
// app/robots.ts (read-only)
import type { MetadataRoute } from "next";

export default function robots(): MetadataRoute.Robots {
  return {
    rules: [{ userAgent: "*", allow: "/", disallow: ["/admin", "/cart"] }],
    sitemap: "https://example.com/sitemap.xml",
  };
}

Remember that robots.txt is a request, not a lock: a disallowed URL can still be visited by anyone, and it can still appear in results if other sites link to it. To keep a page out of an index, use robots: { index: false } in its metadata instead, and protect private pages with real authentication (see Authentication and Sessions). Very large sites (over 50,000 URLs) split the sitemap into several files; the framework has a generateSitemaps helper for that.

Structured data with JSON-LD

JSON-LD is structured data that tells search engines what a page is: a product, an article, a recipe, an event. It can earn rich results such as star ratings. There is no special metadata field for it. The recommended way is a <script type="application/ld+json"> tag rendered in your page component:

TSX
// app/products/[slug]/page.tsx (read-only)
export default async function ProductPage({ params }: Props) {
  const { slug } = await params;
  const product = await getProduct(slug);
  const jsonLd = {
    "@context": "https://schema.org",
    "@type": "Product",
    name: product.name,
    description: product.summary,
  };
  return (
    <section>
      <script
        type="application/ld+json"
        dangerouslySetInnerHTML={{
          __html: JSON.stringify(jsonLd).replace(/</g, "\\u003c"),
        }}
      />
      <h1>{product.name}</h1>
    </section>
  );
}

The .replace(/</g, ...) is not decoration. The JSON contains text from your database. If a product name contains </script>, an unescaped payload would end your script tag and let the rest run as HTML, a cross-site scripting (XSS) hole. Writing < as the escape < keeps the JSON equal in meaning while making it harmless inside HTML. Try it:

Node.js Safe JSON-LD serialization

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The unsafe version contains a literal closing script tag in the middle. The safe version has none, yet parsing it returns the original name.

A short SEO checklist

  • Every page has a unique title and description; use the template for the site name.
  • Set metadataBase once, and give share-worthy pages an Open Graph image.
  • Add a canonical URL where the same content has several addresses.
  • Ship sitemap.ts and robots.ts; use index: false to hide pages.
  • Render content on the server (see React Server Components); crawlers then see the text without running JavaScript.
  • Escape JSON-LD, and validate it with a structured data testing tool before release.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. The root layout sets title.template to '%s | Shop' and a page exports title: 'Mugs'. What is the final title?

    The template of a parent layout is applied to the title of its child segments, replacing %s with the child's title.
  2. 2. The layout sets openGraph: { siteName, type } and a page sets openGraph: { title }. What does the final openGraph contain?

    Metadata merging is shallow: later segments replace whole top-level fields, so repeat shared values in the page if you need them.
  3. 3. Why use metadataBase?

    Open Graph images and similar fields need absolute URLs; metadataBase supplies the origin for relative paths.
  4. 4. Why is JSON.stringify(jsonLd).replace(/</g, '\u003c') used when rendering JSON-LD?

    Data from users or a database may contain a closing script tag. Escaping the less-than sign keeps the JSON valid while preventing an XSS injection.
  5. 5. Which is the right way to keep a page out of search results?

    robots.txt only asks crawlers not to fetch a URL and does not stop it being listed. The noindex directive in metadata is the way to ask for exclusion from the index.

Summary

  • Export a metadata object, or an async generateMetadata function (never both), from a layout or page; both are Server Component features.
  • Use title.template and title.default in layouts, title.absolute to opt out, and metadataBase to resolve relative URLs.
  • Metadata merges from layout to page, shallowly: whole fields such as openGraph are replaced, not combined.
  • alternates.canonical, openGraph, twitter and robots cover the common head tags.
  • sitemap.ts and robots.ts generate the crawler files from code and data; robots.txt is a request, not access control.
  • Render JSON-LD in a script tag and escape < so data cannot break out of it.

Next: Styling in Next.js