Sponsor
ChatHubChatHub Use GPT-4, Gemini, Claude 3.5 and more chatbots side-by-side
ここをクリック
Menu

opengraph-image and twitter-image

opengraph-imagetwitter-imageファイル規約を使用すると、ルートセグメントのOpen GraphとTwitter画像を設定できます。

これらは、ユーザーがサイトのリンクをソーシャルネットワークやメッセージングアプリで共有したときに表示される画像を設定するのに役立ちます。

Open GraphとTwitter画像を設定するには2つの方法があります:

画像ファイル (.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)画像ファイルを追加します。

<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)画像と同じルートセグメントに、alt テキストとして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)画像と同じルートセグメントに、alt テキストとしてtwitter-image.alt.txtファイルを追加します。

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

コードを使用して画像を生成する (.js, .ts, .tsx)

実際の画像ファイルを使用する以外に、コードを使ってプログラムで画像を生成することもできます。

関数をデフォルトエクスポートするopengraph-imageまたはtwitter-imageルートを作成することで、ルートセグメントの共有画像を生成できます。

ファイル規約サポートするファイル形式
opengraph-image.js, .ts, .tsx
twitter-image.js, .ts, .tsx

補足:

  • デフォルトでは、生成された画像は静的に最適化され(ビルド時に生成されキャッシュされる)、Dynamic APIやキャッシュされないデータを使用しない限りキャッシュされます。
  • generateImageMetadataを使用して、同じファイルで複数の画像を生成できます。
  • opengraph-image.jstwitter-image.jsは、Dynamic APIdynamic configオプションを使用しない限り、デフォルトでキャッシュされる特殊なRoute Handlersです。

画像を生成する最も簡単な方法は、next/ogImageResponse 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-imageまたはtwitter-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-imageまたはtwitter-imageルートからaltsizecontentType変数をエクスポートすることで、画像のメタデータを設定できます。

オプション
altstring
size{ width: number; height: number }
contentTypestring - image MIME type

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は特殊なRoute Handlersであり、ページやレイアウトと同じルートセグメント設定オプションを使用できます。

外部データの使用

この例では、paramsオブジェクトと外部データを使用して画像を生成します。

補足: デフォルトでは、この生成された画像は静的に最適化されます。個々のfetchoptionsやルートセグメントのオプションを設定して、この動作を変更できます。

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ランタイムを使用してファイルシステム上のローカル画像を取得し、<img>要素のsrc属性にArrayBufferとして渡します。ローカルアセットは、例のソースファイルの場所ではなく、プロジェクトのルートを基準に配置する必要があります。

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