Adding Page-Specific Metadata with Next.js Head Component
Jul 26, 2023Next.js offers a Head component that functions similarly to the native HTML <head>
tag. This component can be used in your page components to provide page-specific metadata such as title, description, viewport, etc.
Usage of Head Component
In Next.js, you can import the Head component from next/head
and use it to include metadata within your page components. Here's an example of how you can set a page's title and viewport metadata:
import Head from 'next/head'
export default function Home( ) {
return (
<>
<Head>
<title>Home Page</title>
<meta name="viewport" content="initial-scale=1.0, width=device-width" />
</Head>
<h1>Welcome to the Home Page</h1>
</>
)
}
In the above code, the Head component is used to set the title of the page to "Home Page" and the viewport metadata.
Avoiding Duplicates with Key Prop
The key prop can be used to prevent duplicate metadata tags from being added to the head of your document. This is particularly useful when your metadata can come from multiple sources, such as hardcoded data and data fetched from an API or CMS.
Here's an example that demonstrates this:
import Head from 'next/head'
export default function Home( ) {
return (
<>
<Head>
<meta key="og:title" name="og:title" content="My Next.js Course" />
</Head>
<Head>
<meta key="og:title" name="og:title" content="My Awesome Course" />
</Head>
</>
)
}
In the code above, even though we have two Head components with the same 'og:title' tag, only the second one is rendered. The key prop ensures that only the last defined tag with that key is rendered.
Best Practices and Limitations
When using the Head component, you should ensure that each page completely defines its own head elements without making assumptions about what other pages might have added.
The Head component's children should be basic HTML elements. More complex React components may not be correctly parsed. As a rule, title, meta, or any other elements need to be direct children of the Head component, or wrapped into a maximum of one level of React fragments.
Recap
The Head component in Next.js provides a way to add page-specific metadata. You can use multiple Head components in a single page, and they can even contain data fetched from an API or CMS. To avoid duplicates, you can use the key prop. However, it's important to remember that all elements within the Head component must be direct children, or at most wrapped in one level of React fragments.
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras sed sapien quam. Sed dapibus est id enim facilisis, at posuere turpis adipiscing. Quisque sit amet dui dui.
Stay connected with news and updates!
Join our mailing list to receive the latest news and updates from our team.
Don't worry, your information will not be shared.
We hate SPAM. We will never sell your information, for any reason.