AI Image API: JavaScript Guide (Free)
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.
We will use the ZSky AI API, which gives you 100 free calls per day with no credit card required. Every example is copy-paste ready.
Basic: Generate with Fetch
This works in any modern browser (Chrome, Firefox, Safari, Edge) and Node.js 18+:
const API_KEY = "sk_live_your_api_key_here";
const response = await fetch("https://api.zsky.ai/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, valid 24h
Five lines of meaningful code. The API handles GPU computation and returns a download URL. No AI frameworks, no model files, no CUDA.
Node.js: Save Images to Disk
import { writeFile } from "fs/promises";
const API_KEY = process.env.ZSKY_API_KEY;
// Generate
const response = await fetch("https://api.zsky.ai/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
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.ZSKY_API_KEY;
for (let attempt = 0; attempt < maxRetries; attempt++) {
try {
const response = await fetch("https://api.zsky.ai/v1/generate/image", {
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);
Concurrent Generation with Promise.all
Generate multiple images simultaneously for maximum speed:
const prompts = [
"Aurora borealis over snowy mountains",
"Tropical beach at sunset, crystal water",
"Dense bamboo forest with sunlight filtering through",
"Ancient temple ruins in misty jungle"
];
const results = await Promise.all(
prompts.map(prompt => generateImage(prompt))
);
results.forEach((url, i) => {
console.log(`Image ${i + 1}: ${url}`);
});
Next.js API Route
Keep your API key secure by routing requests through a Next.js API endpoint:
// app/api/generate/route.js (Next.js App Router)
export async function POST(request) {
const { prompt, width, height } = await request.json();
if (!prompt) {
return Response.json({ error: "prompt required" }, { status: 400 });
}
const response = await fetch("https://api.zsky.ai/v1/generate/image", {
method: "POST",
headers: {
"Authorization": `Bearer ${process.env.ZSKY_API_KEY}`,
"Content-Type": "application/json"
},
body: JSON.stringify({
prompt,
width: width || 1024,
height: height || 1024
})
});
const data = await response.json();
if (!response.ok) {
return Response.json({ error: data.message }, { status: response.status });
}
return Response.json({ image_url: data.image_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" });
}
const response = await fetch("https://api.zsky.ai/v1/generate/image", {
method: "POST",
headers: {
"Authorization": `Bearer ${process.env.ZSKY_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"));
Ship AI Image Generation in Minutes
100 free API calls per day. Works with any JavaScript framework. No SDK required.
Get Free API Key →Browser: Display Generated Images
For client-side prototyping (remember to use a backend proxy in production):
async function generateAndDisplay(prompt) {
const response = await fetch("https://api.zsky.ai/v1/generate/image", {
method: "POST",
headers: {
"Authorization": "Bearer sk_live_your_key",
"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 the request and response interfaces:
interface GenerateRequest {
prompt: string;
negative_prompt?: string;
width?: 512 | 768 | 1024 | 2048;
height?: 512 | 768 | 1024 | 2048;
guidance_scale?: number;
seed?: number;
output_format?: "png" | "jpeg" | "webp";
style?: "photorealistic" | "stylized" | "anime" | "illustration";
}
interface GenerateResponse {
image_url: string;
job_id: string;
width: number;
height: number;
seed: number;
}
interface ErrorResponse {
error: string;
message: string;
code: number;
}
Frequently Asked Questions
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.
Does the ZSky AI API work with React and Next.js?
Yes. Use Next.js API routes or React Server Components to call the ZSky AI API from your server. For client-side React, create a backend endpoint that proxies the request so your API key stays secure. The API returns 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. For large batches, use the dedicated batch endpoint which accepts up to 50 prompts in a single request. 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.
Build AI into Any JavaScript App
From React dashboards to Node.js backends. One API, every framework. Free to start.
Get API Access →