跳到內容
檔案慣例Metadata 檔案opengraph-image 和 twitter-image

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/ogImageResponse API。

app/about/opengraph-image.tsx
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
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 符合此回傳類型。

Config exports

您可以選擇性地透過從 opengraph-imagetwitter-image 路由匯出 altsizecontentType 變數來設定圖片的 metadata。

選項類型
altstring
size{ width: number; height: number }
contentTypestring - 圖片 MIME 類型

alt

opengraph-image.tsx | twitter-image.tsx
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 | twitter-image.tsx
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 | twitter-image.tsx
export const contentType = 'image/png'
 
export default function Image() {}
<head> 輸出
<meta property="og:image:type" content="image/png" />

路由區段設定

opengraph-imagetwitter-image 是特殊的路由處理器,可以使用與 Pages 和 Layouts 相同的路由區段設定選項。

範例

使用外部資料

此範例使用 params 物件和外部資料來產生圖片。

要知道:預設情況下,此產生的圖片將會是靜態最佳化的。您可以設定個別的 fetch options 或路由區段 options 來變更此行為。

app/posts/[slug]/opengraph-image.tsx
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
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