Generate AI videos and image right in your browser -- unlimited free generation Try ZSky Free →

AI Image API: JavaScript Guide

By Cemhan Biricik · · About the author · Last reviewed May 12, 2026
By Cemhan Biricik 2026-03-27 12 min read

JavaScript runs everywhere -- browsers, servers, edge functions, serverless platforms. That makes it the most versatile language for integrating AI image generation into your stack. This guide covers every environment: browser fetch, Node.js, Next.js API routes, and React components. All examples use the native fetch API with zero dependencies.

The examples below use generic REST API patterns that work with any AI image generation provider (Stability AI, OpenAI DALL-E, Replicate, etc.). Swap the endpoint URL and API key for whichever service you choose. If you just want to generate AI images without writing code, try ZSky AI -- unlimited free generation, no code required.

Logo asset returned from ZSky's image API in JavaScript
Generated with ZSky AI's Signature Image Engine — free, no signup, full commercial rights.

Basic: Generate with Fetch

This pattern works in any modern browser (Chrome, Firefox, Safari, Edge) and Node.js 18+. Replace the URL and key with your chosen provider:

const API_KEY = process.env.IMAGE_API_KEY; // your provider's key

const response = await fetch("https://api.example.com/v1/generate/image", {
  method: "POST",
  headers: {
    "Authorization": `Bearer ${API_KEY}`,
    "Content-Type": "application/json"
  },
  body: JSON.stringify({
    prompt: "A futuristic city skyline at sunset, photorealistic",
    width: 1024,
    height: 1024
  })
});

const data = await response.json();
console.log(data.image_url); // CDN-hosted URL

Five lines of meaningful code.

The API handles GPU computation and returns a download URL.No AI frameworks, no model files, no CUDA.This same pattern applies to Stability AI, OpenAI, Replicate, and other providers.

Node.js: Save Images to Disk

import { writeFile } from "fs/promises";

const API_KEY = process.env.IMAGE_API_KEY;

// Generate (replace URL with your provider)
const response = await fetch("https://api.example.com/v1/generate/image", {
  method: "POST",
  headers: {
    "Authorization": `Bearer ${API_KEY}`,
    "Content-Type": "application/json"
  },
  body: JSON.stringify({
    prompt: "Cozy coffee shop interior, warm lighting, rain outside",
    width: 1024,
    height: 768,
    output_format: "png"
  })
});

const { image_url } = await response.json();

// Download and save
const imageResponse = await fetch(image_url);
const buffer = Buffer.from(await imageResponse.arrayBuffer());
await writeFile("coffee_shop.png", buffer);
console.log("Saved to coffee_shop.png");

Error Handling with Retry

Architecture diagram for ZSky's JS-driven image API workflow
Generated with ZSky AI's Custom Creative Model — free, no signup, full commercial rights.

Production apps need robust error handling. Here is a reusable function with exponential backoff:

async function generateImage(prompt, options = {}, maxRetries = 3) {
  const API_KEY = process.env.IMAGE_API_KEY;
  const API_URL = "https://api.example.com/v1/generate/image"; // your provider

  for (let attempt = 0; attempt < maxRetries; attempt++) {
    try {
      const response = await fetch(API_URL, {
        method: "POST",
        headers: {
          "Authorization": `Bearer ${API_KEY}`,
          "Content-Type": "application/json"
        },
        body: JSON.stringify({
          prompt,
          width: options.width || 1024,
          height: options.height || 1024,
          ...options
        }),
        signal: AbortSignal.timeout(60000) // 60s timeout
      });

      if (response.ok) {
        const data = await response.json();
        return data.image_url;
      }

      if (response.status === 429) {
        // Rate limited -- wait and retry
        const wait = Math.pow(2, attempt) * 1000;
        console.log(`Rate limited. Retrying in ${wait}ms...`);
        await new Promise(r => setTimeout(r, wait));
        continue;
      }

      if (response.status === 400) {
        // Bad request -- do not retry
        const error = await response.json();
        throw new Error(`Bad request: ${error.message}`);
      }

      throw new Error(`API error: ${response.status}`);

    } catch (err) {
      if (err.name === "TimeoutError") {
        console.log(`Timeout on attempt ${attempt + 1}`);
      } else if (attempt === maxRetries - 1) {
        throw err;
      }
    }
  }
  return null;
}

// Usage
const url = await generateImage("Mountain lake at golden hour");
console.log(url);

React Component

A complete React component that generates and displays AI images:

import { useState } from "react";

