Dynamic OG Image Generation
Generate Open Graph images on-the-fly using Next.js ImageResponse with custom fonts and dynamic content.
import { ImageResponse } from 'next/og';
import { NextRequest } from 'next/server';
export const runtime = 'edge';
export async function GET(request: NextRequest) {
const { searchParams } = new URL(request.url);
const title = searchParams.get('title') ?? 'SnippetsLab';
const description = searchParams.get('desc') ?? 'Code snippets for developers';
return new ImageResponse(
(
<div
style={{
height: '100%',
width: '100%',
display: 'flex',
flexDirection: 'column',
justifyContent: 'center',
padding: '60px 80px',
backgroundColor: '#0a0a0a',
color: '#fff',
}}
>
<div style={{ fontSize: 24, color: '#3b82f6', marginBottom: 16 }}>
SnippetsLab
</div>
<div
style={{
fontSize: 56,
fontWeight: 700,
lineHeight: 1.2,
marginBottom: 20,
}}
>
{title}
</div>
<div style={{ fontSize: 24, color: '#9ca3af' }}>
{description}
</div>
</div>
),
{
width: 1200,
height: 630,
}
);
}
// Usage: /api/og?title=My+Snippet&desc=A+useful+code+snippetUse Cases
- Social media sharing
- Blog post previews
- Dynamic link cards
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
Reusable Metadata Factory
Factory function to generate consistent SEO metadata across all pages with Open Graph and canonical URLs.
Type-Safe API Route Handler
Next.js App Router route handler with input validation, typed responses, and proper error handling.
Authentication Middleware Guard
Next.js middleware that checks auth tokens on protected routes and redirects unauthenticated users to login.
Server Action with Form Validation
Next.js Server Action handling form submissions with validation, error messages, and redirect on success.