Menu

Metadata and SEO

Lesson 4: Metadata and SEO

What is the Metadata API?

The Metadata API lets you define <head> content, such as titles and descriptions, from layouts and pages. Next.js merges metadata from parent layouts with the page's own values.

Method Use when
export const metadata The values are fixed
export async function generateMetadata() Values depend on data, such as a course title
File conventions (sitemap.ts, robots.ts, opengraph-image.tsx, icon.png) Generating SEO files and images

Example

// app/layout.tsx
export const metadata: Metadata = {
  metadataBase: new URL('https://learnhub.in'),
  title: { default: 'LearnHub', template: '%s | LearnHub' },
  description: 'Beginner-friendly online courses in data, design, and development.',
};
// app/courses/[slug]/page.tsx
import type { Metadata } from 'next';

export async function generateMetadata({ params }: PageProps<'/courses/[slug]'>): Promise<Metadata> {
  const { slug } = await params;
  const course = await getCourse(slug);
  return {
    title: course.title, // Becomes "Introduction to SQL | LearnHub"
    description: course.summary,
    openGraph: { images: [course.thumbnailUrl] },
    alternates: { canonical: `/courses/${slug}` },
  };
}
// app/sitemap.ts
import type { MetadataRoute } from 'next';

export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
  const courses = await getAllCourses();
  return [
    { url: 'https://learnhub.in', lastModified: new Date() },
    ...courses.map((c) => ({
      url: `https://learnhub.in/courses/${c.slug}`,
      lastModified: c.updatedAt,
    })),
  ];
}

How it works

  • title.template adds a consistent suffix to every child page title.
  • metadataBase turns relative URLs, such as Open Graph images, into absolute ones.
  • getCourse is called in both generateMetadata and the page. Wrap it in React's cache() (Module 5) so the data is fetched once.
  • opengraph-image.tsx can generate a social preview image with ImageResponse from next/og.
File Generates
app/sitemap.ts /sitemap.xml
app/robots.ts /robots.txt
app/icon.png / favicon.ico Favicons
opengraph-image.tsx Social preview image for that route

Common mistakes

Mistake Effect Fix
Same title on every page Poor search results and tabs Use title.template and per-page titles
Missing metadataBase Broken Open Graph image URLs Set it in the root layout
Exporting metadata from a Client Component Ignored or build error Metadata works only in Server Components
Descriptions over ~160 characters Truncated in search results Keep descriptions concise and specific

Key takeaways

  • Set defaults in the root layout and override them per page.
  • Use generateMetadata for data-driven pages, and file conventions for sitemaps and social images.

Try it: Add a title template, per-course metadata, a sitemap.ts, and a robots.ts to LearnHub, then open /sitemap.xml in the browser.


Nextjs Tutorial

J

Jebasta





Get in Touch For Details