Type to generate UI components from text

OR

Browse thousands of MUI, Tailwind, React components that are fully customizable and responsive.

Explore Components

A Comprehensive Guide to the Nextjs Head Component

Next.js is one of the leading full-stack frameworks that enables the development of both frontend and backend components of a web application within a single repository, resulting in a faster process. This comprehensive article will delve into the Nextjs Head component and explore its various applications in different versions of Next.js.

By examining the Head component in detail, we will gain a better understanding of how it functions within the Next.js framework and how to effectively utilize it in our web development projects.

What is the Next.js Head Component?

The Head component is a built-in SEO-friendly feature in Next.js that enables developers to add HTML head elements such as title, description, meta tags, and other elements to a page component.

These elements are standard machine-readable information or metadata used in HTML for search engine optimization purposes.

Here is a simple example of an HTML head containing structured data metadata:

<head>
  <title>Your Page Title Here</title>

  <meta name="description" content="A descriptive summary of your page's content goes here.">

  <meta name="keywords" content="keyword1, keyword2, keyword3">

  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <meta property="og:title" content="Your Page Title">
  <meta property="og:description" content="Your page description">
  <meta property="og:image" content="https://example.com/your-image.jpg">

  <meta name="twitter:card" content="summary_large_image">
  <meta name="twitter:title" content="Your Page Title">
  <meta name="twitter:description" content="Your page description">
  <meta name="twitter:image" content="https://example.com/your-image.jpg">
</head>

Are Meta Tags Still Used in Nextjs?

Yes, meta tags continue to play a crucial role in describing the metadata of a given web page document within NextJs applications. Despite the advancements in web development, there are no alternative tags that can effectively replace meta tags, even in the context of NextJs.

Meta tags serve a variety of essential purposes for web pages, including specifying the character set, providing a concise page title and description, listing relevant keywords, identifying the author of the document, configuring viewport settings, and linking external scripts or stylesheets.

In NextJs, just as in other web development frameworks, meta tags are placed within the <head> section of an HTML document. This ensures that search engine results and social media platforms can easily access and interpret the metadata when indexing or sharing the page. Properly configured meta tags can significantly improve a page’s search engine ranking, enhance its appearance when shared on social media, and ensure optimal display on various devices.

How do I add a script to NextJs head?

It is recommended to avoid using the native <script> tag in the Head component when using third-party scripts in Nextjs. Instead, we recommend making use of the Script component from the next/script.

According to the NextJS Script documentation; the Script component will only load the third-party script and execute it when any route in your application is accessed.

Next.js will ensure the script will only load once, even if a user navigates between multiple pages.

What are Metadata Tags in NextJS Head?

Metadata tags are essential HTML elements that provide descriptive information about the content and structure of a web page document.

This information is primarily used by search engines, social media platforms, and web browsers to understand and display the content more effectively.

By incorporating metadata tags in your NextJS Head, you can improve your website’s search engine optimization (SEO) and enhance the user experience.

There are several types of metadata tags, each serving a specific purpose. Some of the most commonly used metadata tags are below.

The Title Metadata Tag

The title metadata tag is a fundamental and crucial component of any webpage. It is responsible for displaying the title of the webpage on the browser tab, which aids users in differentiating between their currently opened tabs, as illustrated below.

This seemingly simple feature plays a significant role in enhancing the user experience, as it allows users to quickly identify the specific tab they need to access among multiple open tabs.

In addition to improving the user experience, the title metadata tag also has a direct impact on search engine optimization (SEO). Search engines, such as Google, use the title tag as a primary factor in determining the relevance of a webpage to a user’s search query. An accurate and descriptive title tag can help improve your webpage’s search engine ranking, making it more likely for potential users to discover your page.

Another importance of the title metadata tag is that search engines use it to display the page title on search results as shown below.

Moreover, the title metadata tag is often used by social media platforms and other websites when your content is shared. A well-crafted title tag can entice users to click on your link, driving more traffic to your website and increasing the likelihood of user engagement.

Here is an example of a title tag within the Head component in Next.js:

import Head from "next/head";

function IndexPage() {
  return (
    <div>
      <Head>
        <title>Home</title>
      </Head>
    </div>
  );
}

export default IndexPage;

In summary, the title metadata tag serves multiple purposes, from enhancing the user experience by displaying the webpage title on browser tabs to improving your website’s SEO and visibility on search engines and social media platforms.

A well-constructed title tag is an essential element for any webpage, contributing to its overall success and effectiveness.

Adding Page Title in NextJS Version (13.2+)

To add a title tag in Next.js 13.2+, we’ll employ a slightly different approach by utilizing an exported metadata object. This method allows for a more organized and maintainable way of managing metadata across your application.

