Topic 18 of 39
Metadata & SEO
Overview
Next.js handles SEO natively via the Metadata API. You can export a static metadata object or a dynamic generateMetadata function from any layout.tsx or page.tsx to automatically generate <head> tags.
Syntax
tsx
// Static Metadata
import type { Metadata } from 'next';
export const metadata: Metadata = {
title: 'My Startup',
description: 'Building the future of tech.',
openGraph: {
title: 'My Startup',
images: ['/og-image.jpg'],
},
};
export default function Page() { ... }Common Pitfalls
- Trying to export metadata from a Client Component (it must be a Server Component).
- Not understanding that nested route metadata merges with parent layout metadata (title templates help with this).
Interview Questions
Q:
How do you generate SEO metadata based on a dynamic route parameter (like a blog slug)?
A:
You export an async function called generateMetadata({ params }) from the page file, fetch the data based on the params, and return a metadata object.
Real-World Example
Generating dynamic metadata for a blog post to ensure beautiful Twitter/LinkedIn link previews.
example
tsx
// app/blog/[slug]/page.tsx
export async function generateMetadata({ params }): Promise<Metadata> {
const post = await fetchPost(params.slug);
return {
title: `${post.title} | Blog`,
description: post.excerpt,
openGraph: {
images: [post.coverImageUrl],
}
};
}
export default function BlogPost({ params }) { ... }Check Your Knowledge
Test your understanding of Metadata & SEO with these quick questions.