SEO in Next.js 13 with Metadata API
Tags: nextjs, webdev, tutorial, react
Published: 2023-05-15 06:16:03

> Also available on my [blog](https://nikolasbarwicki.com/articles/seo-in-next-js-13-with-metadata-api)

## Introduction

[Next.js](https://nextjs.org/) has always been a developer's go-to choice for building **SEO-optimized web applications**. With the release of [version 13.2](https://nextjs.org/blog/next-13-2), it's become even more powerful with the introduction of the new **Metadata API**. In this article, we'll dive into the world of SEO in Next.js, exploring the old and new ways of handling metadata, and how this can help **boost search engine rankings**.

## Exploring the New Metadata API

Before diving into the new [Metadata API](https://nextjs.org/blog/next-13-2#built-in-seo-support-with-new-metadata-api), let's take a quick look at how metadata was handled **before Next.js 13.2**.

### The Good Ol' Way (Using next/head)

Next.js has provided a simple API for modifying metadata in your application using the `next/head` [component](https://nextjs.org/docs/pages/api-reference/components/head). This allowed you to define metadata (e.g., meta and link tags inside your HTML head element) in your pages and layouts, making it easy to manage SEO.

However, with the introduction of Next.js 13.2, the new **Metadata API** has been designed to enhance and simplify how you optimize for search engines.

### Current State for Next 13

The new **Metadata API** is available in Next.js 13.2 and above, for the [App Router](https://nextjs.org/docs/app) (`app`). It replaces the previous head.js special file and is not available for the pages directory.

This new API is **simple, composable, and designed to be compatible with streaming server rendering**. You can set common metadata attributes in your root layout for the entire application and compose and merge metadata objects together for other routes in your application.

## SEO in Next: The New Way

Now that we know the basics of the new **Metadata API** let's dive deeper into how we can use it to create static and dynamic metadata.

### Static Metadata

To define static metadata, export a `Metadata` object from a layout or static page file. For example:

```tsx
import type { Metadata } from 'next'

export const metadata: Metadata = {
  title: 'Home',
  description: 'Welcome to Next.js',
}
```

This object allows you to set metadata properties like `title`, `description`, `openGraph`, and more. Check the `Metadata` object reference for the complete list of supported fields.

### Dynamic Metadata

Dynamic metadata can be generated based on runtime information such as route parameters, external data, or parent segment metadata. To do this, export a `generateMetadata` function that returns a `Metadata` object.

```tsx
import { Metadata, ResolvingMetadata } from 'next'

type Props = {
  params: { id: string }
  searchParams: { [key: string]: string | string[] | undefined }
}

export async function generateMetadata(
  { params, searchParams }: Props,
  parent?: ResolvingMetadata
): Promise<Metadata> {
  const id = params.id
  const product = await fetch(`https://.../${id}`).then((res) => res.json())

  const previousImages = (await parent).openGraph?.images || []

  return {
    title: product.title,
    openGraph: {
      images: ['/some-specific-page-image.jpg', ...previousImages],
    },
  }
}
```

The `generateMetadata` function accepts route parameters and an optional parent metadata object. Next.js will automatically deduplicate fetch requests for the same data across `generateMetadata`, `generateStaticParams`, Layouts, Pages, and [Server Components](https://nextjs.org/docs/getting-started/react-essentials#server-components).

By using the new **Metadata API**, you'll be able to create SEO-friendly applications with ease, regardless of whether you need static or dynamic metadata. So, go ahead and give it a try in your Next.js projects, and watch your search engine rankings soar!

## Diving Deep into Metadata Fields

As we've explored the new Metadata API in Next.js, it's crucial to understand the different metadata fields, their importance for SEO, and best practices for using them effectively. In this section, we'll take a closer look at each metadata field, providing example values, best practices, and tips to avoid common mistakes. By the end of this section, you will have a comprehensive understanding of how to use these fields to optimize your web application for search engines.

### `metadataBase`

|                            |                                                                                                                                             |
| -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- |
| **Example value**          | `https://example.com`                                                                                                                       |
| **Correct usage**          | Set the `metadataBase` to the root URL of your website.                                                                                     |
| **Best practices**         | Use a secure HTTPS URL <br /> Ensure the URL is the root of your website                                                                    |
| **SEO Importance**         | It helps search engines understand the correct path for your metadata assets, improving the presentation of your content in search results. |
| **Fixing common mistakes** | Check if the metadataBase value is set correctly and points to the root URL of your website.                                                |

### `title`

|                            |                                                                                                                       |
| -------------------------- | --------------------------------------------------------------------------------------------------------------------- |
| **Example value**          | `"My Blog"`                                                                                                           |
| **Correct usage**          | Use the `title` to set the document title.                                                                            |
| **Best practices**         | Keep the title short, descriptive, and unique <br /> Use a template like `%s \| My Website` for consistent formatting |
| **SEO Importance**         | The title is a crucial factor for search engines to understand the content and rank it accordingly.                   |
| **Fixing common mistakes** | Ensure the title is set and not empty <br /> Avoid using special characters or excessive punctuation                  |

### `description`

|                            |                                                                                                                  |
| -------------------------- | ---------------------------------------------------------------------------------------------------------------- |
| **Example value**          | `"My Blog Description"`                                                                                          |
| **Correct usage**          | Use the `description` to set the document description.                                                           |
| **Best practices**         | Keep the description concise and informative <br /> Include relevant keywords                                    |
| **SEO Importance**         | The description helps search engines understand the content and can be displayed in search results as a snippet. |
| **Fixing common mistakes** | Ensure the description is set and not empty <br /> Avoid using special characters or excessive punctuation       |

### `openGraph`

|                            |                                                                                                                                                |
| -------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- |
| **Example value**          | `{ type: "website", url: "https://example.com", title: "My Website", description: "My Website Description", siteName: "My Website"}`           |
| **Correct usage**          | Use the `openGraph` to set the Open Graph metadata for the document.                                                                           |
| **Best practices**         | Include relevant Open Graph properties, such as type, url, title, description, and images                                                      |
| **SEO Importance**         | Open Graph metadata helps improve the appearance of your content on social media platforms, increasing engagement and click-through rates.     |
| **Fixing common mistakes** | Ensure all required Open Graph properties are set and not empty <br /> Use correct property names and values <br /> Provide appropriate images |

#### Open Graph properties

**Open Graph types** are crucial to specify the type of content on your webpage. Each type has its unique set of metadata properties that help search engines and social media platforms better understand and display your content. Some common Open Graph types include _website_, _article_, _book_, and _video.movie_. Make sure to choose the appropriate type for your content so that it's displayed correctly on different platforms.

The `title` and `description` properties are essential for providing a brief overview of your content. The _title_ should be concise and clearly indicate the subject or purpose of your webpage, while the _description_ should provide a short summary of the content. Both properties are often displayed in search results and on social media platforms, so make sure they are engaging and informative to attract users' attention.

The `siteName` property represents the name of your website or brand. This information helps users recognize your content and associate it with your brand. Ensure that the site name is consistent across all your webpages and accurately reflects your brand identity.

Open Graph allows you to include `images`, `audio`, and `videos` in your metadata to enhance the visual appeal of your content on social media platforms and search results. Make sure to provide high-quality, relevant media files that accurately represent your content. Check that the URLs for these files are valid and accessible to ensure proper display on different platforms.

The `url` property specifies the canonical URL of your webpage. This information helps search engines understand the preferred version of your content, avoiding duplicate content issues. Make sure to use a complete and well-formed URL, including the protocol (HTTP or HTTPS) and the domain name.

The `locale` and `alternateLocale` properties help you specify the language and regional settings of your content. The _locale_ property indicates the primary language and region for your webpage, while the _alternateLocale_ property provides a list of alternate languages and regions for users with different preferences. Properly setting these properties ensures that your content reaches a broader audience and is displayed correctly for users with varying language preferences.

To sum up, Open Graph metadata plays a significant role in improving the presentation of your content on social media platforms and search results, ultimately driving more traffic to your site. Make sure to use the correct Open Graph types, provide engaging titles and descriptions, and include high-quality media files to make your content stand out.

### `robots`

|                            |                                                                                                                                                                                 |
| -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Example value**          | `{ index: true, follow: true, noarchive: true, nosnippet: true, noimageindex: true, nocache: true }`                                                                            |
| **Correct usage**          | Set the `robots` metadata to control how search engines crawl and index your website.                                                                                           |
| **Best practices**         | Use a combination of `index`, `follow`, and other attributes to provide clear instructions to search engines.                                                                   |
| **SEO Importance**         | Properly configuring your `robots` metadata can improve your website's visibility in search engine results and prevent indexing of unwanted pages.                              |
| **Fixing common mistakes** | Ensure that you're not accidentally setting `noindex` or `nofollow` if you want your pages to be indexed and followed. Double-check the syntax and values for other attributes. |

#### Robots Attributes

The `robots` metadata is a powerful tool for controlling the behavior of search engines when they crawl and index your website. It accepts a range of attributes, including:

- `index` (boolean): Determines whether the page should be indexed by search engines. Setting it to `true` will allow indexing, while `false` will prevent it. Default is `true`.
- `follow` (boolean): Determines whether search engines should follow links on the page. Setting it to `true` will allow following, while `false` will prevent it. Default is `true`.
- `noarchive` (boolean): Prevents search engines from showing cached versions of the page.
- `nosnippet` (boolean): Prevents search engines from showing snippets of the page in search results.
- `noimageindex` (boolean): Prevents search engines from indexing images on the page.
- `nocache` (boolean): Prevents search engines from caching the page.
- `notranslate` (boolean): Prevents search engines from offering translations of the page.
- `unavailable_after` (string): Indicates that the page should be removed from search results after a specific date. Use a date format like "25 Jun 2021 15:00:00 PST".

To use the `robots` metadata correctly, combine these attributes to provide clear instructions to search engines on how to treat your website's content. For example, if you want your page to be indexed, followed, and not cached, you would set the `robots` metadata as follows:

```
{
  index: true,
  follow: true,
  nocache: true
}
```

This would generate the following HTML:

```
<meta name="robots" content="index, follow, nocache" />
```

Remember to double-check your `robots` metadata to avoid common mistakes, such as accidentally setting `noindex` or `nofollow` if you want your pages to be indexed and followed. Additionally, ensure that the syntax and values for other attributes are correct.

### `referrer`

|                            |                                                                                                                                                                                                                       |
| -------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Example value**          | `origin`                                                                                                                                                                                                              |
| **Correct usage**          | Set the `referrer` to one of the available values depending on the desired level of referrer information sent with requests.                                                                                          |
| **Best practices**         | Choose the appropriate value based on your privacy and security needs.                                                                                                                                                |
| **SEO Importance**         | It helps search engines understand the referrer policy for your website, which can impact how your content is crawled and indexed.                                                                                    |
| **Fixing common mistakes** | Ensure the referrer value is set to one of the accepted values: 'no-referrer', 'origin', 'no-referrer-when-downgrade', 'origin-when-cross-origin', 'same-origin', 'strict-origin', 'strict-origin-when-cross-origin'. |

#### Referrer Values

- `no-referrer`: The _referrer_ header will not be sent with requests.
- `origin`: Only the _origin_ of the referring document will be sent.
- `no-referrer-when-downgrade`: The full URL will be sent unless the request is from HTTPS to HTTP.
- `origin-when-cross-origin`: The _origin_ will be sent for cross-origin requests, and the full URL for same-origin requests.
- `same-origin`: The full URL will be sent for same-origin requests, and no _referrer_ for cross-origin requests.
- `strict-origin`: Only the _origin_ will be sent, unless the request is from HTTPS to HTTP, in which case no _referrer_ will be sent.
- `strict-origin-when-cross-origin`: The _origin_ will be sent for cross-origin requests and the full URL for same-origin requests, unless the request is from HTTPS to HTTP, in which case no _referrer_ will be sent.

### `authors`

|                            |                                                                                                                                   |
| -------------------------- | --------------------------------------------------------------------------------------------------------------------------------- |
| **Example value**          | `[{ name: "Next.js Team", url: "https://nextjs.org" }]`                                                                           |
| **Correct usage**          | Use the `authors` to set the document authors.                                                                                    |
| **Best practices**         | Include the author's name and URL                                                                                                 |
| **SEO Importance**         | The author information helps search engines understand the content and can be displayed in search results.                        |
| **Fixing common mistakes** | Ensure the author's name is set and not empty <br /> Avoid using special characters or excessive punctuation in the author's name |

### `generator`

|                            |                                                                                                                                     |
| -------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- |
| **Example value**          | `"Next.js"`                                                                                                                         |
| **Correct usage**          | Use the `generator` to set the document generator.                                                                                  |
| **Best practices**         | Keep the generator name short and descriptive                                                                                       |
| **SEO Importance**         | The generator name helps search engines understand the content and can be displayed in search results.                              |
| **Fixing common mistakes** | Ensure the generator name is set and not empty <br /> Avoid using special characters or excessive punctuation in the generator name |

### `keywords`

|                            |                                                                                                                          |
| -------------------------- | ------------------------------------------------------------------------------------------------------------------------ |
| **Example value**          | `"nextjs, react, blog"`                                                                                                  |
| **Correct usage**          | Use the `keywords` to set the document keywords.                                                                         |
| **Best practices**         | Use relevant keywords separated by commas                                                                                |
| **SEO Importance**         | Keywords help search engines understand the content and can improve the ranking of your content in search results.       |
| **Fixing common mistakes** | Ensure the keywords are set and not empty <br /> Avoid using special characters or excessive punctuation in the keywords |

### `themeColor`

|                            |                                                                                                              |
| -------------------------- | ------------------------------------------------------------------------------------------------------------ |
| **Example value**          | `"#000000"`                                                                                                  |
| **Correct usage**          | Use the `themeColor` to set the theme color for the document.                                                |
| **Best practices**         | Use a valid color code <br /> Consider providing different theme colors for dark and light color schemes     |
| **SEO Importance**         | The theme color can affect the appearance of your content in search results and improve the user experience. |
| **Fixing common mistakes** | Ensure the theme color is set and not empty <br /> Use a valid color code                                    |

### `colorScheme`

|                            |                                                                                                               |
| -------------------------- | ------------------------------------------------------------------------------------------------------------- |
| **Example value**          | `"dark"`                                                                                                      |
| **Correct usage**          | Use the `colorScheme` to set the color scheme for the document.                                               |
| **Best practices**         | Choose the appropriate color scheme based on your content and design preferences                              |
| **SEO Importance**         | The color scheme can affect the appearance of your content in search results and improve the user experience. |
| **Fixing common mistakes** | Ensure the color scheme is set and not empty <br /> Avoid using unsupported color schemes                     |

### `viewport`

|                            |                                                                                                                     |
| -------------------------- | ------------------------------------------------------------------------------------------------------------------- |
| **Example value**          | `"width=device-width, initial-scale=1"`                                                                             |
| **Correct usage**          | Use the `viewport` to set the viewport setting for the document.                                                    |
| **Best practices**         | Use a combination of width and initial-scale settings for optimal responsiveness                                    |
| **SEO Importance**         | The viewport setting is crucial for mobile responsiveness, which is a significant factor in search engine rankings. |
| **Fixing common mistakes** | Ensure the viewport setting is set and not empty <br /> Use the correct syntax and values for the viewport setting  |

### `creator`

|                            |                                                                                                                                   |
| -------------------------- | --------------------------------------------------------------------------------------------------------------------------------- |
| **Example value**          | `"Next.js Team"`                                                                                                                  |
| **Correct usage**          | Use the `creator` to set the document creator.                                                                                    |
| **Best practices**         | Keep the creator name short and descriptive                                                                                       |
| **SEO Importance**         | The creator information helps search engines understand the content and can be displayed in search results.                       |
| **Fixing common mistakes** | Ensure the creator name is set and not empty <br /> Avoid using special characters or excessive punctuation in the creator's name |

### `publisher`

|                            |                                                                                                                                     |
| -------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- |
| **Example value**          | `"Vercel"`                                                                                                                          |
| **Correct usage**          | Use the `publisher` to set the document publisher.                                                                                  |
| **Best practices**         | Keep the publisher name short and descriptive                                                                                       |
| **SEO Importance**         | The publisher information helps search engines understand the content and can be displayed in search results.                       |
| **Fixing common mistakes** | Ensure the publisher name is set and not empty <br /> Avoid using special characters or excessive punctuation in the publisher name |

### `alternates`

|                            |                                                                                                                                                     |
| -------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Example value**          | `{ canonical: "https://example.com", hreflang: { "en-US": "https://example.com/en-US" } }`                                                          |
| **Correct usage**          | Use the `alternates` to set the canonical and alternate URLs for the document.                                                                      |
| **Best practices**         | Include the canonical URL and alternate URLs with appropriate hreflang attributes                                                                   |
| **SEO Importance**         | Canonical and alternate URLs help search engines understand the relationships between different versions of your content, improving search results. |
| **Fixing common mistakes** | Ensure the canonical and alternate URLs are set and not empty <br /> Use correct hreflang codes <br /> Avoid duplicate URLs                         |

### `icons`

|                            |                                                                                                                                                      |
| -------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Example value**          | `"https://example.com/icon.png"`                                                                                                                     |
| **Correct usage**          | Use the `icons` to set the document icons.                                                                                                           |
| **Best practices**         | Include icons for different devices and platforms <br /> Use appropriate rel attributes, such as "icon" and "apple-touch-icon"                       |
| **SEO Importance**         | Icons can improve the appearance of your content in search results and on social media, enhancing user experience and engagement.                    |
| **Fixing common mistakes** | Ensure the icon URLs are set and not empty <br /> Use correct rel attributes <br /> Provide appropriate file formats and sizes for different devices |

### `manifest`

|                            |                                                                                                                                          |
| -------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- |
| **Example value**          | `"https://example.com/manifest.json"`                                                                                                    |
| **Correct usage**          | Use the `manifest` to set the web application manifest for the document.                                                                 |
| **Best practices**         | Ensure the manifest file is valid and accessible                                                                                         |
| **SEO Importance**         | A web application manifest can improve your content's appearance on mobile devices and provide additional information to search engines. |
| **Fixing common mistakes** | Ensure the manifest URL is set and not empty <br /> Check the manifest file for errors and ensure it is accessible                       |

### `category`

|                            |                                                                                                                                   |
| -------------------------- | --------------------------------------------------------------------------------------------------------------------------------- |
| **Example value**          | `"My Category"`                                                                                                                   |
| **Correct usage**          | Use the `category` to set the category meta name property for the document.                                                       |
| **Best practices**         | Keep the category name short and descriptive                                                                                      |
| **SEO Importance**         | The category information helps search engines understand the content and can be displayed in search results.                      |
| **Fixing common mistakes** | Ensure the category name is set and not empty <br /> Avoid using special characters or excessive punctuation in the category name |

### Summary

In conclusion, having a solid understanding of metadata fields and their impact on SEO is **vital for creating successful web applications**. By leveraging the power of Next.js and its new **Metadata API**, you can easily create both static and dynamic metadata for your pages, enhancing your application's search engine rankings.

Remember to follow best practices and avoid common mistakes when working with metadata fields to ensure **optimal SEO performance**. Now, equipped with your newfound knowledge, you're ready to create outstanding, SEO-optimized web applications using Next.js!