Checkout my CSS Grid By Example and Getting Started With React video courses on Skillshare. Sign up now and get one free month of Skillshare.

Setting the page title and metadata in NextJs

Let's take the following code:

import { useRouter } from 'next/router'

function BlogPostPage() {
    const router = useRouter()
    let {title} = router.query
    const formatedTitle = title?.replace(/-/g, ' ')

    return (<h1>{formatedTitle}</h1>)
}

export default BlogPostPage

What is returned from the BlogPostPage function will be inserted only in the body of the html document. But, how can we control what gets into the head of a NextJs page? What if we want to set the formatedTitle also as the title of the page? At this moment our page title just shows the current url:

For situations like this we can use the Head component, as seen below:

import { useRouter } from 'next/router'
import Head from 'next/head'

function BlogPostPage() {
    const router = useRouter()
    let {title} = router.query
    const formatedTitle = title?.replace(/-/g, ' ')

    return (<div>
        <Head>
            <title>{formatedTitle}</title>
        </Head>
        <h1>{formatedTitle}</h1>
    </div>)
}

export default BlogPostPage

After adding this code we will see that now our page title looks like this:

We can use it to define also metatags. Actually, also the page title can be set as a meta:

return (<div>
    <Head>
        <meta property="og:title" content={formatedTitle} />
        <meta name="viewport" content="initial-scale=1.0, width=device-width" />
        <meta name="description" content="this is a blog about nextjs"></meta>
    </Head>
    <h1>{formatedTitle}</h1>
</div>)

This can be used for any metatags like description, author, Twitter or Facebook share cards, and so on.

If we have multiple Head components on a page or its child components, Next.js will use the latest encountered value. To avoid some display glitching for the page title be sure to use the key property:

return (<div>
    <Head>
        <meta property="og:title" content="A title that will not be used" key="title" />
    </Head>
    <Head>
        <meta property="og:title" content={formatedTitle} key="title" />
    </Head>
</div>)

And finally keep in mind that if you want to set the same metadata for all pages it makes more sense to put them in then the NextJs app template page:

// pages/_app.js
import Head from 'next/head'

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

export default MyApp
Home Screencasts Best of Newsletter Search X