Next.js: populate the head tag with custom tags

By

Learn how to customize the head tag in a Next.js page using the Head component from next/head to set the title, meta tags, and any HTML you want in the header.

~~~

To add custom tags to the <head> of a Next.js page, import the Head component from next/head and put your tags inside it, right in the page JSX. Next.js moves them into the document head for you.

This is handy when:

How to use the Head component

Inside every component you can import the Head component from next/head and include it in your component JSX output:

import Head from 'next/head'

const House = props => (
  <div>
    <Head>
      <title>A house by the sea</title>
      <meta name='description' content='A 3 bedroom house with direct beach access' />
    </Head>
    {/* the rest of the JSX */}
  </div>
)

export default House

You can add any HTML tag you’d like to appear in the <head> section of the page: meta tags, link tags for favicons, whatever you need.

When mounting the component, Next.js will make sure the tags inside Head are added to the heading of the page. Same when unmounting the component, Next.js will take care of removing those tags.

The tags are also rendered server side, so they appear in the initial HTML. Search engines and social networks see them without running any JavaScript.

What happens with duplicate tags?

Since any component can render a Head, you can easily end up with the same tag twice. Say a layout component sets a default title, and a page sets its own.

Duplicate <title> tags are handled for you: Next.js keeps the last one rendered. For other tags, like meta tags, add a key prop:

<meta property='og:title' content='A house by the sea' key='ogtitle' />

If two components render a meta tag with the same key, only the last one ends up in the head. Without the key, you get both.

One thing to watch out for

The tags need to be direct children of Head, or at most wrapped in a single fragment or array. If you extract them into a separate component that renders them, they won’t be updated correctly when you navigate between pages on the client.

So keep the actual <title> and <meta> elements inline, inside the Head element. You can still interpolate values from props:

<Head>
  <title>{props.address}</title>
</Head>

One last note: next/head is for the pages router. If you’re on the app router, you define metadata with the metadata export instead.

Tagged: Next.js · All topics
~~~

Related posts about next: