Generate OG Images in Next.js Without a Headless Browser

Creating beautiful, dynamic Open Graph images for your content has never been easier—or faster. In this guide, I'll show you how to generate OG images in your Next.js app without relying on heavy headless browsers like Puppeteer or Playwright, and without the complexity of edge runtime limitations.

Why the Old Way Doesn't Work

For years, developers have turned to @vercel/og or headless browsers like Puppeteer to generate dynamic OG images. But both approaches come with significant drawbacks that slow down your development workflow and hurt performance.

Why Not next/og?

❌ Limitation next/og has several problems:
  • Edge Runtime Required: You must use Vercel's edge runtime, which has its own quirks and limitations
  • JSX-to-Image Rendering: Converting JSX to an image is complex and error-prone
  • Limited CSS Support: Many CSS features don't work as expected
  • Cold Starts: Cold function starts add 500ms-1s to your render time
  • Provider Lock-in: Tightly coupled to Vercel's infrastructure

Why Not Puppeteer?

❌ Overhead Puppeteer is problematic for OG generation:
  • 150MB+ Dependencies: Chromium bloats your bundle size significantly
  • Slow Performance: 2-3 seconds per image is common, even on fast machines
  • Full Browser Required: You need a complete browser environment
  • Resource Heavy: Each request spawns a new browser instance
  • Difficult to Cache: Hard to implement effective caching strategies

The Better Approach: Imago API

✅ Solution Why Imago API is the superior choice:
  • External HTTP Call: Simple fetch request, no complex setup
  • Cached Results: Your images are cached at the edge for instant delivery
  • Sub-200ms Latency: Fast response times, no cold starts
  • Works Anywhere: Works on Vercel, Netlify, self-hosted, or local development
  • Beautiful Templates: Modern, professional templates out of the box
  • No Heavy Dependencies: Just a simple API call, zero extra code

With Imago API, you get fast, reliable OG image generation with no infrastructure to maintain. Let me show you how to implement it in your Next.js app.

Step-by-Step Implementation

1 Get Your API Key

First, visit imagoapi.com and sign up for a free account. You'll get your API key immediately — no credit card required.

2 Create the API Route

Create a new file at app/api/og/route.ts (for App Router) or pages/api/og.ts (for Pages Router):

import { NextRequest, NextResponse } from 'next/server';

// App Router
export async function GET(req: NextRequest) {
  const title = req.nextUrl.searchParams.get('title') ?? 'My Page';
  const description = req.nextUrl.searchParams.get('description') ?? '';
  
  const url = new URL('https://imagoapi.com/api/og/generate');
  url.searchParams.set('title', title);
  url.searchParams.set('description', description);
  url.searchParams.set('template', 'modern');
  url.searchParams.set('api_key', process.env.IMAGO_API_KEY!);
  
  const res = await fetch(url.toString());
  const arrayBuffer = await res.arrayBuffer();
  
  return new NextResponse(arrayBuffer, {
    headers: {
      // 'Content-Type': 'image/png',
      'Cache-Control': 'public, max-age=86400',
    },
  });
}

This route handler constructs a request to Imago API, passes your parameters, and returns the generated image directly to the client with proper caching headers.

3 Add the Meta Tag to Your Layout

Now, update your page's metadata to use the OG image endpoint:

import { NextResponse } from 'next/server';

export async function generateMetadata({ params }) {
  const post = await getPost(params.slug);
  return {
    openGraph: {
      images: [{
        url: `/api/og?title=${encodeURIComponent(post.title)}&description=${encodeURIComponent(post.excerpt)}`,
        width: 1200,
        height: 630,
      }],
    },
  };
}

Now whenever someone shares your page on social media, the generated OG image will appear automatically.

4 Pages Router Support

For Pages Router users, the implementation is nearly identical. Create pages/api/og.ts with the same logic:

import { NextApiRequest, NextApiResponse } from 'next';

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  const { title, description } = req.query;
  
  const url = new URL('https://imagoapi.com/api/og/generate');
  url.searchParams.set('title', String(title ?? 'My Page'));
  url.searchParams.set('description', String(description ?? ''));
  url.searchParams.set('template', 'modern');
  url.searchParams.set('api_key', process.env.IMAGO_API_KEY!);
  
  const imagoRes = await fetch(url.toString());
  const buffer = await imagoRes.arrayBuffer();
  
  res.setHeader('Content-Type', 'image/png');
  res.setHeader('Cache-Control', 'public, max-age=86400');
  res.status(200).send(Buffer.from(buffer));
}
5 Set Your Environment Variable

Finally, add your API key to your environment:

IMAGO_API_KEY=your_api_key_here

Don't forget to add this to your production environment (Vercel, Netlify, etc.) as well.

Alternative: Direct URL Pattern

If you prefer not to use a proxy route, you can use Imago API directly as your og:image URL:

https://imagoapi.com/api/og/generate?title=Your+Title&description=Your+description&template=modern&api_key=your_api_key
⚠️ Note Security consideration

Using the direct URL pattern exposes your API key in the URL. For production apps, I recommend using the proxy approach (Steps 2-5) to keep your API key secure.

Performance Comparison

Feature next/og Puppeteer Imago API
Setup Complexity Medium High Easy
Latency 300-800ms 2000-3000ms <200ms
Memory Usage Medium High None
Works on Edge Yes No Yes
Dependencies Small 150MB+ None
Caching Manual Manual Automatic

Why Imago API?

After testing multiple approaches for generating OG images, Imago API stands out as the clear winner:

Ready to Generate Better OG Images?

Join thousands of developers using Imago API to create stunning, dynamic OG images for their content.

Get Your Free API Key

FAQ

Do I need to host images myself?

No! Imago API handles image generation and hosting. You just make an API call and get back a PNG image.

Can I use custom fonts?

Yes! Imago API supports custom fonts. Check out our documentation for more details on font customization.

Is there a free tier?

Absolutely! Yes — Imago API is completely free. Unlimited image generation, no credit card required.

Conclusion

Generating OG images in Next.js doesn't have to be complicated. With Imago API, you get fast, reliable image generation with zero infrastructure overhead. Follow the steps above, and you'll have beautiful OG images for all your content in minutes.

Got questions? Reach out to our team or check out our documentation for more examples.