Skip to article content
LESSON 22 / 28

Metadata, SEO, and content delivery

Publish discoverable content with correct metadata, URLs and preview behavior while respecting route and data boundaries.

What you will be able to do

  • Generate metadata from the same trusted content identity as the page.
  • Distinguish canonicalization, indexing and access control.
  • Design sitemap and social-preview output.
  • Avoid leaking draft or private content through metadata.

A page and its metadata describe one resource

A product page has visible content, a document title, a canonical URL and potentially social-preview data. These should describe the same product version and identity. If the page reads one record while metadata reads another stale or incorrectly keyed record, the browser and crawler receive contradictory information. Start with a shared data-access contract and explicit missing-record behavior.

Static metadata suits a fixed page; generateMetadata suits route-dependent content. Keep these exports on the server side. A Client Component can implement the interactive product controls while the route owns the document metadata. A good title should remain understandable when several tabs are open, not just repeat the application name.

Read route parameters using the current contract

Current App Router page parameters are asynchronous. Await them, load the target resource through the appropriate server-only adapter and construct a minimal metadata object. The example shows integration with an existing getPublicProduct function; that adapter must return only publishable content and handle authorization if the route is private.

Set metadataBase to the actual public origin for the application when relative metadata URLs are used. Avoid inferring it from an untrusted request header. Canonical URLs should represent the intended indexable identity, while tracking parameters usually do not create a new content identity. Whether pagination and filter combinations deserve separate canonical pages is a product/content decision.

Server execution

app/catalog/[id]/page.tsx
import type { Metadata } from "next";
import { notFound } from "next/navigation";
import { getPublicProduct } from "@/lib/catalog-data";

type Props = { params: Promise<{ id: string }> };
export async function generateMetadata({ params }: Props): Promise<Metadata> {
  const { id } = await params;
  const product = await getPublicProduct(id);
  if (!product) notFound();
  return {
    title: product.name + " | Practice Store",
    description: product.summary,
    alternates: { canonical: "/catalog/" + encodeURIComponent(id) },
  };
}
export default async function Page({ params }: Props) {
  const { id } = await params;
  const product = await getPublicProduct(id);
  if (!product) notFound();
  return <h1>{product.name}</h1>;
}

PAUSE AND PREDICT

A detail page shows product B but its metadata describes product A. What contract is broken?

Choose one answer, then check your reasoning.

This check does not mark the lesson as solved.

Sitemaps and previews need the same publishing rule

A sitemap helps expose intended public URLs; it is not a list of every possible private or filtered route. Generate entries from publishable records, include accurate modification dates only when available and avoid invented update times on every request. Robots rules influence crawler behavior but do not protect confidential content. Sensitive pages require actual access control.

Social images and descriptions can leak content even when the main interface is gated. Ensure preview endpoints, image generators and metadata use the same publication policy. When a title or image changes, consider the framework cache, your CDN and the external platform's own preview cache separately. Refreshing one layer cannot guarantee immediate refresh everywhere.

Structured content is still an injection boundary

JSON-LD can describe products or articles in a machine-readable form, but it must agree with visible content and be serialized safely. Do not concatenate untrusted fields into a script string. Escape characters that can end the script context, and avoid making claims such as ratings, prices or availability that the page cannot support.

Rich text and user-generated HTML need a sanitization strategy independent of metadata. React escaping for ordinary text is useful, but it does not justify inserting arbitrary HTML. Keep the first implementation small: correct title, description, canonical URL, accessible headings and a valid missing-page response. Add richer markup only when the underlying data is reliable.

PAUSE AND PREDICT

A confidential report is listed in robots.txt as disallowed. Is it protected?

Choose one answer, then check your reasoning.

This check does not mark the lesson as solved.

Inspect what different consumers receive

Check the actual response and browser document for a direct visit and a client navigation. Verify one intended title and canonical link, correct preview URLs and no private fields. Consider metadata streaming and crawler behavior in the documented version rather than assuming every tag arrives in the first response chunk under all conditions.

