PICTIFY
Next.js

Next.js
+ Pictify

Generate dynamic OG images in Next.js with API routes or edge functions.

Frameworks

About Integration

Integrate Pictify with Next.js for dynamic OG image generation. Use API routes for server-side generation, or edge functions for low-latency image creation. Perfect for blogs, e-commerce, and SaaS applications built with Next.js.

Key Capabilities

API route integration

Edge function support

ISR compatibility

App Router ready

Common Use Cases

Dynamic blog OG images

Product page social cards

User-generated content previews

Integration Guide

10 minutes

Prerequisites

  • Next.js 13+ project
  • A Pictify account with an API key
  • A template created in Pictify
1

Install the SDK

Add the Pictify SDK to your Next.js project.

Code
npm install @pictify/sdk
2

Set Up Environment Variables

Add your Pictify API key to your environment configuration.

Code
# .env.local
PICTIFY_API_KEY=your-api-key-here
PICTIFY_TEMPLATE_ID=your-og-template-id
!

Never commit .env.local to git. Add it to .gitignore.

3

Create an API Route (App Router)

Create an API route to generate OG images on demand.

Code
// app/api/og/route.ts
import { Pictify } from '@pictify/sdk';
import { NextRequest, NextResponse } from 'next/server';

const pictify = new Pictify({
  apiKey: process.env.PICTIFY_API_KEY!
});

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

  try {
    const result = await pictify.render({
      templateId: process.env.PICTIFY_TEMPLATE_ID!,
      variables: { title, description },
      format: 'png',
      width: 1200,
      height: 630
    });

    // Redirect to the CDN-hosted image
    return NextResponse.redirect(result.imageUrl);
  } catch (error) {
    return NextResponse.json({ error: 'Failed to generate image' }, { status: 500 });
  }
}
4

Add Dynamic Metadata to Pages

Use Next.js metadata API to set OG images dynamically.

Code
// app/blog/[slug]/page.tsx
import { Metadata } from 'next';

type Props = {
  params: { slug: string };
};

export async function generateMetadata({ params }: Props): Promise<Metadata> {
  const post = await getPost(params.slug);

  // Build the OG image URL with query params
  const ogImageUrl = new URL('/api/og', process.env.NEXT_PUBLIC_SITE_URL);
  ogImageUrl.searchParams.set('title', post.title);
  ogImageUrl.searchParams.set('description', post.excerpt);

  return {
    title: post.title,
    description: post.excerpt,
    openGraph: {
      title: post.title,
      description: post.excerpt,
      images: [
        {
          url: ogImageUrl.toString(),
          width: 1200,
          height: 630,
          alt: post.title,
        },
      ],
    },
    twitter: {
      card: 'summary_large_image',
      title: post.title,
      description: post.excerpt,
      images: [ogImageUrl.toString()],
    },
  };
}

export default async function BlogPost({ params }: Props) {
  const post = await getPost(params.slug);
  return <article>{/* Your post content */}</article>;
}
!

The OG image is generated on-demand when social platforms fetch the URL.

5

Pre-generate at Build Time (Optional)

For static sites, generate OG images during build for better performance.

Code
// scripts/generate-og-images.ts
import { Pictify } from '@pictify/sdk';
import { getAllPosts } from '../lib/posts';
import fs from 'fs';
import path from 'path';

const pictify = new Pictify({ apiKey: process.env.PICTIFY_API_KEY! });

async function generateOgImages() {
  const posts = await getAllPosts();

  for (const post of posts) {
    const result = await pictify.render({
      templateId: process.env.PICTIFY_TEMPLATE_ID!,
      variables: {
        title: post.title,
        author: post.author,
        date: post.date
      },
      download: true
    });

    const outputPath = path.join(
      process.cwd(),
      'public',
      'og',
      `${post.slug}.png`
    );

    fs.mkdirSync(path.dirname(outputPath), { recursive: true });
    fs.writeFileSync(outputPath, result.buffer);

    console.log(`Generated: ${outputPath}`);
  }
}

generateOgImages();
!

Add this script to your build process: "prebuild": "tsx scripts/generate-og-images.ts"

6

Edge Function for Low Latency (Optional)

Use Edge Runtime for faster cold starts globally.

Code
// app/api/og/route.ts
import { Pictify } from '@pictify/sdk';
import { NextRequest, NextResponse } from 'next/server';

// Use Edge Runtime
export const runtime = 'edge';

const pictify = new Pictify({
  apiKey: process.env.PICTIFY_API_KEY!
});

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

  const result = await pictify.render({
    templateId: process.env.PICTIFY_TEMPLATE_ID!,
    variables: { title },
  });

  // Redirect to CDN with caching headers
  return NextResponse.redirect(result.imageUrl, {
    headers: {
      'Cache-Control': 'public, max-age=86400, s-maxage=86400',
    },
  });
}
!

Edge functions run closer to users, reducing latency for global audiences.

Ready to build with Next.js?

Get your API key in seconds and start generating images programmatically.

Related Integrations