Skip to main content

Lesson 4 of 10

SEO & Metadata API

Next.js 13+ Metadata API provides a type-safe way to set page titles, descriptions, Open Graph tags, and Twitter cards - all server-rendered for search engine visibility. Dynamic metadata functions receive route params for per-page customization.

20 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Static & Dynamic Metadata

Static & Dynamic Metadata
import type { Metadata, ResolvingMetadata } from 'next';

// ---- Static metadata ----
// app/about/page.tsx
export const metadata: Metadata = {
  title: 'About Us',          // combined with root layout → 'About Us | My App'
  description: 'Learn about our mission and team.',
  openGraph: {
    title: 'About Us | My App',
    description: 'Learn about our mission and team.',
    type: 'website',
    url: 'https://myapp.com/about',
    images: [{ url: 'https://myapp.com/og/about.jpg', width: 1200, height: 630 }],
  },
  twitter: {
    card: 'summary_large_image',
    site: '@myapp',
    creator: '@myapp',
  },
};

// ---- Dynamic metadata - per route segment ----
// app/products/[id]/page.tsx
interface Props {
  params: { id: string };
  searchParams: { [key: string]: string | string[] | undefined };
}

// generateMetadata receives params + parent metadata
export async function generateMetadata(
  { params }: Props,
  parent: ResolvingMetadata
): Promise<Metadata> {
  const product = await fetch(`https://api.example.com/products/${params.id}`).then(r => r.json());

  // Extend parent metadata
  const previousImages = (await parent).openGraph?.images ?? [];

  return {
    title: product.name,                    // 'AirPods Pro | My App'
    description: product.description,
    openGraph: {
      title: product.name,
      description: product.description,
      images: [product.image, ...previousImages],
    },
    alternates: {
      canonical: `https://myapp.com/products/${params.id}`,
    },
    robots: {
      index: product.isPublished,           // don't index draft products
      follow: true,
    },
    other: {
      'product:price:amount': product.price.toFixed(2),
      'product:price:currency': 'USD',
    },
  };
}

// ---- JSON-LD structured data ----
function ProductStructuredData({ product }: { product: Product }) {
  const jsonLd = {
    '@context': 'https://schema.org',
    '@type': 'Product',
    name: product.name,
    description: product.description,
    image: product.image,
    offers: {
      '@type': 'Offer',
      price: product.price,
      currency: 'USD',
      availability: product.inStock ? 'InStock' : 'OutOfStock',
    },
  };

  return (
    <script
      type="application/ld+json"
      dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd) }}
    />
  );
}

// app/sitemap.ts - generate XML sitemap automatically
import type { MetadataRoute } from 'next';

export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
  const products = await fetch('https://api.example.com/products').then(r => r.json());

  return [
    { url: 'https://myapp.com', lastModified: new Date(), changeFrequency: 'daily', priority: 1 },
    { url: 'https://myapp.com/about', changeFrequency: 'daily', priority: 0.5 },
    ...products.map((p: Product) => ({
      url: `https://myapp.com/products/${p.id}`,
      lastModified: new Date(p.updatedAt),
      changeFrequency: 'daily' as const,
      priority: 0.8,
    })),
  ];
}

// app/robots.ts - generate robots.txt
export default function robots(): MetadataRoute.Robots {
  return {
    rules: [
      { userAgent: '*', allow: '/', disallow: ['/dashboard/', '/api/'] },
    ],
    sitemap: 'https://myapp.com/sitemap.xml',
  };
}

Tip

Tip

Practice SEO Metadata API in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

Visual architecture and flow for SEO & Metadata API

Practice Task

Note

Practice Task - (1) Write a working example of SEO Metadata API from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Quick Quiz

Common Mistake

Warning

A common mistake with SEO Metadata API is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready react code.

Hands-on Practice Tools for this Course

Test what you learn using these free in-browser developer utilities (no signup required).

All 40+ Tools

Topics in This Module

0/10 done