Metadata in Next.js is essential for optimizing SEO and enhancing web shareability by accurately representing your web pages across search engines and social media platforms. Next.js provides a robust Metadata API to manage both static and dynamic metadata efficiently.
Using the Metadata API to define metadata for each page ensures accurate and relevant information is displayed when pages are shared or indexed.
This blog delves into the technical aspects of configuring metadata in a Next.js application.
1<title>Page Title</title>
1<meta name="description" content="A brief description of the page content." />
1<meta name="keywords" content="keyword1, keyword2, keyword3" />
1<meta property="og:title" content="Title Here" /> 2<meta property="og:description" content="Description Here" /> 3<meta property="og:image" content="image_url_here" />
1<link rel="icon" href="path/to/favicon.ico" />
Metadata in Next.js can be configured in two main ways: config-based and file-based.
You can export a static metadata object or a dynamic generateMetadata function from a layout.js or page.js file.
Static Metadata Example:
1import type { Metadata } from 'next'; 2 3export const metadata: Metadata = { 4 title: 'Acme Dashboard', 5 description: 'The official Next.js Course Dashboard, built with App Router.', 6}; 7 8export default function Page() {}
Dynamic Metadata Example:
1import type { Metadata, ResolvingMetadata } from 'next'; 2 3type Props = { 4 params: { id: string } 5 searchParams: { [key: string]: string | string[] | undefined } 6}; 7 8export async function generateMetadata( 9 { params, searchParams }: Props, 10 parent: ResolvingMetadata 11): Promise<Metadata> { 12 const id = params.id; 13 const product = await fetch(`https://.../${id}`).then((res) => res.json()); 14 15 const previousImages = (await parent).openGraph?.images || []; 16 17 return { 18 title: product.title, 19 openGraph: { 20 images: ['/some-specific-page-image.jpg', ...previousImages], 21 }, 22 }; 23} 24 25export default function Page({ params, searchParams }: Props) {}
The title field can be a simple string or an optional template object, which can include dynamic placeholders for the actual title value.
Next.js recognizes specific files like favicon.ico, opengraph-image.jpg, twitter-image.jpg, robots.txt, and sitemap.xml for metadata purposes. These files can be used for static metadata or generated programmatically.
Static Metadata: Defined once and doesn't change. It’s suitable for content that remains consistent across sessions and users.
Dynamic Metadata: Changes based on context, such as user-specific data or route parameters. Use the generateMetadata function to fetch and customize metadata dynamically.
Root Layout: Metadata defined in the root layout applies to all pages under it.
1import { Metadata } from 'next'; 2 3export const metadata: Metadata = { 4 title: 'My App', 5 description: 'An example Next.js application', 6}; 7 8export default function RootLayout({ children }) { 9 return ( 10 <html lang="en"> 11 <body>{children}</body> 12 </html> 13 ); 14}
Page-Specific Metadata: Override parent metadata by defining it in specific pages.
1import { Metadata } from 'next'; 2 3export const metadata: Metadata = { 4 title: 'Dashboard', 5 description: 'User Dashboard', 6}; 7 8export default function DashboardPage() { 9 return <div>Welcome to your dashboard</div>; 10}
Metadata in Next.js is evaluated in order, from the root segment to the segment closest to the final page.js segment. This allows for hierarchical metadata definitions, where child segments can inherit and override parent metadata.
Example of Metadata Inheritance:
1// app/layout.js 2export const metadata = { 3 title: 'Acme Corp', 4 openGraph: { 5 title: 'Acme Corp', 6 description: 'Leading the industry.', 7 }, 8}; 9 10// app/blog/layout.js 11export const metadata = { 12 openGraph: { 13 title: 'Acme Blog', 14 }, 15}; 16 17// app/blog/[slug]/page.js 18export const metadata = { 19 title: 'Blog Post Title', 20 description: 'A detailed blog post about...', 21};
In this example, the final metadata output for the blog page will include the title "Blog Post Title", and the description from the page-specific metadata, while inheriting the Open Graph properties from the parent layout.
Consistency: Ensure consistent metadata across your site to maintain a cohesive brand identity.
Relevance: Use relevant keywords and descriptions to improve SEO.
Open Graph: Properly set Open Graph metadata to enhance the presentation on social media platforms, increasing engagement and click-through rates.
Avoid Duplicates: Manage duplicate keys carefully to avoid conflicting metadata.
Dynamic Updates: For dynamic pages, ensure metadata is updated based on current data and context.
Let's implement metadata for a blog page in a Next.js application.
Root Layout Metadata:
1import { Metadata } from 'next'; 2 3export const metadata: Metadata = { 4 title: 'My Blog', 5 description: 'Latest updates and articles', 6}; 7 8export default function RootLayout({ children }) { 9 return ( 10 <html lang="en"> 11 <body>{children}</body> 12 </html> 13 ); 14}
Blog Page Metadata:
1import { Metadata } from 'next'; 2 3export const metadata: Metadata = { 4 title: 'Understanding Next.js Metadata', 5 description: 'A detailed guide on managing metadata in Next.js applications.', 6 openGraph: { 7 title: 'Understanding Next.js Metadata', 8 description: 'A detailed guide on managing metadata in Next.js applications.', 9 images: ['/og-image.jpg'], 10 }, 11}; 12 13export default function BlogPage() { 14 return <article>Content of the blog post...</article>; 15}
By following these practices and utilizing Next.js's powerful metadata capabilities, you can significantly enhance your web pages' SEO and web shareability, ensuring they are well-represented across search engines and social media platforms.
Tired of manually designing screens, coding on weekends, and technical debt? Let DhiWise handle it for you!
You can build an e-commerce store, healthcare app, portfolio, blogging website, social media or admin panel right away. Use our library of 40+ pre-built free templates to create your first application using DhiWise.