Skip to content

Node.js Examples

Integration examples for Node.js applications.

Installation

bash
npm install node-fetch  # If using CommonJS
# or use native fetch in Node 18+

Basic Example

javascript
import fs from 'fs';

async function generateOGImage(title, subtitle) {
  const response = await fetch('https://ogimageapi.io/api/generate', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'X-API-Key': process.env.OG_IMAGE_API_KEY
    },
    body: JSON.stringify({
      title,
      subtitle,
      theme: 'dark'
    })
  });

  if (!response.ok) {
    const error = await response.json();
    throw new Error(error.message);
  }

  const buffer = await response.arrayBuffer();
  return Buffer.from(buffer);
}

// Usage
const imageBuffer = await generateOGImage(
  'My Blog Post',
  'A fascinating article about something'
);
fs.writeFileSync('og-image.png', imageBuffer);
javascript
// og-image-client.js
class OGImageClient {
  constructor(apiKey) {
    this.apiKey = apiKey;
    this.baseUrl = 'https://ogimageapi.io';
  }

  async generate(options) {
    const response = await fetch(`${this.baseUrl}/api/generate`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'X-API-Key': this.apiKey
      },
      body: JSON.stringify({
        title: options.title,
        subtitle: options.subtitle || '',
        author_name: options.authorName || '',
        author_avatar_url: options.authorAvatar || '',
        theme: options.theme || 'dark',
        template: options.template || 'default'
      })
    });

    if (!response.ok) {
      const error = await response.json();
      throw new Error(`OG Image Error: ${error.message}`);
    }

    return Buffer.from(await response.arrayBuffer());
  }

  async getUsage() {
    const response = await fetch(`${this.baseUrl}/api/user/usage`, {
      headers: { 'X-API-Key': this.apiKey }
    });

    if (!response.ok) {
      const error = await response.json();
      throw new Error(`Usage Error: ${error.message}`);
    }

    return response.json();
  }
}

export default OGImageClient;

Usage:

javascript
import OGImageClient from './og-image-client.js';
import fs from 'fs';

const client = new OGImageClient(process.env.OG_IMAGE_API_KEY);

// Generate image
const buffer = await client.generate({
  title: 'Getting Started with Node.js',
  subtitle: 'A beginner\'s guide',
  authorName: 'Dev Team',
  theme: 'dark',
  template: 'vibrant'
});

fs.writeFileSync('output.png', buffer);

// Check usage
const usage = await client.getUsage();
console.log(`Used ${usage.used} of ${usage.quota} images`);

Express.js Endpoint

Create a proxy endpoint:

javascript
import express from 'express';

const app = express();
app.use(express.json());

app.get('/api/og', async (req, res) => {
  const { title, subtitle } = req.query;

  if (!title) {
    return res.status(400).json({ error: 'Title is required' });
  }

  try {
    const response = await fetch('https://ogimageapi.io/api/generate', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'X-API-Key': process.env.OG_IMAGE_API_KEY
      },
      body: JSON.stringify({ title, subtitle, theme: 'dark' })
    });

    if (!response.ok) {
      const error = await response.json();
      return res.status(response.status).json(error);
    }

    const buffer = await response.arrayBuffer();
    
    res.setHeader('Content-Type', 'image/png');
    res.setHeader('Cache-Control', 'public, max-age=86400');
    res.send(Buffer.from(buffer));
  } catch (error) {
    res.status(500).json({ error: 'Failed to generate image' });
  }
});

app.listen(3000);

Next.js Integration

javascript
// pages/api/og.js (Pages Router)
export default async function handler(req, res) {
  const { title, subtitle } = req.query;

  const response = await fetch('https://ogimageapi.io/api/generate', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'X-API-Key': process.env.OG_IMAGE_API_KEY
    },
    body: JSON.stringify({
      title: title || 'My Website',
      subtitle: subtitle || '',
      theme: 'dark'
    })
  });

  const buffer = await response.arrayBuffer();

  res.setHeader('Content-Type', 'image/png');
  res.setHeader('Cache-Control', 'public, max-age=86400');
  res.send(Buffer.from(buffer));
}

Build Script for Static Sites

javascript
// scripts/generate-og-images.js
import fs from 'fs';
import path from 'path';

const API_KEY = process.env.OG_IMAGE_API_KEY;
const OUTPUT_DIR = './public/og';

// Your blog posts data
const posts = [
  { slug: 'hello-world', title: 'Hello World', subtitle: 'My first post' },
  { slug: 'getting-started', title: 'Getting Started', subtitle: 'A guide' },
  // ... more posts
];

async function generateImages() {
  // Ensure output directory exists
  fs.mkdirSync(OUTPUT_DIR, { recursive: true });

  for (const post of posts) {
    console.log(`Generating: ${post.slug}`);

    const response = await fetch('https://ogimageapi.io/api/generate', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'X-API-Key': API_KEY
      },
      body: JSON.stringify({
        title: post.title,
        subtitle: post.subtitle,
        theme: 'dark'
      })
    });

    if (!response.ok) {
      console.error(`Failed: ${post.slug}`);
      continue;
    }

    const buffer = Buffer.from(await response.arrayBuffer());
    fs.writeFileSync(path.join(OUTPUT_DIR, `${post.slug}.png`), buffer);
  }

  console.log('Done!');
}

generateImages();

Run with:

bash
OG_IMAGE_API_KEY=og_xxx node scripts/generate-og-images.js

Generate stunning Open Graph images programmatically.