동적 오픈그래프 태그 이미지를 생성할 디렉토리와 같은 위치에 opengraph-image.tsx 파일을 만들어준다.
// app/detail/opengraph-image.tsx
import { ImageResponse } from 'next/og'
// Route segment config
export const runtime = 'edge'
// 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({ params }: { params: { id: string } }) {
// Font
const interSemiBold = fetch(
new URL('./Inter-SemiBold.ttf', import.meta.url)
).then((res) => res.arrayBuffer())
const url = `http://localhost:3000/detail/${params.id}`;
const post = await fetch(url).then((res) =>
res.json()
)
return new ImageResponse(
(
// ImageResponse JSX
<div
style={{
backgroundImage: `url(${post.thumbnail})`
fontSize: 128,
background: 'white',
width: '100%',
height: '100%',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
}}
>
{post.title}
</div>
),
// ImageResponse 옵션
{
...size,
fonts: [
{
name: 'Inter',
data: await interSemiBold,
style: 'normal',
weight: 400,
},
],
}
)
}
위와 같이 작성하면 opengraph tag iamge를 동적으로 생성할 수 있다.
정적으로 opengraph image를 만들고 싶다면 마찬가지로 같은 디렉토리 위치에 opengraph-image.(jpg|jpeg|png|gif)파일을 만들어주면 된다.