Thuta Learning
Next.js
IntermediateWeb DevelopmentIntermediate

Metadata, SEO, and Social Sharing

Next.jsLesson 1130 min

What you'll walk away with

  • Set a title template and default in the root layout and predict the titles of child pages
  • Write generateMetadata for a title and description that depend on data
  • Explain that metadata is shallowly merged across segments, so openGraph is replaced as a whole
  • Configure metadataBase, an Open Graph image, sitemap.ts and robots.ts

Explain it simply

Metadata in plain language

Metadata is like the cover and back-cover text of a book. In a bookshop people see the cover before they open the book. On the web, a Google search result, a link preview in Facebook or Viber, and the browser tab are the cover people see before they open your page.

In Next.js you do not write <head> tags by hand; you export metadata from a layout or a page, and Next.js generates the <title>, the description meta tag and the og: tags for you.

Problem → Why → Solution

The problem: a 'Next App' tab and links without a preview

After Myanmar Notes launched, a teammate shared a note link on Facebook. The preview had no image and the title just said 'Next App', and all five open browser tabs showed the same name, so nobody could tell which tab held which note. To fix it, a developer exported metadata from the note page, but that file was "use client", so Next.js reported an error.

app/notes/[id]/page.tsx
"use client";
import { useState } from "react";

// Error: metadata is only supported in Server Components
export const metadata = { title: "Note" }; // and it would be the same for every note

export default function NotePage() {
  const [liked, setLiked] = useState(false);
  return <button onClick={() => setLiked(!liked)}>{liked ? "Liked" : "Like"}</button>;
}

Why this matters

Metadata must be resolved on the server before the page HTML is sent, so metadata exports are only allowed in Server Components. Identical titles make pages indistinguishable in search results and make shared links less tempting to click. Keeping the page a Server Component and moving only the Like button into a Client Component solves both problems.

Core concept: metadata assembled segment by segment

There are two ways to write metadata. For information that never changes, use export const metadata: Metadata = { ... }. For information that depends on data, such as a note's title, use export async function generateMetadata({ params }) and return a Metadata object. Both work only in layout.tsx and page.tsx, and both must be in Server Components. A single segment may not export both at once.

Next.js reads metadata in order from the root layout down to the page and merges it shallowly: when a later segment sets the same key, it replaces the earlier value. So if a page writes only openGraph: { title }, the layout's openGraph.description and images disappear, because nested fields are not combined. A page inherits the layout's openGraph only when it does not set openGraph at all.

For the title, the root layout usually holds { default: "Myanmar Notes", template: "%s | Myanmar Notes" }. The template applies only to titles from child segments, never to its own segment, which is why a template requires a default. A child page with title: "Routing" shows 'Routing | Myanmar Notes' in the tab, and title.absolute skips the template.

File (inside app/)What Next.js generates
favicon.ico, icon.png<link rel="icon"> tags
opengraph-image.png (or .tsx)og:image tags and the image URL
sitemap.tsthe /sitemap.xml route
robots.tsthe /robots.txt route

To write a relative path such as /og.png in URL fields like the Open Graph image, set metadataBase: new URL("https://your-domain") in the root layout; Next.js combines the two into an absolute URL. File-based metadata, such as an opengraph-image.png file, takes priority over the same setting in a metadata object. Put such a file inside a route folder and it applies to that route and the ones below it.

How metadata flows from root to page
  1. Root layout: default, template, base
  2. Nested layouts: per-section tweaks
  3. Page: its own title and description
  4. Same key: the later segment wins

Writing an object such as openGraph in a page replaces the layout's whole object; it is not merged.

General pattern

layout.tsx | page.tsx
import type { Metadata } from "next";

// static: values known in advance
export const metadata: Metadata = { title: "...", description: "..." };

