typescriptadvanced

Next.js Dynamic OG Image Generation

Generate dynamic Open Graph images at build time using next/og for social media sharing.

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

export const runtime = 'edge';

export async function GET(request: NextRequest) {
  const { searchParams } = request.nextUrl;
  const title = searchParams.get('title') || 'SnippetsLab';
  const category = searchParams.get('category') || 'Code Snippets';

  return new ImageResponse(
    (
      <div
        style={{
          height: '100%',
          width: '100%',
          display: 'flex',
          flexDirection: 'column',
          alignItems: 'center',
          justifyContent: 'center',
          backgroundColor: '#0a0a0a',
          color: 'white',
          padding: '40px',
        }}
      >
        <div
          style={{
            fontSize: 24,
            color: '#3b82f6',
            marginBottom: 16,
          }}
        >
          {category}
        </div>
        <div
          style={{
            fontSize: 48,
            fontWeight: 'bold',
            textAlign: 'center',
            maxWidth: '80%',
            lineHeight: 1.2,
          }}
        >
          {title}
        </div>
        <div
          style={{
            fontSize: 20,
            color: '#9ca3af',
            marginTop: 24,
          }}
        >
          snippetslab.dev
        </div>
      </div>
    ),
    {
      width: 1200,
      height: 630,
    }
  );
}

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

Use Cases

  • Dynamic social media preview images
  • Branded OG images for blog posts
  • Automated social card generation

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.