Max Schmitt

February 27 2023

Next.js: How to Set Meta Tags

Meta tags allow you to control various aspects of your website and they are particularly important for SEO.

In order to optimize websites for search engines, you should always include a <title> tag and <meta name="description"> tag for every page.

Using the Next.js Head Component for Meta Tags

In Next.js, we can use the <Head> component to inject tags into the <head> section of the HTML document at any point in the component tree.

It's as easy as this:

pages/index.js

import Head from 'next/head'
function IndexPage() {
return (
<>
<Head>
<title>My website</title>
<meta name="description">
This text will appear in the description section of search engine results.
</meta>
</Head>
{/* ... */}
</>
)
}
export default IndexPage

Setting Meta Tags When Using the App Directory (Next.js 13.2+)

In Next.js 13, the framework received built-in support for metadata that is compatible with streaming.

Using the generateMetadata function

If you use the new app directory, your pages and layouts can export a generateMetadata function.

app/page.tsx

export async function generateMetadata({ params, searchParams }) {
return {
title: 'My title',
description: 'My description',
}
}
function IndexPage() {
return <h1>Hello world</h1>
}
export default IndexPage

Setting a Default Title in Next.js

Your layouts can also export helpful defaults for metadata, such as appending your application's name to the title:

app/layout.tsx

export const metadata = {
title: {
default: 'My App',
template: '%s - My App',
},
}

There are more cool things about the Next.js metadata API.

For example, your pages inherit metadata from the layouts it uses.

Check out the Next.js Metadata API docs for more information!