How To Add HTML Head Element Tags To A Next.js Website
The HTML <head>
element is a container for meta data (<title>
, <style>
, <meta>
, <link>
, <script>
, and <base>
tags) and is placed between the <html>
tag and the <body>
tag in an HTML document.
The data inside the <head>
element is not displayed in the content of the page. And is instead used to describe the contents of the page to both users and search engines.
That's all sweet and good, but how do you add <head>
element data to a Next.js application?
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 something like this:
<Head>
<meta name="viewport" content="initial-scale=1.0, width=device-width" />
<meta charSet="utf-8" />
<title>Your page title</title>
<meta name="description" content="An example of a meta description.">
<link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png" />
</Head>
To serve as an example, the component above includes some different types of HTML tags. But, any of the standard HTML <head>
element tags are supported.
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>
<meta name="viewport" content="initial-scale=1.0, width=device-width" />
<meta charSet="utf-8" />
<title>Your page title</title>
<meta name="description" content="An example of a meta description." />
<link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png" />
</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.
If you added a <title>
tag, you should see it displayed in the browser tab. And remember that this will also be displayed in search results.
And if you added a meta description tag, you can open the Developer Tools and examine the <head>
section of the HTML for your page. You should see the meta description you added.
Remember that this value may be displayed in search engine results.
Also, if you added a favicon image to your <head>
element, you should now see the favicon icon in the browser tab for that page.
There you have it! That's how you add a <head>
element to a Next.js website.
Thanks for reading and happy coding!