// dynamic (instead of the object above, never both in one segment)
export async function generateMetadata(
  { params }: { params: Promise<{ key: string }> },
): Promise<Metadata> {
  const item = await loadItem((await params).key);
  return { title: item.title, description: item.summary };
}

Choose either the static object or generateMetadata per segment. generateMetadata receives the same params Promise as the page and returns a Metadata object.

Worked example: the root layout's metadata

Put this metadata in app/layout.tsx. Pay attention to the metadataBase field: the og.png image is given as the relative path /og.png, and according to the Next.js docs a relative path in a URL field without metadataBase causes a build error. metadataBase supplies the site's origin, so Next.js can turn /og.png into a full URL.

app/layout.tsx
import type { Metadata } from "next";

export const metadata: Metadata = {
  metadataBase: new URL("https://notes.example.com"),
  title: {
    default: "Myanmar Notes",
    template: "%s | Myanmar Notes",
  },
  description: "Learn from practical technology notes.",
  openGraph: {
    title: "Myanmar Notes",
    description: "Organize and save daily learning.",
    images: ["/og.png"],
  },
};

Code breakdown

  1. Base URLmetadataBase: new URL("https://notes.example.com"),

    The base that turns relative URLs into absolute ones. Social sites can only fetch og:image from an absolute URL.

  2. Fallback titledefault: "Myanmar Notes",

    The title used by child pages that set none, and by this layout's own home page. It is required whenever a template is set.

  3. Title templatetemplate: "%s | Myanmar Notes",

    %s is replaced by the child page's title: a page with "Routing" becomes "Routing | Myanmar Notes".

  4. Share previewimages: ["/og.png"],

    Uses public/og.png as the share preview; combined with metadataBase it becomes https://notes.example.com/og.png.

You should see
The home page's <head> contains tags like these (order and formatting may differ):
<title>Myanmar Notes</title>
<meta name="description" content="Learn from practical technology notes."/>
<meta property="og:title" content="Myanmar Notes"/>
<meta property="og:description" content="Organize and save daily learning."/>
<meta property="og:image" content="https://notes.example.com/og.png"/>

generateMetadata for detail pages, and crawler files

On the note detail page, generateMetadata receives the same params as the page. With fetch, Next.js memoizes identical requests made by generateMetadata and the page, so the network is called once. For a function that queries a database directly, wrap it in React's cache(). You can call notFound() inside generateMetadata too when the note is missing.

app/sitemap.ts
import type { MetadataRoute } from "next";
import { getAllNotes } from "@/lib/notes";

// served at /sitemap.xml
export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
  const notes = await getAllNotes();
  return notes.map((note) => ({
    url: `https://notes.example.com/notes/${note.id}`,
    lastModified: note.updatedAt,
  }));
}
app/robots.ts
import type { MetadataRoute } from "next";

// served at /robots.txt
export default function robots(): MetadataRoute.Robots {
  return {
    rules: { userAgent: "*", allow: "/", disallow: "/settings" },
    sitemap: "https://notes.example.com/sitemap.xml",
  };
}

Look at the generated files yourself

With the dev server running, open /sitemap.xml and /robots.txt in the browser. You will see your function's result turned into XML and plain text. This is where you catch wrong URLs or private pages before a search engine does.

In real projects

In real projects

For blogs, shops and documentation sites, metadata is the main front door for traffic. Search engines often use the description as the text under a result, and social apps show og:image as the preview card. Teams test these the way they test any other feature.

  • Product pages use generateMetadata to emit a description with the product name and price, plus the product photo as og:image.
  • app/blog/[slug]/opengraph-image.tsx draws a share image containing each post's title automatically with ImageResponse.
  • sitemap.ts lists every public page from the database, while robots.ts keeps crawlers out of private areas such as /settings.
  • Before deploying, teams check previews with tools such as the Facebook Sharing Debugger, because social sites cache a preview for a while once they have fetched it.

Common mistakes

Common mistakes with metadata

Exporting metadata from a Client Component