The example provided below demonstrates how to implement this technique.

export const metadata = {
  title: "Page title goes here",
};

export default function RootLayout({ children }) {
  return (
    <html lang='en'>
      <body>{children}</body>
    </html>
  );
}

The fields in the metadata object will transform into the corresponding metatags for the pages. You can watch the video below to learn more about title metadata in Next.js Version 14.

Give Purecode AI a try today to instantly generate thousands of customizable, styled Bootstrap and JavaScript components to accelerate your web development projects.

Setting a Default Page Title in Next.js (13.2+)

To set a default page title using the metadata object, which will appear when a title value isn’t provided on a page, we can specify the default field in the title object as shown below.

export const metadata: Metadata = {
  title: {
    default: 'Default Page Title',
  },

Description Metadata Tag

The description tag is a supplementary piece of information that accompanies the title of a page. It offers additional insight into the content of the web page. It is also seen in search engine results and social media previews, as shown below.

Here is an example of a description tag within the Head component in Next.js:

import Head from "next/head";

function IndexPage() {
  return (
    <div>
      <Head>
        <title>...</title>
        <meta
          name='description'
          content='Description of the page goes here...'
          key='desc'
        />
      </Head>
    </div>
  );
}

export default IndexPage;

Adding Page Description in NextJS Version (13.2+)

To add a description tag in Next.js 13 and 14 (the current latest versions), we’ll employ a slightly different approach by utilizing an exported metadata object.

This method allows for a more organized and maintainable way of managing metadata across your application. The example provided below demonstrates how to implement this technique.

export const metadata = {
  title: "...",
  description: "Page description goes here",
};

export default function RootLayout({ children }) {
  return (
    <html lang='en'>
      <body>{children}</body>
    </html>
  );
}

From the example code above, we create a metadata object that contains the necessary information for the description of the page.

By following this approach, you can easily add a description tag in Next.js 13 and 14, while also maintaining a clean and organized codebase.

Open Graph Metadata Tag

Open Graph is an HTML markup protocol that enables social media networks, such as Twitter, Instagram, and Facebook, to display rich previews of website content when people share URLs on their platforms.

This protocol significantly enhances the presentation of shared content, making it more visually appealing and informative for users who come across the shared links.

An Open Graph metadata tag provides essential information about the content, such as the title, description, and image, which the social media platforms use to generate a rich preview.

Below is an example of an Open Graph image on Twitter, showcasing how the metadata tags create an eye-catching and informative preview of the shared content:

By implementing Open Graph tags, you can have better control over how your content appears when shared on social media, ultimately improving user engagement and click-through rates.

Here is an example of OG tags within the Head component in Next.js:

import Head from "next/head";

function IndexPage() {
  return (
    <div>
      <Head>
        {/* Page title */}
        <title>Home</title>

        {/* Page description */}
        <meta
          name='description'
          content='Description of the page goes here...'
          key='desc'
        />

        {/* Page OG */}
        <meta property='og:title' content='Social Media Title' />
        <meta
          property='og:description'
          content='Social description text to show when url is shared'
        />
        <meta property='og:image' content='https://example-image.jpg' />
      </Head>
    </div>
  );
}

export default IndexPage;

From the code above, the meta tags have og:title, og:description and og:image to display content that social media can use to display a rich URL card.

Setting a Dynamic Head Meta Tag

In scenarios where we require varying metadata depending on the information retrieved from the backend, such as for a blog post or a product page, we can dynamically set values for metadata such as title, description, and Open Graph (OG) images.

To achieve this, we can utilize the getServerSideProps function provided by Next.js. This function allows us to fetch data on each request and use it to set the appropriate meta tags for each specific page. By doing so, we can ensure that the correct metadata displays when sharing the URL on social media platforms, resulting in a rich URL card with accurate information.

The following example demonstrates how to implement dynamic meta tags using getServerSideProps:

import Head from "next/head";

function IndexPage(props) {
  const { title, description, coverImage } = props;
  return (
    <div>
      <Head>
        {/* Page title */}
        <title>{title}</title>

        {/* Page description */}
        <meta name='description' content={description} key='desc' />

        {/* Page OG */}
        <meta property='og:title' content={title} />
        <meta property='og:description' content={description} />
        <meta property='og:image' content={coverImage} />
      </Head>
      <h2>{title}</h2>
      <img src={coverImage} />
      <p>{description}</p>
    </div>
  );
}

export async function getServerSideProps(ctx) {
  // Retrieve id from params
  const { query } = ctx;
  const id = query?.id || 1;

  // Fetch data
  const result = await fetch(
    `https://jsonplaceholder.typicode.com/photos/${id}`
  );
  const data = await result.json();

  return {
    props: {
      title: data.title,
      coverImage: data.thumbnailUrl,
      description: `Description for ${data.title}`
    },
  };
}

export default IndexPage;

When you use the inspect element feature in your browser while visiting any of the ports below, you’ll see the title and other metadata as displayed in the screenshot below.

Ports: http://localhost:3000 or http://localhost:3000?id=2

Setting Dynamic Head Metadata in Nextjs 13 and 14

A generateMetadata function was introduced to the server component in order to generate dynamic head metadata based on dynamic route IDs or external data fetched from an API.

This function allows developers to create more personalized and context-specific metadata for their web pages, improving search engine optimization and social media sharing capabilities.

Here’s an example of how to utilize the generateMetadata function to generate dynamic head metadata within a server component in Next.js:

import { Metadata } from "next";

type Props = {
  params: { id: string };
};

export async function generateMetadata({ params }: Props): Promise<Metadata> {
  // Read route params
  const id = params.id;
  const url = `https://jsonplaceholder.typicode.com/photos/${id}`;

  // HTTP call
  const data = await fetch(url).then((res) => res.json());
  console.log(data);

  return {
    title: data.title,
    description: data.description,
  };
}

export default function Page({ params }: Props) {
  return <p>Showing metadata for {params.id}</p>;
}

Explanation:

First, import the necessary dependencies and create a new server component file.

import { generateMetadata } from 'next/head-metadata';

In the server component, define the generateMetadata function. This function should accept any necessary parameters, such as the dynamic route ID, then fetch the external data from an API, and return an object containing the desired metadata properties.

export async function generateMetadata({ params }: Props): Promise<Metadata> {
  // Read route params
  const id = params.id;
  const url = `https://jsonplaceholder.typicode.com/photos/${id}`;

  // HTTP call
  const data = await fetch(url).then((res) => res.json());
  console.log(data);

  return {
    title: data.title,
    description: data.description,
  };
}

By following these steps, you can effectively implement dynamic head metadata in your Next.js server components, allowing for more tailored and relevant metadata that enhances your web pages’ search engine optimization and social media sharing capabilities.

PS: Keep in mind that you cannot export both the metadata object and the generateMetadata() function from the same route segment.

Frequently Asked Questions on Next.js Head Component

Does Vercel own Next.JS?

Ans: Yes, the private compony Vercel developed and maintains Next.js. However, the Next.js code is available as open-source.

What is the difference between the Next head and the Next document head?

Ans: In Next.js, the Head is a built-in component from next/head is used to set elements in the <head> of a specific page. This allows you to customize the metadata (such as title, description, etc.) for each individual page.

On the other hand, the <Head /> component inside the _document.js or _document.tsx file (built-in component, exported from next/document) is used for any <head> code that is common for all pages. This is where you would typically place elements that are consistent across all pages of your application, such as stylesheets or other global scripts.

Is Next.js gaining popularity?

Ans: Next.js is well-received in the React community because it simplifies the process of building React applications and provides features like server-side rendering (SSR) and static site generation (SSG) out of the box. Its ease of use, performance benefits, and support for various data-fetching strategies have contributed to its adoption.

Check out the post from Guillermo Rauch (Creator of Next.js) on X (Twitter) below.

Is Next.js faster than React?

Ans: The primary distinction between Next.js and React.js lies in performance. Next.js applications are incredibly fast due to their static generation and server-side rendering approach.

Wrapping Up The Comprehensive Guide to Next.js Head Component

In conclusion, the Next.js Head component is a powerful tool for managing the metadata of your web pages, which plays a crucial role in SEO and social media sharing.

It offers the flexibility to add various types of metadata tags, from the basic title and description tags to Open Graph tags for social media.

The evolution of Next.js has also introduced more efficient ways to handle dynamic metadata, making it even more adaptable to different use cases.

Whether you’re building a simple website or a complex web application, mastering the use of the Head component in Next.js can significantly enhance your project’s online visibility and user experience.

Check out Purecode AI!

I recommend you try out Purecode AI, an AI tool that can generate custom HTML, CSS, and JavaScript components. Here are some of its features:

  • It uses an AI assistant to generate thousands of responsive pre-made components for you.

  • The components come with default styling using CSS, Tailwind CSS, or your own custom styles so you can match your brand’s design.

  • You can easily customize the generated components to suit your specific needs – change colors, spacing, paddings, margins, etc.

  • It generates both the HTML markup and CSS styles for the components, saving you development time.

  • It also includes some JavaScript functionality within the components to make them interactive.

Ayodele Samuel Adebayo

Ayodele Samuel Adebayo