Next.js: How to Set Page Title and Meta Description

Last updated on May 24, 2022 A Goodman Loading... Post a comment

In Next.js, you can set the title, description, and other metadata for a page by using the <Head> component. Import it like this:

import Head from 'next/head'

Examples

Static Content

The code:

// pages/index.js
// KindaCode.com
import Head from 'next/head'

export default function Home(props) {
  return <>
    <Head>
      <title>KindaCode.com</title>
      <meta name='description' content='I hope this tutorial is helpful for you' />
    </Head>
    <div style={{ padding: 30 }}>
      <h1>Hello there!</h1>
    </div>
  </>
}

Output:

Dynamic Routes & Dynamic Content

You can fetch data from a backend by using getStaticProps, getStaticPaths, or getServerSideProps and use this data to set the page title and description like this:

// pages/[id].js
import Head from 'next/head'

const Product = (props) => {
    const { title, description } = props;
    return <>
        <Head>
            <title>{title}</title>
            <meta name='description' content={description} />
        </Head>

        {/* page content here */}
        <div>
            {content}
        </div>
    </>
}

export default Product

export async function getServerSideProps(context) {
    // Retrieve id
    const { params } = context;
    const id = params.id;

    // Fetch data
    const result = await fetch(`[your API]/${id}`);
    const data = await result.json();

    return {
        props: {
            title: data.title,
            description: data.description,
            content: data.content
        }
    }
}

Note: This isn’t a complete example. You need to make the necessary changes for it to work (use your own API URL, inspect data structure, etc).

Setting Global Metadata

If you want to set the same metadata for all pages, you can put a component in pages/_app.js, like this:

// pages/_app.js

import '../styles/globals.css'
import Head from 'next/head'

function MyApp({ Component, pageProps }) {
  return <>
    <Head>
      <meta name="author" content="John Doe"/>
    </Head>
    <Component {...pageProps} />
  </>
}

export default MyApp

Note: If have multiple <Head> components on a page and its child components, Next.js will automatically merge their content and your app will never crash because of conflict. The latest values would be used.

Final Words

You’ve learned how to use <Head> to set the title and description for a page in Next.js. You can find more information about this wonderful built-in component in the official docs.

If you’d like to explore more new and interesting things about server-side rendering and modern React, take a look at the following articles:

You can also check our React topic page and Next.js topic page for the latest tutorials and examples.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Related Articles