Next.js Developer interview question · Most asked

How do you manage metadata and SEO in the App Router?

Summary

Export a static metadata object or an async generateMetadata() from layouts and pages; Next.js merges them down the tree and renders <title>, meta descriptions, Open Graph and Twitter tags. Use sitemap.ts, robots.ts and opengraph-image.tsx file conventions for the rest.

Longer Answer

generateMetadata can fetch data (deduplicated with the page's fetch). Use title.template in the root layout ('%s | Acme'). Server rendering means crawlers receive full HTML. Add JSON-LD structured data via a <script type='application/ld+json'> in the page.

Code Example

export async function generateMetadata({ params }: { params: Promise<{ slug: string }> }) {
  const post = await getPost((await params).slug);
  return {
    title: post.title,
    description: post.excerpt,
    openGraph: { images: [post.coverUrl] },
  };
}

Key Points

  • metadata / generateMetadata
  • Merged from layouts to pages
  • sitemap.ts, robots.ts, OG image routes
  • Title templates

More most-asked Next.js Developer questions

← All Next.js Developer questions