Skip to content

Assets, Metadata, and CSS

Metadata

What if we wanted to modify the metadata of the page, such as the <title> HTML tag?

<title> is part of the <head> HTML tag, so let's dive into how we can modify the <head> tag in a Next.js page.

Open pages/index.js in your editor and find the following lines:

<Head>
  <title>Create Next App</title>
  <link rel="icon" href="/favicon.ico" />
</Head>

Notice that <Head> is used instead of the lowercase <head>. <Head> is a React Component that is built into Next.js. It allows you to modify the <head> of a page.

You can import the Head component from the next/head module.

Adding Head to first-post.js

We haven't added a <title> to our /posts/first-post route. Let's add one.

Open the pages/posts/first-post.js file and add an import for Head from next/head at the beginning of the file:

import Head from 'next/head';

Then, update the exported FirstPost component to include the Head component. For now, we‘ll add just the title tag:

export default function FirstPost() {
  return (
    <>
      <Head>
        <title>First Post</title>
      </Head>
      <h1>First Post</h1>
      <h2>
        <Link href="/">← Back to home</Link>
      </h2>
    </>
  );
}

Try accessing http://localhost:3000/posts/first-post. The browser tab should now say "First Post". By using your browser’s developer tools, you should see that the title tag is added to <head>.

To learn more about the Head component, check out the API reference for next/head.

If you want to customize the <html> tag, for example to add the lang attribute, you can do so by creating a pages/_document.js file. Learn more in the custom Document documentation.