The exercise below builds a deterministic public identity from a fixed origin, product slug and bounded page number. It intentionally excludes arbitrary query parameters. After implementing it, explain which decisions are universal safety requirements and which are the catalogue's indexing policy. An interview answer becomes stronger when it separates technical mechanics from content strategy.

Misconceptions to replace

Compare the tempting shortcut with the model you can verify in code.

CLAIM TO CHALLENGEServer Components automatically guarantee discoverable content.
A more accurate model

Inspect delivered content, semantics, metadata, status and crawlable URLs.

How to check it

The server/client boundary and metadata guides distinguish rendering mechanics from content quality.

CLAIM TO CHALLENGEA gated page cannot leak through its preview.
A more accurate model

Titles, social images, descriptions and sitemaps must share the publication/access policy.

How to check it

Request preview and metadata routes directly as an unauthenticated caller.

Mistakes to catch in your own code

  • Using robots.txt as authorization.
  • Publishing draft records in a sitemap or social preview.
  • Generating canonical origins from untrusted headers.
  • Inventing lastModified or rating values.

Write it by hand

JavaScript logic playground

Build a canonical catalogue identity

Implement solve(input). This sandbox runs the lesson's logic with FrontendX's isolated code runner. Next.js server behavior is verified in the project lab below.

  1. Input is {origin,slug,page,title}; origin is a trusted HTTPS origin and slug/title are strings.
  2. Trim surrounding origin slashes at the end, URI-encode the entire slug, and append ?page=N only for an integer page greater than one.
  3. Trim title and fall back to Product if empty. Return {canonical,title} with the title suffix | Practice Store.

Tab moves to the next control. Use spaces to indent and return your answer from solve. Console output is not retained.

Ready when you are. Try the exercise before opening the worked solution.
Inspect 3 test cases
  1. Normal product

    Input

    {
      "origin": "https://example.test/",
      "slug": "blue-pen",
      "page": 1,
      "title": " Blue pen "
    }

    Expected

    {
      "canonical": "https://example.test/catalog/blue-pen",
      "title": "Blue pen | Practice Store"
    }
  2. Encode a slug as one segment

    Input

    {
      "origin": "https://example.test",
      "slug": "pens/blue",
      "page": 2,
      "title": "Pens"
    }

    Expected

    {
      "canonical": "https://example.test/catalog/pens%2Fblue?page=2",
      "title": "Pens | Practice Store"
    }
  3. Fallback empty title and invalid page

    Input

    {
      "origin": "https://example.test",
      "slug": "book",
      "page": 0,
      "title": " "
    }

    Expected

    {
      "canonical": "https://example.test/catalog/book",
      "title": "Product | Practice Store"
    }
Reveal the worked solution and reasoning
solution.js
function solve(input) {
  const origin = input.origin.replace(/\/+$/, "");
  const page = Number.isInteger(input.page) && input.page > 1 ? input.page : 1;
  const canonical = origin + "/catalog/" + encodeURIComponent(input.slug) + (page > 1 ? "?page=" + page : "");
  const title = (input.title.trim() || "Product") + " | Practice Store";
  return { canonical, title };
}

Encoding the complete slug prevents its slash from silently changing route structure.

The origin is trusted by contract; production code must validate configuration before this function.

Keeping page two distinct is this exercise's policy, not a universal canonicalization rule.

Verify it in a real Next.js application

Next.js application lab

Inspect product metadata and add a public-site contract

Open the local application route /catalog/keyboard after starting the workbench. Follow the experiment and collect the evidence described below.

