コンテンツにスキップ

ImageResponse

ImageResponseコンストラクタを使用すると、JSXとCSSを使用して動的に画像を生成できます。これは、Open Graph画像、Twitterカードなどのソーシャルメディア画像を生成するのに役立ちます。

リファレンス

Parameters

ImageResponseで利用可能なパラメータは次のとおりです。

import { ImageResponse } from 'next/og'
 
new ImageResponse(
  element: ReactElement,
  options: {
    width?: number = 1200
    height?: number = 630
    emoji?: 'twemoji' | 'blobmoji' | 'noto' | 'openmoji' = 'twemoji',
    fonts?: {
      name: string,
      data: ArrayBuffer,
      weight: number,
      style: 'normal' | 'italic'
    }[]
    debug?: boolean = false
 
    // Options that will be passed to the HTTP response
    status?: number = 200
    statusText?: string
    headers?: Record<string, string>
  },
)

例はVercel OG Playgroundで利用できます。

サポートされているHTMLおよびCSS機能

ImageResponseは、flexboxと絶対配置、カスタムフォント、テキスト折り返し、センタリング、ネストされた画像を含む一般的なCSSプロパティをサポートしています。

サポートされているHTMLおよびCSS機能のリストについては、Satoriのドキュメントを参照してください。

動作

  • ImageResponseは、HTMLとCSSをPNGに変換するために、@vercel/ogSatori、およびResvgを使用します。
  • flexboxとCSSプロパティのサブセットのみがサポートされています。高度なレイアウト(例:display: grid)は機能しません。
  • 最大バンドルサイズは500KBです。バンドルサイズには、JSX、CSS、フォント、画像、およびその他のアセットが含まれます。制限を超えた場合は、アセットのサイズを削減するか、実行時に取得することを検討してください。
  • サポートされているフォント形式はttfotfwoffのみです。フォントの解析速度を最大化するために、woffよりもttfまたはotfが推奨されます。

ルートハンドラー

ImageResponseは、Route Handlersで使用して、リクエスト時に動的に画像を生成できます。

app/api/route.js
import { ImageResponse } from 'next/og'
 
export async function GET() {
  try {
    return new ImageResponse(
      (
        <div
          style={{
            height: '100%',
            width: '100%',
            display: 'flex',
            flexDirection: 'column',
            alignItems: 'center',
            justifyContent: 'center',
            backgroundColor: 'white',
            padding: '40px',
          }}
        >
          <div
            style={{
              fontSize: 60,
              fontWeight: 'bold',
              color: 'black',
              textAlign: 'center',
            }}
          >
            Welcome to My Site
          </div>
          <div
            style={{
              fontSize: 30,
              color: '#666',
              marginTop: '20px',
            }}
          >
            Generated with Next.js ImageResponse
          </div>
        </div>
      ),
      {
        width: 1200,
        height: 630,
      }
    )
  } catch (e) {
    console.log(`${e.message}`)
    return new Response(`Failed to generate the image`, {
      status: 500,
    })
  }
}

ファイルベースのメタデータ

opengraph-image.tsxファイルでImageResponseを使用すると、ビルド時またはリクエスト時に動的にOpen Graph画像を生成できます。

app/opengraph-image.tsx
import { ImageResponse } from 'next/og'
 
// Image metadata
export const alt = 'My site'
export const size = {
  width: 1200,
  height: 630,
}
 
export const contentType = 'image/png'
 
// 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',
        }}
      >
        My site
      </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配列を提供することにより、ImageResponseでカスタムフォントを使用できます。

app/opengraph-image.tsx
import { ImageResponse } from 'next/og'
import { readFile } from 'node:fs/promises'
import { join } from 'node:path'
 
// Image metadata
export const alt = 'My site'
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 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,
        },
      ],
    }
  )
}

バージョン履歴

バージョン変更履歴
v14.0.0ImageResponsenext/serverからnext/ogに移動しました
v13.3.0ImageResponsenext/serverからインポートできます。
v13.0.0ImageResponse@vercel/ogパッケージを通じて導入されました。