A file with "use client" may not export metadata or generateMetadata. Keep the page a Server Component and move the interactive part into a separate file.

Using the same title and description on every page

Relying only on the root layout's title makes every page look identical in search results, so nobody knows which one to click. Give every detail page a meaningful title and description through generateMetadata.

Overriding only part of openGraph

Writing only openGraph: { title: "Routing" } in a page drops the og:image set by the layout, so the preview loses its picture. Pull shared fields into a variable and spread them back with ...sharedOpenGraph, or use an opengraph-image file.

Best practices

Best practices

  • Keep metadataBase, the title template and the shared Open Graph image in one place: the root layout.
  • Write the description as one sentence of about 150-160 characters that states the page's main point.
  • When a page must change openGraph, spread the shared fields so the image is not lost.
  • Use the static object, not generateMetadata, for metadata that does not depend on data.

Mini challenge

Mini challenge: metadata for the note detail page

Write generateMetadata for app/notes/[id]/page.tsx. The browser tab must show the note's title (the root template turns it into '... | Myanmar Notes'), the description must be roughly the first 150 characters of the content, and the share image must not be lost.

  • Await params and load the note with getNote(id)
  • Call notFound() when the note is missing
  • An excerpt helper cuts text longer than 150 characters and adds …
  • openGraph includes title, description and the /og.png image
app/notes/[id]/page.tsx
import type { Metadata } from "next";
import { notFound } from "next/navigation";
import { getNote } from "@/lib/notes";

// TODO: return text unchanged if it is short, otherwise cut it and add "…"
function excerpt(text: string, max = 150): string {}

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

export async function generateMetadata({ params }: Props): Promise<Metadata> {
  // TODO: load the note, call notFound() if missing
  // TODO: return title, description and openGraph (keep the /og.png image)
}

// (the page component from lesson 8 stays below)

Expected: /notes/routing shows 'Routing basics | Myanmar Notes' in the tab, and the description is at most 150 characters. The share preview shows the note title with the og.png image, and an unknown id gives a 404.

Show hint

In excerpt, return text when text.length <= max, otherwise text.slice(0, max - 1).trimEnd() + "…". Remember that writing openGraph in the page replaces the layout's version, so add images back.

Show solution
app/notes/[id]/page.tsx
import type { Metadata } from "next";
import { notFound } from "next/navigation";
import { getNote } from "@/lib/notes";

function excerpt(text: string, max = 150): string {
  if (text.length <= max) return text;
  return text.slice(0, max - 1).trimEnd() + "…";
}

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

export async function generateMetadata({ params }: Props): Promise<Metadata> {
  const { id } = await params;
  const note = await getNote(id);
  if (!note) notFound();

  const description = excerpt(note.content);
  return {
    title: note.title, // becomes "Routing basics | Myanmar Notes"
    description,
    openGraph: { title: note.title, description, images: ["/og.png"] },
  };
}

Quick quiz 1 / 3

The root layout has title: { default: "Myanmar Notes", template: "%s | Myanmar Notes" } and app/about/page.tsx exports title: "About". What is the tab title of /about?

Quick quiz 2 / 3

A layout sets openGraph: { title, description, images } and a page exports only openGraph: { title: "Blog" }. What is the page's final openGraph?

Quick quiz 3 / 3

Where can generateMetadata be exported from?

What to remember

  • Use the metadata object for static values and generateMetadata for data-driven ones, in Server Component layouts and pages.
  • title.template applies only to child segments, and a template requires a default.
  • Metadata is merged shallowly across segments, so objects such as openGraph are replaced as a whole.
  • metadataBase turns relative URLs into absolute ones, and Next.js handles icon, opengraph-image, sitemap.ts and robots.ts files for you.

Next.js — Metadata and OG Images — Next.js

Next.js — Metadata and OG Images — Next.js

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Metadata, SEO, and Social Sharing | Thuta Learning