← coderrocketfuel.com

How To Add A Title Tag To A Next.js Website

The title tag is an HTML element that is used to specify the title of a given page.

Its primary purpose is to tell users and search engines what to expect from a web page. And to do so in the most precise amount of words possible (50-60 words). When adding a title tag to your web page, you should make it both enticing to your reader and have it serve as a proper description and preview of the page's content.

So, how do you add a title tag to a Next.js website?

Next.js has a built-in Head component for appending elements to the head section of a page.

First, you need to import the next/head component at the top of your Next.js page:

import Head from "next/head"

Since the next/head component is included with Next.js, you don't need to install any NPM dependencies to your project.

Then, you can create a new <Head> component that looks like this:

<Head>
  <title>Your page title</title>
</Head>

The component will also look like this when placed in a Next.js page:

import { Component } from "react"
import Head from "next/head"

export default class extends Component {
  render() {
    return (
      <>
        <Head>
          <title>Your page title</title>
        </Head>
        <div>Page Content</div>
      </>
    )
  }
}

Notice that the <Head> component is the first item inside the return() method. This is to ensure that the tags inside the <Head> component are picked up properly on client-side navigations.

Save your file and view the page in your favorite browser.

You should see the title you put inside the <title> element displayed in the browser tab. And remember that this will also be displayed in search results.

Google Search Results - Title Tag Shown

There you have it! That's how you add a title tag element to your Next.js website.

Thanks for reading and happy coding!