export function ImageGenerator() {
  const [prompt, setPrompt] = useState("");
  const [imageUrl, setImageUrl] = useState(null);
  const [loading, setLoading] = useState(false);

  const generate = async () => {
    setLoading(true);
    try {
      const res = await fetch("/api/generate", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ prompt })
      });
      const data = await res.json();
      setImageUrl(data.image_url);
    } catch (err) {
      console.error("Generation failed:", err);
    }
    setLoading(false);
  };

  return (
    <div>
      <input
        value={prompt}
        onChange={e => setPrompt(e.target.value)}
        placeholder="Describe your image..."
      />
      <button onClick={generate} disabled={loading}>
        {loading ? "Generating..." : "Generate"}
      </button>
      {imageUrl && <img src={imageUrl} alt={prompt} />}
    </div>
  );
}

Express.js Middleware

Build a backend API server that proxies image generation requests:

import express from "express";

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

app.post("/api/generate", async (req, res) => {
  const { prompt } = req.body;

  if (!prompt) {
    return res.status(400).json({ error: "prompt required" });
  }

  // Replace with your AI image provider's endpoint
  const response = await fetch("https://api.example.com/v1/generate/image", {
    method: "POST",
    headers: {
      "Authorization": `Bearer ${process.env.IMAGE_API_KEY}`,
      "Content-Type": "application/json"
    },
    body: JSON.stringify({ prompt, width: 1024, height: 1024 })
  });

  const data = await response.json();

  if (response.ok) {
    res.json(data);
  } else {
    res.status(response.status).json({ error: data.message });
  }
});

app.listen(3000, () => console.log("Server running on port 3000"));

Generate AI Images Without Code

Thumbnail produced from a single fetch call on ZSky
Generated with ZSky AI's Personal Style Engine — free, no signup, full commercial rights.

Unlimited free generation. 1080p videos with audio. Commercial rights on every plan. Paid plans from $19/mo.

Try ZSky Free →

Browser: Display Generated Images

For client-side prototyping (remember to use a backend proxy in production to keep your API key secure):

async function generateAndDisplay(prompt) {
  // In production, call YOUR backend (e.g. /api/generate)
  // which proxies to the AI provider -- never expose keys in browser code
  const response = await fetch("/api/generate", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ prompt, width: 1024, height: 1024 })
  });

  const { image_url } = await response.json();

  const img = document.createElement("img");
  img.src = image_url;
  img.alt = prompt;
  document.getElementById("output").appendChild(img);
}

generateAndDisplay("Watercolor painting of a forest at dawn");

TypeScript Types

If you use TypeScript, here are common request and response interfaces for AI image APIs. Adjust field names to match your provider's documentation:

// Common shape -- field names vary by provider
interface GenerateRequest {
  prompt: string;
  negative_prompt?: string;
  width?: number;
  height?: number;
  guidance_scale?: number;
  seed?: number;
  output_format?: "png" | "jpeg" | "webp";
}

interface GenerateResponse {
  image_url: string;   // or "data", "output", "url" depending on provider
  job_id?: string;
  width: number;
  height: number;
  seed?: number;
}

interface ErrorResponse {
  error: string;
  message: string;
  code: number;
}

Frequently Asked Questions

JavaScript request flow infographic for ZSky's image API
Generated with ZSky AI's Bespoke generative model — free, no signup, full commercial rights.

Can I call an AI image API directly from the browser?

You can, but it is not recommended for production because it exposes your API key in client-side code. For production apps, route API calls through your backend server (Node.js, Next.js API routes, or serverless functions). For prototyping and local development, direct browser calls work fine.

Do AI image APIs work with React and Next.js?

Yes. Use Next.js API routes or React Server Components to call AI image APIs from your server. For client-side React, create a backend endpoint that proxies the request so your API key stays secure. Most APIs return JSON with image URLs that render directly in img tags.

What is the fastest way to generate AI images with JavaScript?

Use Promise.all with multiple fetch calls to generate images concurrently. Some providers also offer dedicated batch endpoints for bulk generation. Both approaches are significantly faster than sequential generation.

Do I need npm packages to use an AI image API in JavaScript?

No. The built-in fetch API in modern browsers and Node.js 18+ is all you need. No npm packages, SDKs, or external dependencies required. The API uses standard REST conventions with JSON request and response bodies.

How do I save AI-generated images to disk with Node.js?

Fetch the image URL returned by the API, convert the response to a buffer, and write it with fs.writeFile. Node.js 18+ supports fetch natively. For older versions, use the node-fetch package. The image data is a standard binary blob in PNG, JPEG, or WebP format.

Try AI Image Generation Now

No code needed. Unlimited free generation. 1080p videos with audio. Paid plans from $19/mo.

Try ZSky Free →
Editorial note: This article is drafted with AI assistance using ZSky's own tooling and reviewed by the ZSky editorial team for accuracy and brand voice. Feedback welcome at [email protected].