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: ...@@ -7,10 +7,13 @@ related:
description: Learn more about the Metadata APIs mentioned in this page. description: Learn more about the Metadata APIs mentioned in this page.
links: links:
- app/api-reference/functions/generate-metadata - 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/api-reference/file-conventions/metadata/app-icons - app/api-reference/file-conventions/metadata/app-icons
- app/api-reference/file-conventions/metadata/opengraph-image - 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: 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 = { ...@@ -59,7 +62,7 @@ export const metadata = {
export default function Page() {} 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 ## Generated metadata
...@@ -177,6 +180,17 @@ export default async function Page({ params }) { ...@@ -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
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. 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. ...@@ -110,7 +110,7 @@ When using file based routing, you can use MDX pages like any other page.
<AppOnly> <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: Create a new MDX page within the `/app` directory:
......
...@@ -166,7 +166,7 @@ export default function RootLayout({ ...@@ -166,7 +166,7 @@ export default function RootLayout({
- The root layout replaces the `pages/_app.tsx` and `pages/_document.tsx` files. - The root layout replaces the `pages/_app.tsx` and `pages/_document.tsx` files.
- `.js`, `.jsx`, or `.tsx` extensions can be used for layout 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 ```tsx filename="app/layout.tsx" switcher
import type { Metadata } from 'next' import type { Metadata } from 'next'
...@@ -265,7 +265,7 @@ Page.getLayout = function getLayout(page) { ...@@ -265,7 +265,7 @@ Page.getLayout = function getLayout(page) {
### Step 3: Migrating `next/head` ### 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:** **Before:**
......
...@@ -145,7 +145,7 @@ export default function RootLayout({ children }) { ...@@ -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 ### Step 4: Metadata
...@@ -189,7 +189,7 @@ export default function RootLayout({ children }) { ...@@ -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 ```tsx filename="app/layout.tsx" switcher
export default function RootLayout({ export default function RootLayout({
...@@ -227,7 +227,7 @@ export default function RootLayout({ children }) { ...@@ -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 ```tsx filename="app/layout.tsx" switcher
import type { Metadata } from 'next' import type { Metadata } from 'next'
...@@ -269,7 +269,7 @@ export default function RootLayout({ children }) { ...@@ -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 ### Step 5: Styles
......
...@@ -249,11 +249,11 @@ export default function RootLayout({ children }) { ...@@ -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 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 `<head>` tag as long as you have them placed into the top level of the `app` directory. After
moving 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: into the `app` directory you can safely delete their `<link>` tags:
```tsx filename="app/layout.tsx" switcher ```tsx filename="app/layout.tsx" switcher
...@@ -293,7 +293,7 @@ export default function RootLayout({ children }) { ...@@ -293,7 +293,7 @@ export default function RootLayout({ children }) {
``` ```
6. Finally, Next.js can manage your last `<head>` tags with the 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 info into an exported
[`metadata` object](/docs/app/api-reference/functions/generate-metadata#metadata-object): [`metadata` object](/docs/app/api-reference/functions/generate-metadata#metadata-object):
...@@ -339,7 +339,7 @@ export default function RootLayout({ children }) { ...@@ -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' With the above changes, you shifted from declaring everything in your `index.html` to using Next.js'
convention-based approach built into the framework 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. to more easily improve your SEO and web shareability of your pages.
### Step 5: Create the Entrypoint Page ### Step 5: Create the Entrypoint Page
......
...@@ -108,7 +108,7 @@ While building your application, we recommend using the following features to en ...@@ -108,7 +108,7 @@ While building your application, we recommend using the following features to en
<AppOnly> <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. - **[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. - **[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) { ...@@ -208,7 +208,7 @@ export function GET(req: NextRequest) {
npx @next/codemod@latest next-og-import . 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: For example:
......
...@@ -187,7 +187,7 @@ In terms of nesting, `template.js` is rendered between a layout and its children ...@@ -187,7 +187,7 @@ In terms of nesting, `template.js` is rendered between a layout and its children
### Metadata ### 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. 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.
......
...@@ -113,7 +113,7 @@ export default function RootLayout({ children }) { ...@@ -113,7 +113,7 @@ export default function RootLayout({ children }) {
``` ```
- The root layout **must** define `<html>` and `<body>` tags. - 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. - 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. - 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: ...@@ -6,7 +6,6 @@ related:
description: View all the Metadata API options. description: View all the Metadata API options.
links: links:
- app/api-reference/file-conventions/metadata - 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. 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.
......
...@@ -6,7 +6,6 @@ related: ...@@ -6,7 +6,6 @@ related:
description: View all the Metadata API options. description: View all the Metadata API options.
links: links:
- app/api-reference/file-conventions/metadata - 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. 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. ...@@ -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 `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 ```jsx
import { ImageResponse } from 'next/og' import { ImageResponse } from 'next/og'
...@@ -32,10 +36,173 @@ new ImageResponse( ...@@ -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. 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 History
| Version | Changes | | 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