Sponsor
ntab.devntab.dev 提升效率的新标签页组件
点击查看
Menu

opengraph-image 和 twitter-image

opengraph-imagetwitter-image 文件约定允许你为路由段设置 Open Graph 和 Twitter 图像。

当用户分享你网站的链接时,这些图像会显示在社交网络和消息应用中,非常有用。

设置 Open Graph 和 Twitter 图像有两种方式:

图像文件(.jpg、.png、.gif)

通过在路由段中放置 opengraph-imagetwitter-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) 图像文件添加到任何路由段。

<head>
<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) 图像文件添加到任何路由段。

<head>
<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 文件作为其替代文本。

opengraph-image.alt.txt
About Acme
<head>
<meta property="og:image:alt" content="About Acme" />

twitter-image.alt.txt

在与 twitter-image.(jpg|jpeg|png|gif) 图像相同的路由段中添加一个相应的 twitter-image.alt.txt 文件作为其替代文本。

twitter-image.alt.txt
About Acme
<head>
<meta property="twitter:image:alt" content="About Acme" />

使用代码生成图像(.js、.ts、.tsx)

除了使用实际图像文件外,你还可以通过代码以编程方式生成图像。

通过创建一个默认导出函数的 opengraph-imagetwitter-image 路由来生成路由段的共享图像。

文件约定支持的文件类型
opengraph-image.js.ts.tsx
twitter-image.js.ts.tsx

值得注意的是

  • 默认情况下,生成的图像是静态优化的(在构建时生成并缓存),除非它们使用动态 API或未缓存的数据。
  • 你可以使用 generateImageMetadata 在同一文件中生成多个图像。
  • opengraph-image.jstwitter-image.js 是特殊的路由处理程序,默认情况下会被缓存,除非它使用动态 API动态配置选项。

生成图像最简单的方法是使用 next/og 中的 ImageResponse API。

app/about/opengraph-image.tsx
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'
 
// 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 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,
        },
      ],
    }
  )
}
<head>
<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" />

Props

默认导出函数接收以下 props:

params(可选)

一个包含从根段到 opengraph-imagetwitter-image 所在段的动态路由参数对象。

app/shop/[slug]/opengraph-image.tsx
TypeScript
export default function Image({ params }: { params: { slug: string } }) {
  // ...
}
路由URLparams
app/shop/opengraph-image.js/shopundefined
app/shop/[slug]/opengraph-image.js/shop/1{ slug: '1' }
app/shop/[tag]/[item]/opengraph-image.js/shop/1/2{ tag: '1', item: '2' }

返回值

默认导出函数应该返回 Blob | ArrayBuffer | TypedArray | DataView | ReadableStream | Response

值得注意的是ImageResponse 满足这个返回类型。

配置导出

你可以通过从 opengraph-imagetwitter-image 路由导出 altsizecontentType 变量来选择性地配置图像的元数据。

选项类型
altstring
size{ width: number; height: number }
contentTypestring - 图像 MIME 类型

alt

opengraph-image.tsx
TypeScript
export const alt = 'My images alt text'
 
export default function Image() {}
<head>
<meta property="og:image:alt" content="My images alt text" />

size

opengraph-image.tsx
TypeScript
export const size = { width: 1200, height: 630 }
 
export default function Image() {}
<head>
<meta property="og:image:width" content="1200" />
<meta property="og:image:height" content="630" />

contentType

opengraph-image.tsx
TypeScript
export const contentType = 'image/png'
 
export default function Image() {}
<head>
<meta property="og:image:type" content="image/png" />

路由段配置

opengraph-imagetwitter-image 是专门的路由处理程序,可以使用与页面和布局相同的路由段配置选项。

示例

使用外部数据

此示例使用 params 对象和外部数据生成图像。

值得注意的是: 默认情况下,这个生成的图像将被静态优化。你可以配置单个 fetch 选项或路由段选项来更改此行为。

app/posts/[slug]/opengraph-image.tsx
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: { slug: string } }) {
  const post = await fetch(`https://.../posts/${params.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 运行时在文件系统上获取本地图像,并将其作为 ArrayBuffer 传递给 <img> 元素的 src 属性。本地资源应该放置在项目根目录下,而不是示例源文件所在的位置。

app/opengraph-image.tsx
TypeScript
import { ImageResponse } from 'next/og'
import { join } from 'node:path'
import { readFile } from 'node:fs/promises'
 
export default async function Image() {
  const logoData = await readFile(join(process.cwd(), 'logo.png'))
  const logoSrc = Uint8Array.from(logoData).buffer
 
  return new ImageResponse(
    (
      <div
        style={{
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
        }}
      >
        <img src={logoSrc} height="100" />
      </div>
    )
  )
}

版本历史

版本变更
v13.3.0引入 opengraph-imagetwitter-image