Skip to content
Styling & OptimizationChapter 28 / 34Intermediate5 min read

Metadata & SEO

Next.js metadata for SEO with the metadata object, generateMetadata, metadataBase, canonical URLs, Open Graph and JSON-LD in the App Router.

On this page

1. What is metadata and SEO?

There are two ways:

  • Static: export const metadata from layout.tsx or page.tsx.
  • Dynamic: export async function generateMetadata() when the title depends on data, such as a blog post's name.

2. Why does it matter?

Google and social apps understand a page through the tags in its head. Writing meta tags by hand on every page, plus duplicate titles and forgotten canonical links, hurts SEO.

Hand-written meta tagsMetadata API
Copy and paste head tags on every pageExport one typed object
Layout and page tags get duplicatedAutomatic merge from layout to page
Relative image URLs break on social appsAbsolute URLs through metadataBase
Typos go unnoticedAutocomplete and errors from the Metadata type

3. Where is it used?

PageMetadata
Root layoutSite name, title template, metadataBase
Blog postThe post's title and description through generateMetadata
Product pageOpen Graph image, JSON-LD with the price
Duplicate URLs (filters, query params)alternates.canonical
Admin pagesrobots: { index: false }

4. How does it work?

Order of metadata resolution
Root layout metadata
Nested layout metadata
Page metadata or generateMetadata
Next.js merges everything, and the deeper segment overrides
Final tags in the HTML head

metadata and generateMetadata can only be exported from Server Components. You cannot export both from the same segment.

5. Code example

Root layout: base and template

tsx
import type { Metadata } from "next";

export const metadata: Metadata = {
  metadataBase: new URL("https://znpedia.com"),
  title: {
    default: "ZnPedia",
    template: "%s | ZnPedia",
  },
  description: "Learn web development in simple language.",
  openGraph: {
    siteName: "ZnPedia",
    locale: "ur_PK",
    type: "website",
  },
  twitter: { card: "summary_large_image" },
};

Dynamic page: generateMetadata

tsx
import type { Metadata } from "next";
import { getPost } from "@/lib/posts";

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

export async function generateMetadata({ params }: Props): Promise<Metadata> {
  const { slug } = await params;
  const post = await getPost(slug);

  return {
    title: post.title,
    description: post.excerpt,
    alternates: { canonical: `/blog/${slug}` },
    openGraph: {
      title: post.title,
      images: [{ url: post.cover, width: 1200, height: 630 }],
      type: "article",
    },
  };
}

export default async function Page({ params }: Props) {
  const { slug } = await params;
  const post = await getPost(slug);

  const jsonLd = {
    "@context": "https://schema.org",
    "@type": "Article",
    headline: post.title,
    datePublished: post.publishedAt,
  };

  return (
    <article>
      <script
        type="application/ld+json"
        dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd).replace(/</g, "\\u003c") }}
      />
      <h1>{post.title}</h1>
    </article>
  );
}

How does the code work?

ItemMeaning
metadataBaseTurns relative URLs (canonical, OG image) into absolute ones
title.templateA child page's title replaces %s, for example "Closures | ZnPedia"
await paramsIn Next.js 16, params is a Promise
alternates.canonicalTells Google which URL is this page's original one
openGraph, twitterShare preview on WhatsApp, LinkedIn and X
JSON-LD scriptStructured data for rich results, with < escaped

6. Common mistakes

Mistake: Not setting metadataBase

Why? A relative Open Graph image or canonical URL does not become absolute, so the image does not show in social previews.

Better: Set metadataBase: new URL(production domain) in the root layout.

Mistake: Exporting metadata from a Client Component

Why? metadata and generateMetadata are supported only in Server Components, and in a use client file they are ignored or cause an error.

Better: Keep the page a Server Component and move the interactive part into a separate Client Component.

Mistake: Using the same description on every page

Why? Google treats duplicate descriptions as a weak signal and builds its own snippet.

Better: Write a unique description for each page, and build it from the data on dynamic pages.

Mistake: Forgetting canonical when one page opens at several URLs

Why? URLs with query params or filters become duplicate content and ranking gets split.

Better: Use alternates.canonical to point to the original URL.

Interview tip

"What is the difference between static metadata and generateMetadata?" A static object is fixed at build time. generateMetadata is an async function that fetches params and data to build different metadata for each route.

7. What to learn before and after

Final quick revision

PointDetail
Static metadataexport const metadata: Metadata
Dynamic metadataexport async function generateMetadata
Absolute URLsmetadataBase in the root layout
Duplicate URLsalternates.canonical
Social previewopenGraph and twitter
Structured dataA JSON-LD script tag in the page