섬네일 이미지를 자동으로 생성하기 (with @vercel/og)
블로그에 글을 작성할 때, 섬네일(thumbnail)을 매번 직접 만드는 것은 추가적인 비용이 필요한 작업입니다. 이를 해결하기 위해 미니픽(https://mini-pick.vercel.app)을 직접 만들었지만, 제목 등을 직접 입력해야 해서, 자동화하면 어떨까 하는 needs가 생겼습니다.
`@vercel/og` 라이브러리를 도입해서 자동으로 이미지를 생성하도록 해서 이를 해결할 수 있었습니다.
※ Next.js 13 + App Router 버전 기준입니다.
공식 문서를 참고해서, app 디렉토리에 og 폴더를 만들고, route.tsx 파일을 생성하고, 아래와 같이 구현했습니다.
// app/og/route.tsx
import { ImageResponse } from 'next/server';
export const runtime = 'edge';
export async function GET(request: Request) {
try {
const { searchParams } = new URL(request.url);
const hasTitle = searchParams.has('title');
const title = hasTitle
? searchParams.get('title')?.slice(0, 100)
: 'Woongsnote';
const size = { width: 1200, height: 630 };
return new ImageResponse(
(
<div
style={{
height: '100%',
width: '100%',
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
justifyContent: 'center',
backgroundImage:
'linear-gradient(to bottom right, #00C0FF, #4218B8)',
fontSize: 64,
fontWeight: 600,
}}
>
<div style={{ color: 'white' }}>{title}</div>
</div>
),
{
...size,
},
);
} catch (error) {
return new Response(`Failed to generate the Image`, { status: 500 });
}
}
```
Next.js의 Metadata API 기준으로 해당 이미지를 Open-graph image로 사용하려면, 아래와 같이 호출하면 됩니다.
openGraph: {
images: [
{
url: `/og?title=${post.title}`,
width: 1200,
height: 630,
alt: post.title,
},
],
},
동일한 url로 섬네일로 사용하려고 했으나, 배포 환경에서 400 Error 를 만났습니다.
Next.js 의 Image를 사용하려다 보니, image에 대한 주소 설정이 안되어 있다고 생각되어 아래와 같이 config 파일에 remotepattern을 추가했습니다.
{
protocol: 'https',
hostname: '배포한 url 주소',
port: '',
pathname: '/og/**',
},
또한, 이미지를 불러오는 url도 아래와 같이 수정했습니다.
src={`${배포한 url}/og?title=${title}`}
수정 후에 재배포한 결과, 정상적으로 동작하는 것을 확인할 수 있었습니다.
아래 블로그에서 실제로 생성된 섬네일을 확인할 수 있습니다.
감사합니다. 😊