NextJS Head: Optimize MetaData

Next.js is an alternative to GatsbyJS and is a framework built on React that comes equipped with tooling for server side rendering and static site generation. Long story short, it’s a great way to leverage React while obtaining excellent Next.js SEO metrics.

NextJs ships with a collection of components that help streamline certain aspects of development. One such component we’ll be discussing here is the NextJS Head component, which simplifies injection of metadata into the HTML head tag of your web app. Getting the head tag right is crucial for search engines, much like other aspects we cover such as robots.txt and sitemaps.

SEO Consultant

Free Weekly SEO Newsletter

Hey! I’m Scott, I’ve been an SEO consultant for nearly 10 years. Get on my weekly newsletter to get..

  • Weekly SEO updates, keep up with the latest and greatest.
  • How we grow websites from zero to millions of visitors
  • A bunch of SEO tips and Tricks you won’t find anywhere else test

TL;DR: Next JS Head Quick Links

For those of us who want answers quickly:

NextJs Head and HTML head

In HTML, the head tag can contain styling, scripting, and a variety of metadata related to a given web page. Modern frameworks like ReactJs and NextJs utilize coding techniques to facilitate the population of data within the HTML head tag.

NextJs Head | Controlling the <head> Tag with Nextjs Head

In comes the NextJs <Head /> component, giving developers the ability to configure their own dynamic Head component, or simply configure the head tag statically.

This feature is important for front-end frameworks like Next JS. Developers don’t have direct access to each individual HTML file, and the Head component is how we get our metadata where it needs to be within the head tag.

Which types of Metadata are important when using Next/Head?

There are many tags and techniques used within Head to optimize search engine performance. Rather than attempt an exhaustive list (which could probably fill a book), let’s take a look at some of the most important tags that google really weighs heavily.

Note: Going forward, Head is synonymous with the NextJs Head component. While head will refer to the HTML tag. 

Title Tag 

<title>Title Goes Here</title>

The title tag is perhaps the most important metadata found within the head tag. It sends a powerful signal to Google about your content, providing a bite sized phrase defining what your content actually is. If we could optimize only one aspect of the Head, this would be it.

The title is shown as the link text in Google search results, and also in browser tabs. A length of 50-60 characters is ideal for the title tag.

Meta Description

<meta name=’description’ content=’Description goes here’ />

The meta description is perhaps the most underrated meta tag found within the head tag. It is often left blank, leaving Google to extract the description from your page, leading to undesired results.

The meta description is displayed underneath the title in Google search results. Since Google usually truncates descriptions at around 155-160 characters, it’s considered optimal to stay within this range.

 

Structured Data 

<script type=”application/ld+json”>{ json: “goes here” }</script>

Structured data is a way to spoon feed Google information about your site. Googlebot is just a program, and programs can read and process structured data much easier than extracting data from tags.

Structured data mostly reflects the metadata found within already existing tags inside the head tag. It’s programmatically represented using JavaScript object notation (JSON), and is fairly simple to set up.

NextJs Head | Basic Example

The NextJs Head component is easy to use. Let’s take a look at a basic example using our previously discussed tags:

import Head from 'next/head'

function IndexPage() {
  return (
    <div>
      <Head>
        <title>My page title</title>
        <meta name="viewport" content="initial-scale=1.0, width=device-width" />
      </Head>
      <p>Hello world!</p>
    </div>
  )
}

export default IndexPage

This simple example was pulled straight from the NextJs docs. To help illustrate what Next is doing here, take a look at some of the HTML rendered in the browser:

<html>
	<head>
		<title>My page title</title>
<meta name="viewport" content="initial-scale=1.0, width=device-width" />
	</head>
	<body>
		<div>
			<p>Hello world!</p>
		</div>
	</body>
</html>

As can be seen, NextJs Head simply created an HTML head tag and inserted our metadata. It’s important to note that although the NextJs <Head /> component is located within the <div> tag inside our component, that’s not where it was rendered. 

NextJs extracts the content within the <Head /> component and moves it to the HTML <head> tag.

Why not just create the HTML head tag ourselves? 

Don’t forget, as we went over earlier; when using frameworks like Next, we don’t have direct access to the HTML file. All HTML is generated at client or server run time, or at build time, when each individual component (such as the one above) is converted into HTML.

Therefore, we need the Head component to insert our content properly behind the scenes.

NextJs Static Head vs Dynamic Head

In the previous example, we created our head tag by providing static information. But this isn’t very flexible, and doesn’t lend itself nicely to the DRY (don’t repeat yourself) principle of coding.

Let’s take a look at creating a dynamic Head component that partially simplifies the process of optimizing for search engines, then discuss what problems it solves.

NextJs | Dynamic Head Example

First, we’ll create a file called globalmeta.js that contains data which can be used globally throughout the application:

globalmeta.js

const globalMeta = {
	siteName: "Your Site Name",
	siteUrl: "https://yoursite.com",
	siteLogo: "https://yoursite.com/images/logo.png",
	email: "email@yoursite.com",
	description: "Default site description."
}

export default globalMeta;

Now, we’ll create our dynamic Head component. Notice it is populated with some optional parameters from our globalmeta.js file we just created:

Head.js

import Head from 'next/head';
import globalMeta from '../globalmeta';
 
