typescriptadvanced

OG Image Generation at the Edge

Generate dynamic Open Graph images using @vercel/og with custom layouts and fonts.

typescript
// app/api/og/route.tsx
import { ImageResponse } from 'next/og';

export const runtime = 'edge';

export async function GET(request: Request) {
  const { searchParams } = new URL(request.url);
  const title = searchParams.get('title') || 'Default Title';
  const description = searchParams.get('desc') || '';
  const category = searchParams.get('cat') || '';

  return new ImageResponse(
    (
      <div
        style={{
          height: '100%',
          width: '100%',
          display: 'flex',
          flexDirection: 'column',
          justifyContent: 'center',
          padding: '60px',
          background: 'linear-gradient(135deg, #0a0a0a 0%, #1a1a2e 100%)',
          color: 'white',
          fontFamily: 'system-ui',
        }}
      >
        {category && (
          <div
            style={{
              fontSize: 24,
              color: '#3B82F6',
              marginBottom: 16,
              textTransform: 'uppercase',
              letterSpacing: 2,
            }}
          >
            {category}
          </div>
        )}
        <div
          style={{
            fontSize: 64,
            fontWeight: 700,
            lineHeight: 1.2,
            marginBottom: 20,
          }}
        >
          {title}
        </div>
        {description && (
          <div style={{ fontSize: 28, color: '#9CA3AF', lineHeight: 1.4 }}>
            {description}
          </div>
        )}
        <div
          style={{
            position: 'absolute',
            bottom: 40,
            right: 60,
            fontSize: 24,
            color: '#6B7280',
          }}
        >
          snippetslab.dev
        </div>
      </div>
    ),
    {
      width: 1200,
      height: 630,
    }
  );
}

// Usage in metadata:
// openGraph: {
//   images: [`/api/og?title=${encodeURIComponent(title)}&cat=React`],
// }

Use Cases

  • social media cards
  • blog OG images
  • dynamic previews

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.