Next.js Course
Next.js
/
Beginner

Metadata API

Definition

The built-in Next.js system for defining `<head>` elements like `<title>`, `<meta name="description">`, and favicons.

Explain Like I'm New

If you don't define a Title, the Google tab just shows the raw URL, which looks terrible. In Next.js, you just export a `metadata` object from your `page.tsx` or `layout.tsx`, and Next.js perfectly injects it into the HTML head for you.

Real World Example

Setting the global website title ('My Cool Startup') in the root `layout.tsx`, and overriding it with a specific title ('Pricing | My Cool Startup') on the pricing page.

Common Use Cases

  • •Search Engine Optimization (SEO)
  • •Browser tab titles
  • •Favicons

Interactive Example

// app/layout.tsx (Global Metadata)
import { Metadata } from 'next';

export const metadata: Metadata = {
  title: {
    // A powerful template feature!
    // If a child page exports 'About', the title becomes 'About | Acme Corp'
    template: '%s | Acme Corp',
    default: 'Acme Corp - The best widgets',
  },
  description: 'Buy the best widgets in the world.',
};

// app/pricing/page.tsx (Page-Specific Metadata)
export const metadata: Metadata = {
  title: 'Pricing', // Generates: 'Pricing | Acme Corp'
  description: 'View our affordable pricing plans.',
};

export default function PricingPage() { return <h1>Pricing</h1> }

Interview Questions

basic

  • What object must you export from a `page.tsx` file to set the page title?

intermediate

  • Can you export the `metadata` object from a Client Component (`'use client'`)?

Flash Cards

Question

What object?

Click to reveal answer
Answer

The `metadata` object.

Question

From Client Component?

Click to reveal answer
Answer

No! Metadata must be generated on the server so it is present in the initial HTML sent to Google's crawlers. It only works in Server Components.