opengraph-image 和 twitter-image
Open Graph Image 和 Twitter Image 文件约定的 API 参考。
opengraph-image 和 twitter-image 文件约定允许你为路由段设置 Open Graph 和 Twitter 图片。
当用户分享指向你网站的链接时,它们可用于设置显示在社交网络和即时通讯应用中的图片。
有两种方式设置 Open Graph 和 Twitter 图片:
与元数据导出之间的优先级
以下规则同时适用于静态图片文件和生成的图片,遵循元数据排序:
- 页面元数据:页面从其
metadata对象或generateMetadata函数中显式设置的openGraph.images或twitter.images会覆盖对应的opengraph-image或twitter-image文件。这包括同一段中的文件以及从父段继承的图片。 - 布局元数据:与页面同目录的图片文件可以替换同一段或父段中布局所配置的图片。这适用于页面省略对应
images属性的情况。
例如,如果 app/blog/page.tsx 将 openGraph.images 设置为 ['/custom-og.png'],那么即使 app/blog/opengraph-image.png 存在,页面也会使用 /custom-og.png。
图片文件(.jpg、.png、.gif)
通过在路由段中放置 opengraph-image 或 twitter-image 图片文件,即可使用图片文件设置该路由段的共享图片。
Next.js 会解析该文件,并自动向应用的 <head> 元素添加适当的标签。
| 文件约定 | 支持的文件类型 |
|---|---|
opengraph-image |
.jpg, .jpeg, .png, .gif |
twitter-image |
.jpg, .jpeg, .png, .gif |
opengraph-image.alt |
.txt |
twitter-image.alt |
.txt |
须知:
twitter-image文件大小不得超过 5MB,opengraph-image文件大小不得超过 8MB。如果图片文件大小超过这些限制,构建将失败。
opengraph-image
将 opengraph-image.(jpg|jpeg|png|gif) 图片文件添加到任意路由段。
<meta property="og:image" content="<generated>" />
<meta property="og:image:type" content="<generated>" />
<meta property="og:image:width" content="<generated>" />
<meta property="og:image:height" content="<generated>" />
twitter-image
将 twitter-image.(jpg|jpeg|png|gif) 图片文件添加到任意路由段。
<meta name="twitter:image" content="<generated>" />
<meta name="twitter:image:type" content="<generated>" />
<meta name="twitter:image:width" content="<generated>" />
<meta name="twitter:image:height" content="<generated>" />
opengraph-image.alt.txt
在与 opengraph-image.(jpg|jpeg|png|gif) 图片相同的路由段中添加一个配套的 opengraph-image.alt.txt 文件,用作其替代文本。
About Acme
<meta property="og:image:alt" content="About Acme" />
twitter-image.alt.txt
在与 twitter-image.(jpg|jpeg|png|gif) 图片相同的路由段中添加一个配套的 twitter-image.alt.txt 文件,用作其替代文本。
About Acme
<meta name="twitter:image:alt" content="About Acme" />
使用代码生成图片(.js、.ts、.tsx)
除了使用字面图像文件之外,你还可以通过代码以编程方式生成图像。
通过创建一个默认导出函数的 opengraph-image 或 twitter-image 路由,即可生成路由段的共享图像。
| 文件约定 | 支持的文件类型 |
|---|---|
opengraph-image |
.js, .ts, .tsx |
twitter-image |
.js, .ts, .tsx |
须知:
- 默认情况下,生成的图像会进行静态优化(在构建时生成并缓存),除非它们使用了请求时 API 或未缓存的数据。
- 你可以使用
generateImageMetadata在同一个文件中生成多个图像。opengraph-image.js和twitter-image.js是特殊的路由处理器,默认情况下会被缓存,除非它使用了请求时 API 或动态配置选项。
生成图像最简单的方法是使用 next/og 中的 ImageResponse API。
TypeScript
import { ImageResponse } from 'next/og'
import { readFile } from 'node:fs/promises'
import { join } from 'node:path'
// Image metadata
export const alt = 'About Acme'
export const size = {
width: 1200,
height: 630,
}
export const contentType = 'image/png'
const interSemiBold = await readFile(
join(process.cwd(), 'assets/Inter-SemiBold.ttf')
)
// 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',
}}
>
About Acme
</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,
fonts: [
{
name: 'Inter',
data: interSemiBold,
style: 'normal',
weight: 400,
},
],
}
)
}
JavaScript
import { ImageResponse } from 'next/og'
import { readFile } from 'node:fs/promises'
import { join } from 'node:path'
// Image metadata
export const alt = 'About Acme'
export const size = {
width: 1200,
height: 630,
}
export const contentType = 'image/png'
const interSemiBold = await readFile(
join(process.cwd(), 'assets/Inter-SemiBold.ttf')
)
// 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',
}}
>
About Acme
</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,
fonts: [
{
name: 'Inter',
data: interSemiBold,
style: 'normal',
weight: 400,
},
],
}
)
}
<meta property="og:image" content="<generated>" />
<meta property="og:image:alt" content="About Acme" />
<meta property="og:image:type" content="image/png" />
<meta property="og:image:width" content="1200" />
<meta property="og:image:height" content="630" />
属性
默认导出函数接收以下属性:
params(可选)
一个 Promise,解析为一个对象,其中包含从根段一直到 opengraph-image 或 twitter-image 所在段的动态路由参数对象。
须知:
如果你使用
generateImageMetadata,该函数还会接收一个id属性,它是一个 Promise,解析为generateImageMetadata返回的其中一项中的id值。
TypeScript
export default async function Image({
params,
}: {
params: Promise<{ slug: string }>
}) {
const { slug } = await params
// ...
}
JavaScript
export default async function Image({ params }) {
const { slug } = await params
// ...
}
| 路由 | URL | params |
|---|---|---|
app/shop/opengraph-image.js |
/shop |
undefined |
app/shop/[slug]/opengraph-image.js |
/shop/1 |
Promise<{ slug: '1' }> |
app/shop/[tag]/[item]/opengraph-image.js |
/shop/1/2 |
Promise<{ tag: '1', item: '2' }> |
返回值
默认导出函数应返回一个 Response。
须知:
ImageResponse满足此返回类型。
配置导出
你可以选择通过从 opengraph-image 或 twitter-image 路由中导出 alt、size 和 contentType 变量来配置图像元数据。
| 选项 | 类型 |
|---|---|
alt |
string |
size |
{ width: number; height: number } |
contentType |
string - 图像 MIME 类型 |
alt
TypeScript
export const alt = 'My images alt text'
export default function Image() {}
JavaScript
export const alt = 'My images alt text'
export default function Image() {}
<meta property="og:image:alt" content="My images alt text" />
size
TypeScript
export const size = { width: 1200, height: 630 }
export default function Image() {}
JavaScript
export const size = { width: 1200, height: 630 }
export default function Image() {}
<meta property="og:image:width" content="1200" />
<meta property="og:image:height" content="630" />
contentType
TypeScript
export const contentType = 'image/png'
export default function Image() {}
JavaScript
export const contentType = 'image/png'
export default function Image() {}
<meta property="og:image:type" content="image/png" />
路由段配置
opengraph-image 和 twitter-image 是特殊的路由处理器,它们可以使用与页面和布局相同的路由段配置选项。
示例
使用外部数据
此示例使用 params 对象和外部数据来生成图像。
须知:
TypeScript
import { ImageResponse } from 'next/og'
export const alt = 'About Acme'
export const size = {
width: 1200,
height: 630,
}
export const contentType = 'image/png'
export default async function Image({
params,
}: {
params: Promise<{ slug: string }>
}) {
const { slug } = await params
const post = await fetch(`https://.../posts/${slug}`).then((res) =>
res.json()
)
return new ImageResponse(
(
<div
style={{
fontSize: 48,
background: 'white',
width: '100%',
height: '100%',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
}}
>
{post.title}
</div>
),
{
...size,
}
)
}
JavaScript
import { ImageResponse } from 'next/og'
export const alt = 'About Acme'
export const size = {
width: 1200,
height: 630,
}
export const contentType = 'image/png'
export default async function Image({ params }) {
const { slug } = await params
const post = await fetch(`https://.../posts/${slug}`).then((res) =>
res.json()
)
return new ImageResponse(
(
<div
style={{
fontSize: 48,
background: 'white',
width: '100%',
height: '100%',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
}}
>
{post.title}
</div>
),
{
...size,
}
)
}
结合本地资源使用 Node.js 运行时
这些示例使用 Node.js 运行时从文件系统获取本地图像,并以 base64 字符串或 ArrayBuffer 的形式将其传递给 <img> 的 src 属性。请将本地资源放置在相对于项目根目录的位置,而不是示例源文件所在位置。
该资源不依赖请求数据,因此请在模块作用域中只读取一次。参见可预测的值。
TypeScript
import { ImageResponse } from 'next/og'
import { join } from 'node:path'
import { readFile } from 'node:fs/promises'
const logoData = await readFile(join(process.cwd(), 'logo.png'), 'base64')
const logoSrc = `data:image/png;base64,${logoData}`
export default async function Image() {
return new ImageResponse(
(
<div
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
}}
>
<img src={logoSrc} height="100" />
</div>
)
)
}
JavaScript
import { ImageResponse } from 'next/og'
import { join } from 'node:path'
import { readFile } from 'node:fs/promises'
const logoData = await readFile(join(process.cwd(), 'logo.png'), 'base64')
const logoSrc = `data:image/png;base64,${logoData}`
export default async function Image() {
return new ImageResponse(
(
<div
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
}}
>
<img src={logoSrc} height="100" />
</div>
)
)
}
将 ArrayBuffer 传递给 <img> 元素的 src 属性并不属于 HTML 规范的一部分。next/og 使用的渲染引擎支持它,但由于 TypeScript 定义遵循该规范,你需要使用 @ts-expect-error 指令或类似方式才能使用此功能。
TypeScript
import { ImageResponse } from 'next/og'
import { join } from 'node:path'
import { readFile } from 'node:fs/promises'
const logoData = await readFile(join(process.cwd(), 'logo.png'))
const logoSrc = Uint8Array.from(logoData).buffer
export default async function Image() {
return new ImageResponse(
(
<div
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
}}
>
{/* @ts-expect-error Satori accepts ArrayBuffer/typed arrays for <img src> at runtime */}
<img src={logoSrc} height="100" />
</div>
)
)
}
JavaScript
import { ImageResponse } from 'next/og'
import { join } from 'node:path'
import { readFile } from 'node:fs/promises'
const logoData = await readFile(join(process.cwd(), 'logo.png'))
const logoSrc = Uint8Array.from(logoData).buffer
export default async function Image() {
return new ImageResponse(
(
<div
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
}}
>
<img src={logoSrc} height="100" />
</div>
)
)
}
故障排除
基于文件的图片未被使用
如果页面使用了与同目录下的 opengraph-image 或 twitter-image 文件不同的图片:
- 检查页面渲染出的
og:image或twitter:imagemeta 标签,以找到所选图片的 URL。即使页面的元数据指向别处,基于文件的图片路由仍可以提供图片。 - 检查页面的元数据导出中是否存在
openGraph.images或twitter.images,包括从共享对象复制过来的属性。 - 要使用同目录下的文件,请完全省略相应的
images属性。
须知:
将
images设置为[]、null或undefined仍会覆盖基于文件的图片。对于 Twitter,只有[]还会抑制回退到已解析的 Open Graph 图片。
继承的图片消失
当子路由定义了 openGraph 或 twitter 但没有 images,且没有同目录下的图片文件时,它可能会丢失继承的图片。有关如何保留继承字段,请参阅元数据合并。
版本历史
| 版本 | 变更 |
|---|---|
v16.0.0 |
params 现在是一个解析为对象的 Promise |
v13.3.0 |
引入了 opengraph-image 和 twitter-image。 |