🎓 A1Learner
🔍
0 of 50 lessons completed

Next.js Metadata and SEO

Metadata is the title and description a search engine sees. generateMetadata builds it per page.

The title per book

The function reads the book, then builds the title from its name and author.

export async function generateMetadata({
  params,
}: {
  params: Promise<{ id: string }>;
}): Promise<Metadata> {
  const { id } = await params;
  const book = await getBook(id);
  if (!book) {
    return { title: 'Book not found | My Bookshelf' };
  }
  const title = `${book.title} by ${book.author} | My Bookshelf`;
  const description = `${book.title} by ${book.author}. ${
    book.read ? 'Finished.' : 'Still reading.'
  } Track it on My Bookshelf.`;
  return {
    title,
    description,
    openGraph: {
      title,
      description,
      type: 'website',
    },
  };
}

The site metadata in the layout

The layout holds one title and one description for the whole site.

export const metadata: Metadata = {
  title: 'My Bookshelf',
  description: 'A small app that tracks the books you own and have read.',
};

Example

curl -s http://localhost:3110/books/dune | grep -o "<title>[^<]*</title>"

Key points

  • generateMetadata runs on the server. It builds the title for one book page.
  • The Dune title is "Dune by Frank Herbert | My Bookshelf".
  • The description and the Open Graph tags travel with the title.
  • The layout holds the site title "My Bookshelf" and its description.
  • A missing book gets "Book not found | My Bookshelf".

In this example, one check reads the served Dune page. The title tag holds "Dune by Frank Herbert | My Bookshelf". That title came from generateMetadata, not from the page text. A search engine reads the same title tag. The page text shows the book name, and the title tag shows the book name plus the site name.

Note

Write the title for the reader first. The search engine reads what the reader reads.

Try it Yourself

Edit the code, then press Run.

Running is simulated · TypeScript Playground

Exercise

What builds the title for one book page?