opengraph-image and twitter-image
opengraph-image および twitter-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)画像ファイルを任意のルートセグメントに追加します。
<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 property="twitter:image:alt" content="About Acme" />コードで画像を生成する(.js、.ts、.tsx)
リテラル画像ファイルに加えて、コードを使用してプログラムで画像を生成することもできます。
opengraph-imageまたはtwitter-imageルートを作成し、関数をデフォルトエクスポートすることで、ルートセグメントの共有画像を生成します。
| ファイル規約 | サポートされているファイルタイプ |
|---|---|
opengraph-image | .js、.ts、.tsx |
twitter-image | .js、.ts、.tsx |
知っておくと良いこと:
画像を生成する最も簡単な方法は、next/ogからImageResponse APIを使用することです。
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,
},
],
}
)
}<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
デフォルトエクスポート関数は、次のプロップを受け取ります。
params (オプション)
opengraph-imageまたはtwitter-imageが共存するセグメントからルートセグメントまでの動的ルートパラメーターオブジェクトを含むオブジェクトに解決されるPromise。
豆知識:
generateImageMetadataを使用する場合、関数はgenerateImageMetadataが返すアイテムの1つからのid値に解決されるPromiseであるidプロップも受け取ります。
export default async function Image({
params,
}: {
params: Promise<{ slug: string }>
}) {
const { slug } = await params
// ...
}| Route | 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' }> |
戻り値
デフォルトエクスポート関数は、Blob | ArrayBuffer | TypedArray | DataView | ReadableStream | Responseを返す必要があります。
豆知識:
ImageResponseはこの戻り値の型を満たします。
設定エクスポート
オプションで、opengraph-imageまたはtwitter-imageルートからalt、size、contentType変数をエクスポートすることで、画像のメタデータを設定できます。
| オプション | タイプ |
|---|---|
alt | string |
size | { width: number; height: number } |
contentType | string - 画像のMIMEタイプ |
alt
export const alt = 'My images alt text'
export default function Image() {}<meta property="og:image:alt" content="My images alt text" />size
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
export const contentType = 'image/png'
export default function Image() {}<meta property="og:image:type" content="image/png" />ルートセグメント設定
opengraph-imageおよびtwitter-imageは、PagesやLayoutsと同じルートセグメント設定オプションを使用できる、特殊なルートハンドラーです。
例
外部データの使用
この例では、paramsオブジェクトと外部データを使用して画像を生成します。
豆知識:デフォルトでは、この生成された画像は静的に最適化されます。この動作を変更するには、個々の
fetchoptionsまたはルートセグメントのオプションを設定できます。
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,
}
)
}ローカルアセットを使用したNode.jsランタイムの使用
これらの例では、Node.jsランタイムを使用してファイルシステムからローカル画像をフェッチし、それを<img>のsrc属性に、base64文字列またはArrayBufferとして渡します。ローカルアセットは、例のソースファイルではなく、プロジェクトのルート相対で配置します。
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'), 'base64')
const logoSrc = `data:image/png;base64,${logoData}`
return new ImageResponse(
(
<div
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
}}
>
<img src={logoSrc} height="100" />
</div>
)
)
}<img>要素のsrc属性にArrayBufferを渡すことは、HTML仕様の一部ではありません。next/ogで使用されるレンダリングエンジンはそれをサポートしますが、TypeScriptの定義は仕様に従っているため、この機能を使用するには、@ts-expect-errorディレクティブなどが必要です。
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',
}}
>
{/* @ts-expect-error Satori accepts ArrayBuffer/typed arrays for <img src> at runtime */}
<img src={logoSrc} height="100" />
</div>
)
)
}バージョン履歴
| バージョン | 変更履歴 |
|---|---|
v16.0.0 | paramsは、オブジェクトに解決されるPromiseになりました。 |
v13.3.0 | opengraph-imageおよびtwitter-imageが導入されました。 |
役に立ちましたか?