export default function Home({
	title = globalMeta.siteName,
	description = globalMeta.description,
	canonicalUrl = globalMeta.siteUrl,
	ogType,
	ogImgUrl = globalMeta.siteLogo,
	structuredData,
	children
}) {
 
  return (
	<Head>
    	{/*
        	Fundamental head elements.
    	*/}
    	<title>{ title } </title>
    	<meta name="description" content={description} />
    	<link rel="canonical" href={canonicalUrl} />
    	<meta name="viewport" content="width=device-width, initial-scale=1" />
    	<link rel="icon" href="/favicon.ico" />
 
    	{/*
        	Open graph meta tags.
    	*/}
    	<meta property="og:locale" content="en_US" />
    	<meta property="og:site_name" content={globalMeta.siteName} />
    	<meta property="og:type" content={ogType} />
    	<meta property="og:description" content={description} />
    	<meta property="og:image" content={ogImgUrl} />
    	<meta property="og:url" content={canonicalUrl} />
 
    	{/*
        	Structured data.
    	*/}
    	<script
            type="application/ld+json"
        	dangerouslySetInnerHTML={{__html: structuredData}}
        	key="item-jsonld"
    	/>
    	{ children }
	</Head>
  )
}

And now we’ll create our index page, which serves as the landing page in a NextJs app. Notice that instead of using the Head component, we will import our dynamic SearchEngineHead implementation:

index.js

import SearchEngineHead from './components/SearchEngineHead.js';
import styles from '../styles/Home.module.css';
import globalMeta from './globalmeta';
import Link from 'next/link';
 
export default function Home() {
 
  const structuredLd = JSON.stringify({
    	"@context": globalMeta.canonicalUrl + "/cool-article",
    	"description": "NextJs Head, a reliable guide for how to use it and what it's really for."
  });
 
  return (
	<div className={styles.container}>
 
  	<SearchEngineHead
    	canonicalUrl={ globalMeta.siteUrl }
    	structuredData={structuredLd}
    	title="NextJs Head"
    	description="NextJs Head, a reliable guide for how to use it and what it's really for."
    	ogType="website"
    	/>
 
  	<main className={styles.main}>
    	<div>
        	<h2>Use NextJs Head!</h2>
        	<Link href="/coolarticle">Cool Article!</Link>
    	</div>
  	</main>
	</div>
  )
}

And finally, we’ll simulate a blog article, which will also import our dynamic SearchEngineHead component:

coolarticle.js

import SearchEngineHead from './components/SearchEngineHead.js';
import styles from '../styles/Home.module.css';
import globalMeta from './globalmeta';
import Link from 'next/link';
 
export default function CoolArticle() {
 
  const structuredLd = JSON.stringify({
    	"@context": globalMeta.canonicalUrl + "/cool-article",
    	"description": "NextJs Head, a cool article page for our nextjs Head example site."
  });

 
  return (
	<div className={styles.container}>
 
  	<SearchEngineHead
    	canonicalUrl={ globalMeta.siteUrl + "/cool-article" }
    	structuredData={structuredLd}
	    title="NextJs Head | Cool Article!"
    	description="NextJs Head, a cool article page for our nextjs Head example site."
    	ogType="article"
    	/>
 
  	<main className={styles.main}>
    	<div>
        	<h2>Cool article!</h2>
            <Link href="/">Home</Link>
    	</div>
  	</main>
	</div>
  )
}

And there we have it! A basic implementation of a dynamic Head component using NextJs.

Let’s have a quick look at the important parts of the HTML output from the head tag on our article page:

NextJs Head HTML Output

<head>
  <meta charSet="utf-8"/>
  <title>NextJs Head | Cool Article!</title>
  <meta name="description" content="NextJs Head, a cool article     page for our nextjs Head example site."/>
  <link rel="canonical" href="https://yoursite.com/cool-article"/>
  <meta name="viewport" content="width=device-width,   initial-scale=1"/>
  <link rel="icon" href="/favicon.ico"/>
  <meta property="og:locale" content="en_US"/>
  <meta property="og:site_name" content="Your Site Name"/>
  <meta property="og:type" content="article"/>
  <meta property="og:description" content="NextJs Head, a cool article page for our nextjs Head example site."/>
  <meta property="og:image" content="https://yoursite.com/images/logo.png"/>
  <meta property="og:url" content="undefined/cool-article"/>
 
  <script type="application/ld+json">
    {
     "@context":"undefined/cool-article",
     "description":"NextJs Head, a cool article page for our nextjs Head example site."
    }
  </script>
</head>

As can be seen from the output, we have successfully populated the head tag using NextJs Head dynamically. The benefits of this method are quite obvious. 

If you have a site with 100 pages, and you need to change something such as the canonical URL, you’d have to manually make the change on each page without our global data. As it stands, we can make our change one time versus one hundred times. 

NextJs Head | Final Thoughts & Quick Overview

When optimizing a site for search engines, the head tag contains important metadata that Google uses to index and rank your site. When using NextJs, the way to modify the head tag is by utilizing the Head component.

The Head component comes with NextJs out of the box. It can be imported into any page component, or a custom implemented component, for modifying the HTML head tag.

NextJs will automatically extract your content from the Head component, and inject it into the HTML head tag. This feature is imperative for optimizing metadata found within the head tag.

For optimizing SEO in React style apps, some variant of NextJs Head must be used. If you plan on using NextJs or other ReactJs frameworks for your development, becoming familiar with this concept is a must.

Leave a Comment

oh my crawl logo
Digital Architecture
For Search Engines
Javascript Frameworks
Most Js Frameworks..
Contact
Brooklyn, NY 11219

Blog