Make the change

  1. Load /catalog/keyboard directly and inspect app/catalog/[id]/page.tsx. The project already implements async params, generateStaticParams and generated product title/description; the root layout applies its title template.
  2. Compare the metadata and visible product heading on a direct visit and catalogue navigation. Visit an unknown product and inspect the not-found UI, robots directives and actual HTTP response, including any effects of streaming.
  3. Inspect app/robots.ts. It deliberately disallows crawling of this local training application; the fixture is not presented as a public production catalogue.
  4. Implementation extension: define metadataBase for a controlled public origin, add canonical metadata and build a sitemap containing only public catalogue records. Canonicals and a sitemap are not included in the current project.
  5. Implementation extension: define metadata and cache behavior for previews and unavailable products. Keep any indexing-policy changes confined to your separate deployment exercise.

Check the behavior

  • The existing product title and description identify the same product as the page content.
  • An unknown product renders the not-found experience. Check the actual status and noindex behavior instead of assuming every streamed not-found response can still change an already-sent status.
  • The local fixture retains its deliberate crawler exclusion, and no session token or private user record enters product metadata.
  • The new canonical and sitemap contract uses one trusted origin, excludes private/draft records and is verified in the running extension.
Review the application reasoning

The browser kata formats resource identity. Generated metadata already runs in the real project; canonical URLs, sitemap publication and deployment indexing policy remain explicit work to implement.

Open the project files and run instructions

A complete App Router application with catalogue routing, cart state, a task dashboard, practice sessions, tenant checks, cached data, hydration repairs, and HTTP streaming. Next.js 16.4.6 and React 19.3.0 are pinned in the project.

The playground opens a new editable copy. A local Node.js 22.14+ installation also runs the project. Use the local production build when measuring caching, streaming, or deployment behavior.

Terminal
cd nextjs-interview-lab
npm ci
npm run dev

# In a second terminal
npm test

# Stop dev, then verify the production application
npm run build
npm start

# In a second terminal, install the test browser once
npx playwright install chromium
npm run test:e2e

Open http://localhost:3003. The project includes a credential-free practice account selector and a single-process file store. Those choices make experiments reproducible; the security and deployment lessons show what a production system needs.

Explain it in an interview

Give your answer aloud before opening the explanation. Then answer the follow-ups using your implementation as evidence.

  1. 01Why keep metadata in the server route?

    The route knows the content identity and can derive document metadata from trusted data before or during server delivery. Interactive widgets can remain client components without owning the document contract.

    I keep a consistent lookup between metadata and page content and define the missing-resource path. I also verify the actual output after client navigation.

    Follow-up questions

    • How do you avoid duplicate lookups?
    • What if the product is not published?
  2. 02What does a canonical URL do, and what does it not do?

    It signals the preferred content identity for indexing when similar URLs exist. It does not redirect the browser, secure the resource or guarantee a search engine will use that preference.

    I decide which filters or pages represent distinct useful content and omit tracking parameters from the canonical identity. Redirect policy is a separate routing decision.

    Follow-up questions

    • Should page two canonicalize to page one?
    • What about localized alternatives?
  3. 03How might metadata leak a private page?

    A title, description, social image or sitemap can reveal a record even when the visible page requires login. Those outputs must respect the same publication and authorization policy.

    I test the metadata and preview routes directly as an unauthenticated caller, and ensure caches do not share private output between users.

    Follow-up questions

    • Can noindex replace authentication?
    • What should a preview route return for a draft?
  4. 04Does using Server Components automatically guarantee good SEO?

    No. The important content still needs to be available to the intended consumer, with correct semantics, metadata and crawlable URLs. Both server and client components can contribute initial HTML.

    I inspect real output and route behavior instead of inferring discoverability from a component label. Content hidden behind interaction is a separate concern.

    Follow-up questions

    • What does a non-JavaScript crawler receive?
    • How do you check status for a missing record?

Check your understanding

Answer these without reopening the worked examples. The feedback explains the reasoning and the misconception behind each choice.

FINAL KNOWLEDGE CHECK

Two filtered catalogue URLs differ only by tracking parameters. How should canonicalization be reasoned about?

Choose one answer, then check your reasoning.

This check does not mark the lesson as solved.

Your checkpoint

Mark what you can do independently

Loading your local progress.

Sources and further reading

© 2026 FrontendX. All rights reserved.