Performance: Dynamic OG images
Dynamic OG images affect the initial page load speed and server response time because the image is generated on demand when the page is shared.
import { cache } from 'react'; const generateCachedImage = cache(async (params) => { return await generateImage(params); }); export async function GET() { const image = await generateCachedImage({ title: 'Dynamic OG Image', style: 'complex', }); return new Response(image, { headers: { 'Content-Type': 'image/png' } }); }
export async function GET() { const image = await generateImage({ title: 'Dynamic OG Image', style: 'complex', }); return new Response(image, { headers: { 'Content-Type': 'image/png' } }); }
| Pattern | Server Processing | Network Transfer | Cache Usage | Verdict |
|---|---|---|---|---|
| Generate on every request | High (300-500ms) | Medium (image size) | None | [X] Bad |
| Generate once and cache | Low (<50ms after cache) | Medium (image size) | Effective caching | [OK] Good |
ImageResponse from 'next/server' to build dynamic OG images.createImage, DynamicImage, or generateImage do not exist or are incorrect for this purpose.?title=Hello?
import { ImageResponse } from 'next/server';
export const runtime = 'edge';
export async function GET(request) {
const { searchParams } = new URL(request.url);
const title = searchParams.get('title') || 'Default';
return new ImageResponse(
(
<div style={{
backgroundColor: 'white',
width: '100%',
height: '100%',
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
fontSize: 48,
color: 'black'
}}>
{title}
</div>
),
{ width: 1200, height: 630 }
);
}import { ImageResponse } from 'next/server';
export async function GET(request) {
const { searchParams } = new URL(request.url);
const name = searchParams.get('name');
return new ImageResponse(
(
<div style={{ fontSize: 40 }}>
Welcome, {name.toUpperCase()}!
</div>
),
{ width: 800, height: 400 }
);
}name.toUpperCase() without checking if name is null. If the URL has no 'name' parameter, name is null, causing a runtime error.const score = searchParams.get('score') || 'N/A';
const displayScore = score === 0 ? 'N/A' : score;
B:
const score = Number(searchParams.get('score'));
const displayScore = score ?? 'N/A';
C:
const score = Number(searchParams.get('score'));
const displayScore = score > 0 ? score : 'N/A';
D:
const score = searchParams.get('score');
const displayScore = score === null || score === 0 ? 'N/A' : score;Pass the test and this pattern moves unknown