Unverified Commit d05288de authored by Delba de Oliveira's avatar Delba de Oliveira Committed by GitHub

Docs IA 2.0: Metadata (#78905)

Closes: https://linear.app/vercel/issue/DOC-4642/metadata
Redirects: https://github.com/vercel/front/pull/45244

- Expands `generateMetadata` API reference to describe behavior
- Adds new examples to the `ImageResponse` API reference
- Create JSON-LD guide

---------
Co-authored-by: 's avatarRich Haines <hello@richardhaines.dev>
parent 6e3af1b0
......@@ -7,10 +7,13 @@ related:
description: Learn more about the Metadata APIs mentioned in this page.
links:
- app/api-reference/functions/generate-metadata
- app/api-reference/functions/generate-viewport
- app/api-reference/functions/image-response
- app/api-reference/file-conventions/metadata
- app/api-reference/file-conventions/metadata/app-icons
- app/api-reference/file-conventions/metadata/opengraph-image
- app/api-reference/functions/image-response
- app/api-reference/file-conventions/metadata/robots
- app/api-reference/file-conventions/metadata/sitemap
---
The Metadata APIs can be used to define your application metadata for improved SEO and web shareability and include:
......@@ -59,7 +62,7 @@ export const metadata = {
export default function Page() {}
```
You can view a full list of available options, in the [generate metadata documentation](/docs/app/api-reference/functions/generate-metadata#metadata-fields).
You can view a full list of available options, in the [`generateMetadata` documentation](/docs/app/api-reference/functions/generate-metadata#metadata-fields).
## Generated metadata
......@@ -177,6 +180,17 @@ export default async function Page({ params }) {
}
```
## File-based metadata
The following special files are available for metadata:
- [favicon.ico, apple-icon.jpg, and icon.jpg](/docs/app/api-reference/file-conventions/metadata/app-icons)
- [opengraph-image.jpg and twitter-image.jpg](/docs/app/api-reference/file-conventions/metadata/opengraph-image)
- [robots.txt](/docs/app/api-reference/file-conventions/metadata/robots)
- [sitemap.xml](/docs/app/api-reference/file-conventions/metadata/sitemap)
You can use these for static metadata, or you can programmatically generate these files with code.
## Favicons
Favicons are small icons that represent your site in bookmarks and search results. To add a favicon to your application, create a `favicon.ico` and add to the root of the app folder.
......
---
title: How to implement JSON-LD in your Next.js application
nav_title: JSON-LD
description: Learn how to add JSON-LD to your Next.js application to describe your content to search engines and AI.
---
[JSON-LD](https://json-ld.org/) is a format for structured data that can be used by search engines and AI to to help them understand the structure of the page beyond pure content. For example, you can use it to describe a person, an event, an organization, a movie, a book, a recipe, and many other types of entities.
Our current recommendation for JSON-LD is to render structured data as a `<script>` tag in your `layout.js` or `page.js` components. For example:
```tsx filename="app/products/[id]/page.tsx" switcher
export default async function Page({ params }) {
const { id } = await params
const product = await getProduct(id)
const jsonLd = {
'@context': 'https://schema.org',
'@type': 'Product',
name: product.name,
image: product.image,
description: product.description,
}
return (
<section>
{/* Add JSON-LD to your page */}
<script
type="application/ld+json"
dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd) }}
/>
{/* ... */}
</section>
)
}
```
```jsx filename="app/products/[id]/page.js" switcher
export default async function Page({ params }) {
const { id } = await params
const product = await getProduct(id)
const jsonLd = {
'@context': 'https://schema.org',
'@type': 'Product',
name: product.name,
image: product.image,
description: product.description,
}
return (
<section>
{/* Add JSON-LD to your page */}
<script
type="application/ld+json"
dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd) }}
/>
{/* ... */}
</section>
)
}
```
You can validate and test your structured data with the [Rich Results Test](https://search.google.com/test/rich-results) for Google or the generic [Schema Markup Validator](https://validator.schema.org/).
You can type your JSON-LD with TypeScript using community packages like [`schema-dts`](https://www.npmjs.com/package/schema-dts):
```tsx
import { Product, WithContext } from 'schema-dts'
const jsonLd: WithContext<Product> = {
'@context': 'https://schema.org',
'@type': 'Product',
name: 'Next.js Sticker',
image: 'https://nextjs.org/imgs/sticker.png',
description: 'Dynamic at the speed of static.',
}
```
......@@ -110,7 +110,7 @@ When using file based routing, you can use MDX pages like any other page.
<AppOnly>
In App Router apps, that includes being able to use [metadata](/docs/app/building-your-application/optimizing/metadata).
In App Router apps, that includes being able to use [metadata](/docs/app/getting-started/metadata-and-og-images).
Create a new MDX page within the `/app` directory:
......
......@@ -166,7 +166,7 @@ export default function RootLayout({
- The root layout replaces the `pages/_app.tsx` and `pages/_document.tsx` files.
- `.js`, `.jsx`, or `.tsx` extensions can be used for layout files.
To manage `<head>` HTML elements, you can use the [built-in SEO support](/docs/app/building-your-application/optimizing/metadata):
To manage `<head>` HTML elements, you can use the [built-in SEO support](/docs/app/getting-started/metadata-and-og-images):
```tsx filename="app/layout.tsx" switcher
import type { Metadata } from 'next'
......@@ -265,7 +265,7 @@ Page.getLayout = function getLayout(page) {
### Step 3: Migrating `next/head`
In the `pages` directory, the `next/head` React component is used to manage `<head>` HTML elements such as `title` and `meta` . In the `app` directory, `next/head` is replaced with the new [built-in SEO support](/docs/app/building-your-application/optimizing/metadata).
In the `pages` directory, the `next/head` React component is used to manage `<head>` HTML elements such as `title` and `meta` . In the `app` directory, `next/head` is replaced with the new [built-in SEO support](/docs/app/getting-started/metadata-and-og-images).
**Before:**
......
......@@ -145,7 +145,7 @@ export default function RootLayout({ children }) {
}
```
> **Good to know**: Next.js ignores CRA’s `public/manifest.json`, additional iconography, and [testing configuration](/docs/app/guides/testing) by default. If you need these, Next.js has support with its [Metadata API](/docs/app/building-your-application/optimizing/metadata) and [Testing](/docs/app/guides/testing) setup.
> **Good to know**: Next.js ignores CRA’s `public/manifest.json`, additional iconography, and [testing configuration](/docs/app/guides/testing) by default. If you need these, Next.js has support with its [Metadata API](/docs/app/getting-started/metadata-and-og-images) and [Testing](/docs/app/guides/testing) setup.
### Step 4: Metadata
......@@ -189,7 +189,7 @@ export default function RootLayout({ children }) {
}
```
Any [metadata files](/docs/app/building-your-application/optimizing/metadata#file-based-metadata) such as `favicon.ico`, `icon.png`, `robots.txt` are automatically added to the application `<head>` tag as long as you have them placed into the top level of the `app` directory. After moving [all supported files](/docs/app/building-your-application/optimizing/metadata#file-based-metadata) into the `app` directory you can safely delete their `<link>` tags:
Any [metadata files](/docs/app/getting-started/metadata-and-og-images#file-based-metadata) such as `favicon.ico`, `icon.png`, `robots.txt` are automatically added to the application `<head>` tag as long as you have them placed into the top level of the `app` directory. After moving [all supported files](/docs/app/getting-started/metadata-and-og-images#file-based-metadata) into the `app` directory you can safely delete their `<link>` tags:
```tsx filename="app/layout.tsx" switcher
export default function RootLayout({
......@@ -227,7 +227,7 @@ export default function RootLayout({ children }) {
}
```
Finally, Next.js can manage your last `<head>` tags with the [Metadata API](/docs/app/building-your-application/optimizing/metadata). Move your final metadata info into an exported [`metadata` object](/docs/app/api-reference/functions/generate-metadata#metadata-object):
Finally, Next.js can manage your last `<head>` tags with the [Metadata API](/docs/app/getting-started/metadata-and-og-images). Move your final metadata info into an exported [`metadata` object](/docs/app/api-reference/functions/generate-metadata#metadata-object):
```tsx filename="app/layout.tsx" switcher
import type { Metadata } from 'next'
......@@ -269,7 +269,7 @@ export default function RootLayout({ children }) {
}
```
With the above changes, you shifted from declaring everything in your `index.html` to using Next.js' convention-based approach built into the framework ([Metadata API](/docs/app/building-your-application/optimizing/metadata)). This approach enables you to more easily improve your SEO and web shareability of your pages.
With the above changes, you shifted from declaring everything in your `index.html` to using Next.js' convention-based approach built into the framework ([Metadata API](/docs/app/getting-started/metadata-and-og-images)). This approach enables you to more easily improve your SEO and web shareability of your pages.
### Step 5: Styles
......
......@@ -249,11 +249,11 @@ export default function RootLayout({ children }) {
}
```
5. Any [metadata files](/docs/app/building-your-application/optimizing/metadata#file-based-metadata)
5. Any [metadata files](/docs/app/getting-started/metadata-and-og-images#file-based-metadata)
such as `favicon.ico`, `icon.png`, `robots.txt` are automatically added to the application
`<head>` tag as long as you have them placed into the top level of the `app` directory. After
moving
[all supported files](/docs/app/building-your-application/optimizing/metadata#file-based-metadata)
[all supported files](/docs/app/getting-started/metadata-and-og-images#file-based-metadata)
into the `app` directory you can safely delete their `<link>` tags:
```tsx filename="app/layout.tsx" switcher
......@@ -293,7 +293,7 @@ export default function RootLayout({ children }) {
```
6. Finally, Next.js can manage your last `<head>` tags with the
[Metadata API](/docs/app/building-your-application/optimizing/metadata). Move your final metadata
[Metadata API](/docs/app/getting-started/metadata-and-og-images). Move your final metadata
info into an exported
[`metadata` object](/docs/app/api-reference/functions/generate-metadata#metadata-object):
......@@ -339,7 +339,7 @@ export default function RootLayout({ children }) {
With the above changes, you shifted from declaring everything in your `index.html` to using Next.js'
convention-based approach built into the framework
([Metadata API](/docs/app/building-your-application/optimizing/metadata)). This approach enables you
([Metadata API](/docs/app/getting-started/metadata-and-og-images)). This approach enables you
to more easily improve your SEO and web shareability of your pages.
### Step 5: Create the Entrypoint Page
......
......@@ -108,7 +108,7 @@ While building your application, we recommend using the following features to en
<AppOnly>
- **[Metadata API](/docs/app/building-your-application/optimizing/metadata):** Use the Metadata API to improve your application's Search Engine Optimization (SEO) by adding page titles, descriptions, and more.
- **[Metadata API](/docs/app/getting-started/metadata-and-og-images):** Use the Metadata API to improve your application's Search Engine Optimization (SEO) by adding page titles, descriptions, and more.
- **[Open Graph (OG) images](/docs/app/api-reference/file-conventions/metadata/opengraph-image):** Create OG images to prepare your application for social sharing.
- **[Sitemaps](/docs/app/api-reference/functions/generate-sitemaps) and [Robots](/docs/app/api-reference/file-conventions/metadata/robots):** Help Search Engines crawl and index your pages by generating sitemaps and robots files.
......
......@@ -208,7 +208,7 @@ export function GET(req: NextRequest) {
npx @next/codemod@latest next-og-import .
```
This codemod moves transforms imports from `next/server` to `next/og` for usage of [Dynamic OG Image Generation](/docs/app/building-your-application/optimizing/metadata#dynamic-image-generation).
This codemod moves transforms imports from `next/server` to `next/og` for usage of [Dynamic OG Image Generation](/docs/app/getting-started/metadata-and-og-images#generated-open-graph-images).
For example:
......
......@@ -187,7 +187,7 @@ In terms of nesting, `template.js` is rendered between a layout and its children
### Metadata
You can modify the `<head>` HTML elements such as `title` and `meta` using the [Metadata APIs](/docs/app/building-your-application/optimizing/metadata).
You can modify the `<head>` HTML elements such as `title` and `meta` using the [Metadata APIs](/docs/app/getting-started/metadata-and-og-images).
Metadata can be defined by exporting a [`metadata` object](/docs/app/api-reference/functions/generate-metadata#the-metadata-object) or [`generateMetadata` function](/docs/app/api-reference/functions/generate-metadata#generatemetadata-function) in a [`layout.js`](/docs/app/api-reference/file-conventions/layout) or [`page.js`](/docs/app/api-reference/file-conventions/page) file.
......
---
title: Metadata
description: Use the Metadata API to define metadata in any layout or page.
related:
description: View all the Metadata API options.
links:
- app/api-reference/functions/generate-metadata
- app/api-reference/file-conventions/metadata
- app/api-reference/functions/generate-viewport
---
Next.js has a Metadata API that can be used to define your application metadata (e.g. `meta` and `link` tags inside your HTML `head` element) for improved SEO and web shareability.
There are two ways you can add metadata to your application:
- **Config-based Metadata**: Export a [static `metadata` object](/docs/app/api-reference/functions/generate-metadata#metadata-object) or a dynamic [`generateMetadata` function](/docs/app/api-reference/functions/generate-metadata#generatemetadata-function) in a `layout.js` or `page.js` file.
- **File-based Metadata**: Add static or dynamically generated special files to route segments.
With both these options, Next.js will automatically generate the relevant `<head>` elements for your pages. You can also create dynamic OG images using the [`ImageResponse`](/docs/app/api-reference/functions/image-response) constructor.
## Static Metadata
To define static metadata, export a [`Metadata` object](/docs/app/api-reference/functions/generate-metadata#metadata-object) from a `layout.js` or static `page.js` file.
```tsx filename="layout.tsx | page.tsx" switcher
import type { Metadata } from 'next'
export const metadata: Metadata = {
title: '...',
description: '...',
}
export default function Page() {}
```
```jsx filename="layout.js | page.js" switcher
export const metadata = {
title: '...',
description: '...',
}
export default function Page() {}
```
For all the available options, see the [API Reference](/docs/app/api-reference/functions/generate-metadata).
## Dynamic Metadata
You can use `generateMetadata` function to `fetch` metadata that requires dynamic values.
```tsx filename="app/products/[id]/page.tsx" switcher
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> {
// read route params
const { id } = await params
// fetch data
const product = await fetch(`https://.../${id}`).then((res) => res.json())
// optionally access and extend (rather than replace) parent metadata
const previousImages = (await parent).openGraph?.images || []
return {
title: product.title,
openGraph: {
images: ['/some-specific-page-image.jpg', ...previousImages],
},
}
}
export default function Page({ params, searchParams }: Props) {}
```
```jsx filename="app/products/[id]/page.js" switcher
export async function generateMetadata({ params, searchParams }, parent) {
// read route params
const { id } = await params
// fetch data
const product = await fetch(`https://.../${id}`).then((res) => res.json())
// optionally access and extend (rather than replace) parent metadata
const previousImages = (await parent).openGraph?.images || []
return {
title: product.title,
openGraph: {
images: ['/some-specific-page-image.jpg', ...previousImages],
},
}
}
export default function Page({ params, searchParams }) {}
```
For all the available params, see the [API Reference](/docs/app/api-reference/functions/generate-metadata).
> **Good to know**:
>
> - Both static and dynamic metadata through `generateMetadata` are **only supported in Server Components**.
> - `fetch` requests are automatically [memoized](/docs/app/deep-dive/caching#request-memoization) for the same data across `generateMetadata`, `generateStaticParams`, Layouts, Pages, and Server Components. React [`cache` can be used](/docs/app/deep-dive/caching#react-cache-function) if `fetch` is unavailable.
> - Next.js will wait for data fetching inside `generateMetadata` to complete before streaming UI to the client. This guarantees the first part of a [streamed response](/docs/app/building-your-application/routing/loading-ui-and-streaming) includes `<head>` tags.
## File-based metadata
These special files are available for metadata:
- [favicon.ico, apple-icon.jpg, and icon.jpg](/docs/app/api-reference/file-conventions/metadata/app-icons)
- [opengraph-image.jpg and twitter-image.jpg](/docs/app/api-reference/file-conventions/metadata/opengraph-image)
- [robots.txt](/docs/app/api-reference/file-conventions/metadata/robots)
- [sitemap.xml](/docs/app/api-reference/file-conventions/metadata/sitemap)
You can use these for static metadata, or you can programmatically generate these files with code.
For implementation and examples, see the [Metadata Files](/docs/app/api-reference/file-conventions/metadata) API Reference and [Dynamic Image Generation](#dynamic-image-generation).
## Behavior
File-based metadata has the higher priority and will override any config-based metadata.
### Default Fields
There are two default `meta` tags that are always added even if a route doesn't define metadata:
- The [meta charset tag](https://developer.mozilla.org/docs/Web/HTML/Element/meta#attr-charset) sets the character encoding for the website.
- The [meta viewport tag](https://developer.mozilla.org/docs/Web/HTML/Viewport_meta_tag) sets the viewport width and scale for the website to adjust for different devices.
```html
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
```
> **Good to know**: You can overwrite the default [`viewport`](/docs/app/api-reference/functions/generate-metadata#viewport) meta tag.
### Ordering
Metadata is evaluated in order, starting from the root segment down to the segment closest to the final `page.js` segment. For example:
1. `app/layout.tsx` (Root Layout)
2. `app/blog/layout.tsx` (Nested Blog Layout)
3. `app/blog/[slug]/page.tsx` (Blog Page)
### Merging
Following the [evaluation order](#ordering), Metadata objects exported from multiple segments in the same route are **shallowly** merged together to form the final metadata output of a route. Duplicate keys are **replaced** based on their ordering.
This means metadata with nested fields such as [`openGraph`](/docs/app/api-reference/functions/generate-metadata#opengraph) and [`robots`](/docs/app/api-reference/functions/generate-metadata#robots) that are defined in an earlier segment are **overwritten** by the last segment to define them.
#### Overwriting fields
```jsx filename="app/layout.js"
export const metadata = {
title: 'Acme',
openGraph: {
title: 'Acme',
description: 'Acme is a...',
},
}
```
```jsx filename="app/blog/page.js"
export const metadata = {
title: 'Blog',
openGraph: {
title: 'Blog',
},
}
// Output:
// <title>Blog</title>
// <meta property="og:title" content="Blog" />
```
In the example above:
- `title` from `app/layout.js` is **replaced** by `title` in `app/blog/page.js`.
- All `openGraph` fields from `app/layout.js` are **replaced** in `app/blog/page.js` because `app/blog/page.js` sets `openGraph` metadata. Note the absence of `openGraph.description`.
If you'd like to share some nested fields between segments while overwriting others, you can pull them out into a separate variable:
```jsx filename="app/shared-metadata.js"
export const openGraphImage = { images: ['http://...'] }
```
```jsx filename="app/page.js"
import { openGraphImage } from './shared-metadata'
export const metadata = {
openGraph: {
...openGraphImage,
title: 'Home',
},
}
```
```jsx filename="app/about/page.js"
import { openGraphImage } from '../shared-metadata'
export const metadata = {
openGraph: {
...openGraphImage,
title: 'About',
},
}
```
In the example above, the OG image is shared between `app/layout.js` and `app/about/page.js` while the titles are different.
#### Inheriting fields
```jsx filename="app/layout.js"
export const metadata = {
title: 'Acme',
openGraph: {
title: 'Acme',
description: 'Acme is a...',
},
}
```
```jsx filename="app/about/page.js"
export const metadata = {
title: 'About',
}
// Output:
// <title>About</title>
// <meta property="og:title" content="Acme" />
// <meta property="og:description" content="Acme is a..." />
```
**Notes**
- `title` from `app/layout.js` is **replaced** by `title` in `app/about/page.js`.
- All `openGraph` fields from `app/layout.js` are **inherited** in `app/about/page.js` because `app/about/page.js` doesn't set `openGraph` metadata.
## Dynamic Image Generation
The `ImageResponse` constructor allows you to generate dynamic images using JSX and CSS. This is useful for creating social media images such as Open Graph images, Twitter cards, and more.
To use it, you can import `ImageResponse` from `next/og`:
```jsx filename="app/about/opengraph-image.js"
import { ImageResponse } from 'next/og'
export default function OG() {
return new ImageResponse(
(
<div
style={{
fontSize: 128,
background: 'white',
width: '100%',
height: '100%',
display: 'flex',
textAlign: 'center',
alignItems: 'center',
justifyContent: 'center',
}}
>
Hello world!
</div>
),
{
width: 1200,
height: 600,
}
)
}
```
`ImageResponse` integrates well with other Next.js APIs, including [Route Handlers](/docs/app/building-your-application/routing/route-handlers) and file-based Metadata. For example, you can use `ImageResponse` in a `opengraph-image.tsx` file to generate Open Graph images at build time or dynamically at request time.
`ImageResponse` supports common CSS properties including flexbox and absolute positioning, custom fonts, text wrapping, centering, and nested images. [See the full list of supported CSS properties](/docs/app/api-reference/functions/image-response).
> **Good to know**:
>
> - Examples are available in the [Vercel OG Playground](https://og-playground.vercel.app/).
> - `ImageResponse` uses [@vercel/og](https://vercel.com/docs/concepts/functions/edge-functions/og-image-generation), [Satori](https://github.com/vercel/satori), and Resvg to convert HTML and CSS into PNG.
> - Only flexbox and a subset of CSS properties are supported. Advanced layouts (e.g. `display: grid`) will not work.
> - Maximum bundle size of `500KB`. The bundle size includes your JSX, CSS, fonts, images, and any other assets. If you exceed the limit, consider reducing the size of any assets or fetching at runtime.
> - Only `ttf`, `otf`, and `woff` font formats are supported. To maximize the font parsing speed, `ttf` or `otf` are preferred over `woff`.
## JSON-LD
[JSON-LD](https://json-ld.org/) is a format for structured data that can be used by search engines to understand your content. For example, you can use it to describe a person, an event, an organization, a movie, a book, a recipe, and many other types of entities.
Our current recommendation for JSON-LD is to render structured data as a `<script>` tag in your `layout.js` or `page.js` components. For example:
```tsx filename="app/products/[id]/page.tsx" switcher
export default async function Page({ params }) {
const { id } = await params
const product = await getProduct(id)
const jsonLd = {
'@context': 'https://schema.org',
'@type': 'Product',
name: product.name,
image: product.image,
description: product.description,
}
return (
<section>
{/* Add JSON-LD to your page */}
<script
type="application/ld+json"
dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd) }}
/>
{/* ... */}
</section>
)
}
```
```jsx filename="app/products/[id]/page.js" switcher
export default async function Page({ params }) {
const { id } = await params
const product = await getProduct(id)
const jsonLd = {
'@context': 'https://schema.org',
'@type': 'Product',
name: product.name,
image: product.image,
description: product.description,
}
return (
<section>
{/* Add JSON-LD to your page */}
<script
type="application/ld+json"
dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd) }}
/>
{/* ... */}
</section>
)
}
```
You can validate and test your structured data with the [Rich Results Test](https://search.google.com/test/rich-results) for Google or the generic [Schema Markup Validator](https://validator.schema.org/).
You can type your JSON-LD with TypeScript using community packages like [`schema-dts`](https://www.npmjs.com/package/schema-dts):
```tsx
import { Product, WithContext } from 'schema-dts'
const jsonLd: WithContext<Product> = {
'@context': 'https://schema.org',
'@type': 'Product',
name: 'Next.js Sticker',
image: 'https://nextjs.org/imgs/sticker.png',
description: 'Dynamic at the speed of static.',
}
```
......@@ -113,7 +113,7 @@ export default function RootLayout({ children }) {
```
- The root layout **must** define `<html>` and `<body>` tags.
- You should **not** manually add `<head>` tags such as `<title>` and `<meta>` to root layouts. Instead, you should use the [Metadata API](/docs/app/building-your-application/optimizing/metadata) which automatically handles advanced requirements such as streaming and de-duplicating `<head>` elements.
- You should **not** manually add `<head>` tags such as `<title>` and `<meta>` to root layouts. Instead, you should use the [Metadata API](/docs/app/getting-started/metadata-and-og-images) which automatically handles advanced requirements such as streaming and de-duplicating `<head>` elements.
- You can use [route groups](/docs/app/building-your-application/routing/route-groups) to create multiple root layouts.
- Navigating **across multiple root layouts** will cause a **full page load** (as opposed to a client-side navigation). For example, navigating from `/cart` that uses `app/(shop)/layout.js` to `/blog` that uses `app/(marketing)/layout.js` will cause a full page load. This **only** applies to multiple root layouts.
......
......@@ -6,7 +6,6 @@ related:
description: View all the Metadata API options.
links:
- app/api-reference/file-conventions/metadata
- app/building-your-application/optimizing/metadata
---
You can use `generateImageMetadata` to generate different versions of one image or return multiple images for one route segment. This is useful for when you want to avoid hard-coding metadata values, such as for icons.
......
......@@ -7,45 +7,9 @@ related:
links:
- app/api-reference/file-conventions/metadata
- app/api-reference/functions/generate-viewport
- app/building-your-application/optimizing/metadata
---
This page covers all **Config-based Metadata** options with `generateMetadata` and the static metadata object.
```tsx filename="layout.tsx | page.tsx" switcher
import type { Metadata } from 'next'
// either Static metadata
export const metadata: Metadata = {
title: '...',
}
// or Dynamic metadata
export async function generateMetadata({ params }) {
return {
title: '...',
}
}
```
```jsx filename="layout.js | page.js" switcher
// either Static metadata
export const metadata = {
title: '...',
}
// or Dynamic metadata
export async function generateMetadata({ params }) {
return {
title: '...',
}
}
```
> **Good to know**:
>
> - The `metadata` object and `generateMetadata` function exports are **only supported in Server Components**.
> - You cannot export both the `metadata` object and `generateMetadata` function from the same route segment.
You can use the `metadata` object or the `generateMetadata` function to define metadata.
## The `metadata` object
......@@ -71,7 +35,7 @@ export const metadata = {
export default function Page() {}
```
See the [Metadata Fields](#metadata-fields) for a complete list of supported options.
> See the [Metadata Fields](#metadata-fields) for a complete list of supported options.
## `generateMetadata` function
......@@ -131,6 +95,17 @@ export async function generateMetadata({ params, searchParams }, parent) {
export default function Page({ params, searchParams }) {}
```
> **Good to know**:
>
> - Metadata can be added to `layout.js` and `page.js` files.
> - Next.js will automatically resolve the metadata, and create the relevant `<head>` tags for the page.
> - The `metadata` object and `generateMetadata` function exports are **only supported in Server Components**.
> - You cannot export both the `metadata` object and `generateMetadata` function from the same route segment.
> - `fetch` requests inside `generateMetadata` are automatically [memoized](/docs/app/deep-dive/caching#request-memoization) for the same data across `generateMetadata`, `generateStaticParams`, Layouts, Pages, and Server Components.
> - React [`cache` can be used](/docs/app/deep-dive/caching#react-cache-function) if `fetch` is unavailable. -[ File-based metadat](/docs/app/api-reference/file-conventions/metadata) has the higher priority and will override the `metadata` object and `generateMetadata` function.
## Reference
### Parameters
`generateMetadata` function accepts the following parameters:
......@@ -166,13 +141,15 @@ export default function Page({ params, searchParams }) {}
> - `searchParams` are only available in `page.js` segments.
> - The [`redirect()`](/docs/app/api-reference/functions/redirect) and [`notFound()`](/docs/app/api-reference/functions/not-found) Next.js methods can also be used inside `generateMetadata`.
## Metadata Fields
### Metadata Fields
The following fields are supported:
### `title`
#### `title`
The `title` attribute is used to set the title of the document. It can be defined as a simple [string](#string) or an optional [template object](#template-object).
The `title` attribute is used to set the title of the document. It can be defined as a simple [string](#string) or an optional [template object](#template).
#### String
##### String
```jsx filename="layout.js | page.js"
export const metadata = {
......@@ -184,31 +161,7 @@ export const metadata = {
<title>Next.js</title>
```
#### Template object
```tsx filename="app/layout.tsx" switcher
import type { Metadata } from 'next'
export const metadata: Metadata = {
title: {
template: '...',
default: '...',
absolute: '...',
},
}
```
```jsx filename="app/layout.js" switcher
export const metadata = {
title: {
default: '...',
template: '...',
absolute: '...',
},
}
```
##### Default
##### `default`
`title.default` can be used to provide a **fallback title** to child route segments that don't define a `title`.
......@@ -230,7 +183,7 @@ export const metadata: Metadata = {}
// Output: <title>Acme</title>
```
##### Template
##### `template`
`title.template` can be used to add a prefix or a suffix to `titles` defined in **child** route segments.
......@@ -282,7 +235,7 @@ export const metadata = {
>
> - `title.template` has **no effect** if a route has not defined a `title` or `title.default`.
##### Absolute
##### `absolute`
`title.absolute` can be used to provide a title that **ignores** `title.template` set in parent segments.
......@@ -352,7 +305,7 @@ export const metadata = {
<meta name="description" content="The React Framework for the Web" />
```
### Basic Fields
### Other fields
```jsx filename="layout.js | page.js"
export const metadata = {
......@@ -385,7 +338,7 @@ export const metadata = {
<meta name="format-detection" content="telephone=no, address=no, email=no" />
```
### `metadataBase`
#### `metadataBase`
`metadataBase` is a convenience option to set a base URL prefix for `metadata` fields that require a fully qualified URL.
......@@ -1023,10 +976,95 @@ export const metadata = {
<meta name="custom" content="meta1" /> <meta name="custom" content="meta2" />
```
## Unsupported Metadata
### Unsupported Metadata
The following metadata types do not currently have built-in support. However, they can still be rendered in the layout or page itself.
### Types
You can add type safety to your metadata by using the `Metadata` type. If you are using the [built-in TypeScript plugin](/docs/app/api-reference/config/typescript) in your IDE, you do not need to manually add the type, but you can still explicitly add it if you want.
#### `metadata` object
```tsx filename="layout.tsx | page.tsx"
import type { Metadata } from 'next'
export const metadata: Metadata = {
title: 'Next.js',
}
```
#### `generateMetadata` function
##### Regular function
```tsx filename="layout.tsx | page.tsx"
import type { Metadata } from 'next'
export function generateMetadata(): Metadata {
return {
title: 'Next.js',
}
}
```
##### Async function
```tsx filename="layout.tsx | page.tsx"
import type { Metadata } from 'next'
export async function generateMetadata(): Promise<Metadata> {
return {
title: 'Next.js',
}
}
```
##### With segment props
```tsx filename="layout.tsx | page.tsx"
import type { Metadata } from 'next'
type Props = {
params: Promise<{ id: string }>
searchParams: Promise<{ [key: string]: string | string[] | undefined }>
}
export function generateMetadata({ params, searchParams }: Props): Metadata {
return {
title: 'Next.js',
}
}
export default function Page({ params, searchParams }: Props) {}
```
##### With parent metadata
```tsx filename="layout.tsx | page.tsx"
import type { Metadata, ResolvingMetadata } from 'next'
export async function generateMetadata(
{ params, searchParams }: Props,
parent: ResolvingMetadata
): Promise<Metadata> {
return {
title: 'Next.js',
}
}
```
##### JavaScript Projects
For JavaScript projects, you can use JSDoc to add type safety.
```js filename="layout.js | page.js"
/** @type {import("next").Metadata} */
export const metadata = {
title: 'Next.js',
}
```
| Metadata | Recommendation |
| ----------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `<meta http-equiv="...">` | Use appropriate HTTP Headers via [`redirect()`](/docs/app/api-reference/functions/redirect), [Middleware](/docs/app/building-your-application/routing/middleware#nextresponse), [Security Headers](/docs/app/api-reference/config/next-config-js/headers) |
......@@ -1073,7 +1111,7 @@ export function PreloadResources() {
}
```
##### `<link rel="preload">`
#### `<link rel="preload">`
Start loading a resource early in the page rendering (browser) lifecycle. [MDN Docs](https://developer.mozilla.org/docs/Web/HTML/Attributes/rel/preload).
......@@ -1097,7 +1135,7 @@ ReactDOM.preconnect(href: string, options?: { crossOrigin?: string })
<link rel="preconnect" href="..." crossorigin />
```
##### `<link rel="dns-prefetch">`
#### `<link rel="dns-prefetch">`
Attempt to resolve a domain name before resources get requested. [MDN Docs](https://developer.mozilla.org/docs/Web/HTML/Attributes/rel/dns-prefetch).
......@@ -1114,118 +1152,151 @@ ReactDOM.prefetchDNS(href: string)
> - These methods are currently only supported in Client Components, which are still Server Side Rendered on initial page load.
> - Next.js in-built features such as `next/font`, `next/image` and `next/script` automatically handle relevant resource hints.
## Types
## Behavior
You can add type safety to your metadata by using the `Metadata` type. If you are using the [built-in TypeScript plugin](/docs/app/api-reference/config/typescript) in your IDE, you do not need to manually add the type, but you can still explicitly add it if you want.
### Default Fields
### `metadata` object
There are two default `meta` tags that are always added even if a route doesn't define metadata:
```tsx filename="layout.tsx | page.tsx"
import type { Metadata } from 'next'
- The [meta charset tag](https://developer.mozilla.org/docs/Web/HTML/Element/meta#attr-charset) sets the character encoding for the website.
- The [meta viewport tag](https://developer.mozilla.org/docs/Web/HTML/Viewport_meta_tag) sets the viewport width and scale for the website to adjust for different devices.
export const metadata: Metadata = {
title: 'Next.js',
}
```html
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
```
### `generateMetadata` function
> **Good to know**: You can overwrite the default [`viewport`](/docs/app/api-reference/functions/generate-metadata#viewport) meta tag.
#### Regular function
### Streaming metadata
```tsx filename="layout.tsx | page.tsx"
import type { Metadata } from 'next'
Metadata returned by `generateMetadata` is streamed to the client. This allows Next.js to inject metadata into the HTML as soon as it's resolved.
export function generateMetadata(): Metadata {
return {
title: 'Next.js',
}
}
```
Since page metadata primarily targets bots and crawlers, Next.js will stream metadata for bots that can execute JavaScript and inspect the full page DOM (e.g. `Googlebot`). However, metadata will continue blocking the render of the page for **HTML-limited** bots (e.g. `Twitterbot`) as these cannot execute JavaScript while crawling.
#### Async function
Next.js automatically detects the user agent of incoming requests to determine whether to serve streaming metadata or fallback to blocking metadata.
```tsx filename="layout.tsx | page.tsx"
import type { Metadata } from 'next'
If you need to customize this list, you can define them manually using the `htmlLimitedBots` option in `next.config.js`. Next.js will ensure user agents matching this regex receive blocking metadata when requesting your web page.
export async function generateMetadata(): Promise<Metadata> {
return {
title: 'Next.js',
}
```ts filename="next.config.ts" switcher
import type { NextConfig } from 'next'
const config: NextConfig = {
htmlLimitedBots: 'MySpecialBot|MyAnotherSpecialBot|SimpleCrawler',
}
export default config
```
#### With segment props
```js filename="next.config.js" switcher
module.exports = {
htmlLimitedBots: 'MySpecialBot|MyAnotherSpecialBot|SimpleCrawler',
}
```
```tsx filename="layout.tsx | page.tsx"
import type { Metadata } from 'next'
Specifying a `htmlLimitedBots` config will override the Next.js' default list, allowing you full control over what user agents should opt into this behavior. This is advanced behavior, and the default should be sufficient for most cases.
type Props = {
params: Promise<{ id: string }>
searchParams: Promise<{ [key: string]: string | string[] | undefined }>
}
### Ordering
export function generateMetadata({ params, searchParams }: Props): Metadata {
return {
title: 'Next.js',
}
}
Metadata is evaluated in order, starting from the root segment down to the segment closest to the final `page.js` segment. For example:
export default function Page({ params, searchParams }: Props) {}
```
1. `app/layout.tsx` (Root Layout)
2. `app/blog/layout.tsx` (Nested Blog Layout)
3. `app/blog/[slug]/page.tsx` (Blog Page)
#### With parent metadata
### Merging
```tsx filename="layout.tsx | page.tsx"
import type { Metadata, ResolvingMetadata } from 'next'
Following the [evaluation order](#ordering), Metadata objects exported from multiple segments in the same route are **shallowly** merged together to form the final metadata output of a route. Duplicate keys are **replaced** based on their ordering.
export async function generateMetadata(
{ params, searchParams }: Props,
parent: ResolvingMetadata
): Promise<Metadata> {
return {
title: 'Next.js',
}
}
```
This means metadata with nested fields such as [`openGraph`](/docs/app/api-reference/functions/generate-metadata#opengraph) and [`robots`](/docs/app/api-reference/functions/generate-metadata#robots) that are defined in an earlier segment are **overwritten** by the last segment to define them.
#### JavaScript Projects
#### Overwriting fields
For JavaScript projects, you can use JSDoc to add type safety.
```jsx filename="app/layout.js"
export const metadata = {
title: 'Acme',
openGraph: {
title: 'Acme',
description: 'Acme is a...',
},
}
```
```js filename="layout.js | page.js"
/** @type {import("next").Metadata} */
```jsx filename="app/blog/page.js"
export const metadata = {
title: 'Next.js',
title: 'Blog',
openGraph: {
title: 'Blog',
},
}
// Output:
// <title>Blog</title>
// <meta property="og:title" content="Blog" />
```
## Streaming metadata
In the example above:
Metadata returned by `generateMetadata` is streamed to the client. This allows Next.js to inject metadata into the HTML as soon as it's resolved.
- `title` from `app/layout.js` is **replaced** by `title` in `app/blog/page.js`.
- All `openGraph` fields from `app/layout.js` are **replaced** in `app/blog/page.js` because `app/blog/page.js` sets `openGraph` metadata. Note the absence of `openGraph.description`.
Since page metadata primarily targets bots and crawlers, Next.js will stream metadata for bots that can execute JavaScript and inspect the full page DOM (e.g. `Googlebot`). However, metadata will continue blocking the render of the page for **HTML-limited** bots (e.g. `Twitterbot`) as these cannot execute JavaScript while crawling.
If you'd like to share some nested fields between segments while overwriting others, you can pull them out into a separate variable:
Next.js automatically detects the user agent of incoming requests to determine whether to serve streaming metadata or fallback to blocking metadata.
```jsx filename="app/shared-metadata.js"
export const openGraphImage = { images: ['http://...'] }
```
If you need to customize this list, you can define them manually using the `htmlLimitedBots` option in `next.config.js`. Next.js will ensure user agents matching this regex receive blocking metadata when requesting your web page.
```jsx filename="app/page.js"
import { openGraphImage } from './shared-metadata'
```ts filename="next.config.ts" switcher
import type { NextConfig } from 'next'
export const metadata = {
openGraph: {
...openGraphImage,
title: 'Home',
},
}
```
const config: NextConfig = {
htmlLimitedBots: 'MySpecialBot|MyAnotherSpecialBot|SimpleCrawler',
```jsx filename="app/about/page.js"
import { openGraphImage } from '../shared-metadata'
export const metadata = {
openGraph: {
...openGraphImage,
title: 'About',
},
}
```
export default config
In the example above, the OG image is shared between `app/layout.js` and `app/about/page.js` while the titles are different.
#### Inheriting fields
```jsx filename="app/layout.js"
export const metadata = {
title: 'Acme',
openGraph: {
title: 'Acme',
description: 'Acme is a...',
},
}
```
```js filename="next.config.js" switcher
module.exports = {
htmlLimitedBots: 'MySpecialBot|MyAnotherSpecialBot|SimpleCrawler',
```jsx filename="app/about/page.js"
export const metadata = {
title: 'About',
}
// Output:
// <title>About</title>
// <meta property="og:title" content="Acme" />
// <meta property="og:description" content="Acme is a..." />
```
Specifying a `htmlLimitedBots` config will override the Next.js' default list, allowing you full control over what user agents should opt into this behavior. This is advanced behavior, and the default should be sufficient for most cases.
**Notes**
- `title` from `app/layout.js` is **replaced** by `title` in `app/about/page.js`.
- All `openGraph` fields from `app/layout.js` are **inherited** in `app/about/page.js` because `app/about/page.js` doesn't set `openGraph` metadata.
## Version History
......
......@@ -6,7 +6,6 @@ related:
description: View all the Metadata API options.
links:
- app/api-reference/file-conventions/metadata
- app/building-your-application/optimizing/metadata
---
You can customize the initial viewport of the page with the static `viewport` object or the dynamic `generateViewport` function.
......
......@@ -5,7 +5,11 @@ description: API Reference for the ImageResponse constructor.
The `ImageResponse` constructor allows you to generate dynamic images using JSX and CSS. This is useful for generating social media images such as Open Graph images, Twitter cards, and more.
The following options are available for `ImageResponse`:
## Reference
### Parameters
The following parameters are available for `ImageResponse`:
```jsx
import { ImageResponse } from 'next/og'
......@@ -32,10 +36,173 @@ new ImageResponse(
)
```
## Supported CSS Properties
> Examples are available in the [Vercel OG Playground](https://og-playground.vercel.app/).
### Supported HTML and CSS features
`ImageResponse` supports common CSS properties including flexbox and absolute positioning, custom fonts, text wrapping, centering, and nested images.
Please refer to [Satori’s documentation](https://github.com/vercel/satori#css) for a list of supported HTML and CSS features.
## Behavior
- `ImageResponse` uses [@vercel/og](https://vercel.com/docs/concepts/functions/edge-functions/og-image-generation), [Satori](https://github.com/vercel/satori), and Resvg to convert HTML and CSS into PNG.
- Only flexbox and a subset of CSS properties are supported. Advanced layouts (e.g. `display: grid`) will not work.
- Maximum bundle size of `500KB`. The bundle size includes your JSX, CSS, fonts, images, and any other assets. If you exceed the limit, consider reducing the size of any assets or fetching at runtime.
- Only `ttf`, `otf`, and `woff` font formats are supported. To maximize the font parsing speed, `ttf` or `otf` are preferred over `woff`.
## Examples
### Route Handlers
`ImageResponse` can be used in Route Handlers to generate images dynamically at request time.
```js filename="app/api/route.js"
import { ImageResponse } from 'next/og'
export async function GET() {
try {
return new ImageResponse(
(
<div
style={{
height: '100%',
width: '100%',
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
justifyContent: 'center',
backgroundColor: 'white',
padding: '40px',
}}
>
<div
style={{
fontSize: 60,
fontWeight: 'bold',
color: 'black',
textAlign: 'center',
}}
>
Welcome to My Site
</div>
<div
style={{
fontSize: 30,
color: '#666',
marginTop: '20px',
}}
>
Generated with Next.js ImageResponse
</div>
</div>
),
{
width: 1200,
height: 630,
}
)
} catch (e) {
console.log(`${e.message}`)
return new Response(`Failed to generate the image`, {
status: 500,
})
}
}
```
### File-based Metadata
You can use `ImageResponse` in a [`opengraph-image.tsx`](/docs/app/api-reference/file-conventions/metadata/opengraph-image) file to generate Open Graph images at build time or dynamically at request time.
```tsx filename="app/opengraph-image.tsx"
import { ImageResponse } from 'next/og'
// Image metadata
export const alt = 'My site'
export const size = {
width: 1200,
height: 630,
}
export const contentType = 'image/png'
// Image generation
export default async function Image() {
return new ImageResponse(
(
// ImageResponse JSX element
<div
style={{
fontSize: 128,
background: 'white',
width: '100%',
height: '100%',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
}}
>
My site
</div>
),
// ImageResponse options
{
// For convenience, we can re-use the exported opengraph-image
// size config to also set the ImageResponse's width and height.
...size,
}
)
}
```
### Custom fonts
You can use custom fonts in your `ImageResponse` by providing a `fonts` array in the options.
```tsx filename="app/opengraph-image.tsx"
import { ImageResponse } from 'next/og'
import { readFile } from 'node:fs/promises'
import { join } from 'node:path'
// Image metadata
export const alt = 'My site'
export const size = {
width: 1200,
height: 630,
}
export const contentType = 'image/png'
// Image generation
export default async function Image() {
// Font loading, process.cwd() is Next.js project directory
const interSemiBold = await readFile(
join(process.cwd(), 'assets/Inter-SemiBold.ttf')
)
return new ImageResponse(
(
// ...
),
// ImageResponse options
{
// For convenience, we can re-use the exported opengraph-image
// size config to also set the ImageResponse's width and height.
...size,
fonts: [
{
name: 'Inter',
data: interSemiBold,
style: 'normal',
weight: 400,
},
],
}
)
}
```
## Version History
| Version | Changes |
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment