Next.js - Head Component



The <Head> component in Next.js extends the functionality of the standard HTML <head> element. Next.js will make sure that the data defined in <Head> component will be rendered in server-side for better SEO optimization. In this chapter we will explore Head component, it's syntax, features, props and examples.

Next.js Head Component

The <Head> component in Next.js is used to modify the <head> section of a page. This tag will allow you to set title, metadata, external links and other essential SEO feature to your webpage.

Features of Head Component

  • <Head> component in Next.js can be used to set dynamic metadata for your webpage, For example title can be changed based on route user visiting.
  • The <Head> component is rendered server-side by default, this will ensure metadata is available to crawlers.
  • Next.js automatically ensures that duplicate tags are avoided. For example, if multiple <title> tags are defined, the most recent one overrides the previous ones
Note: <Head> component is only supported in Next.js page router. In App router, you can use generateMetadata() function to set metadata for your webpage.

Basic Usage of Head Component

The below code shows how to use <Head> component in Next.js About page we created in earlier chapters.

import Head from 'next/head'
 
export default function About() {
  return (
    <>
        <Head>
            <title>About Us - My Website</title>
            <meta name="keywords" content="about us, company, team" />
            <link rel="icon" href="/favicon.ico" />
        </Head>
        <h1>About Us</h1>
        <p>Welcome to the about us page of our website!</p>
    </>
  )
}

Output

The image below is output of above code.

Head Component Example

Generate Dynamic Metadata Inside Head

We can generate dynamic metadata using JavaScript's string interpolation. By this we can fetch data from server, keep it in a variable and display as title of the page. See the code below.

import Head from 'next/head';

export default function About() {
  // Variable for dynamic title
  const companyName = "TutorialsPoint";

  return (
    <>
      <Head>
        {/* Dynamic title using variable */}
        <title>About Us - {companyName}</title>
        <meta name="keywords" content="about us, company, team" />
        <link rel="icon" href="/favicon.ico" />
      </Head>
      <h1>About Us</h1>
      <p>Welcome to the about us page of our website!</p>
    </>
  );
}

Output

The image below shows output of above code.

Dynamic Title
Advertisements