How to add metadata
Here is a guide on how to add metadata. This entire documentation is referenced from Nextjs, so for a better view, please check this Nextjs tutorial - https://nextjs.org/docs/app/getting-started/metadata-and-og-images
The Metadata APIs can be used to define your application metadata for improved SEO and web shareability and include:
Special file conventions that can be used to add static or dynamically generated favicons and OG images.
With all the options above, Next.js will automatically generate the relevant <head>
tags for your page, which can be inspected in the browser's developer tools.
There are two default meta
tags that are always added even if a route doesn't define metadata:
The meta charset tag sets the character encoding for the website.
The meta viewport tag sets the viewport width and scale for the website to adjust for different devices.
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
The other metadata fields can be defined with the Metadata
object (for static metadata) or the generateMetadata
function (for generated metadata).
To define static metadata, export a Metadata
object from a static layout.js
or page.js
file. For example, to add a title and description to the blog route:
app/blog/layout.tsx
import type { Metadata } from 'next'
export const metadata: Metadata = {
title: 'My Blog',
description: '...',
}
export default function Page() {}
You can view a full list of available options, in the generate metadata documentation.
You can use generateMetadata
function to fetch
metadata that depends on data. For example, to fetch the title and description for a specific blog post:
app/blog/[slug]/page.tsx
import type { Metadata, ResolvingMetadata } from 'next'
type Props = {
params: Promise<{ id: string }>
searchParams: Promise<{ [key: string]: string | string[] | undefined }>
}
export async function generateMetadata(
{ params, searchParams }: Props,
parent: ResolvingMetadata
): Promise<Metadata> {
const slug = (await params).slug
// fetch post information
const post = await fetch(`https://api.vercel.app/blog/${slug}`).then((res) =>
res.json()
)
return {
title: post.title,
description: post.description,
}
}
export default function Page({ params, searchParams }: Props) {}
Behind-the-scenes, Next.js will stream metadata separately from the UI and inject the metadata into the HTML as soon as it's resolved.
Last updated
Was this helpful?