Skip to content
Guides

Image Generation API in JavaScript and TypeScript

An image generation API JavaScript guide: one fetch call from Node, Deno, Bun or a Worker, TypeScript types from OpenAPI, references, batches, a safe key.

Updated 5 min read

Image generation API JavaScript code needs no SDK: one fetch call with a Bearer key submits the prompt, a second reads the job until its images are ready, and the same lines run in Node.js, Deno, Bun, Next.js route handlers and Cloudflare Workers. On Frameport that one request reaches Nano Banana Pro, Frameport Image 1, GPT Image 2.5 Sunburst and every other image model in the catalog, from $0.025 per image, and an image that fails costs nothing.

This guide writes the first request with fetch, adds TypeScript types generated from the OpenAPI spec, sends reference pictures and batches, and keeps the key where it belongs: on the server.

What you need

  • A runtime with fetch. Any current Node.js release (it has been built in since Node 18), Deno, Bun, or an edge runtime. No package is needed for the requests.
  • An API key. Create an account, add to the balance, then create a key under API keys. It starts with fp_live_ and is shown once.
  • The key in an environment variable, read only by server code:
export FRAMEPORT_API_KEY="fp_live_..."

The request and the answer are plain JSON, so nothing below depends on a framework. Every field is in the images reference.

Your first image generation API JavaScript call

POST /v1/images/generations holds the price and answers at once with 202 Accepted and a generation in the queued state. Read the generation every couple of seconds until it is succeeded or failed, then fetch each file:

image.mjs
import { writeFile } from 'node:fs/promises'
import { setTimeout as sleep } from 'node:timers/promises'

const API = 'https://frameport.ai/v1'
const headers = {
  'Authorization': `Bearer ${process.env.FRAMEPORT_API_KEY}`,
  'Content-Type': 'application/json',
}

// 1. Submit: the price is held on the balance
let gen = await fetch(`${API}/images/generations`, {
  method: 'POST',
  headers,
  body: JSON.stringify({
    model: 'nano-banana-pro',
    prompt: 'A ceramic teapot shaped like a sleeping fox on a linen tablecloth, soft morning light, product photo',
    aspect_ratio: '4:3',
  }),
}).then(res => res.json())
if (gen.error) throw new Error(`${gen.error.code}: ${gen.error.message}`)

// 2. Read it until it settles
while (gen.status === 'queued' || gen.status === 'running') {
  await sleep(2000)
  gen = await fetch(`${API}/generations/${gen.id}`, { headers }).then(res => res.json())
}
if (gen.status === 'failed') throw new Error(gen.error.message) // nothing was charged

// 3. Save every image that succeeded
for (const [index, output] of gen.outputs.entries()) {
  if (output.status !== 'succeeded') continue
  const file = await fetch(output.url)
  const extension = output.content_type.split('/')[1] ?? 'png'
  await writeFile(`teapot-${index + 1}.${extension}`, new Uint8Array(await file.arrayBuffer()))
}
console.log(gen.id, 'charged', gen.cost_usd)

Run it with node image.mjs. Bun runs the same file (bun image.mjs), and so does Deno through its Node compatibility (deno run -A image.mjs). In a Worker or an edge function there is no disk: return the image's url, or stream the file to your own storage. The finished generation reads like this:

GET /v1/generations/{id} · succeeded (abridged)
{
  "id": "gen_4kQ8vT2nLm9Xr7Wd1sYcPa",
  "type": "image",
  "model": "nano-banana-pro",
  "status": "succeeded",
  "reserved_usd": 0.16,
  "cost_usd": 0.16,
  "outputs": [{
    "id": "file_8Hc2RkQw5ZpT1mVb7nXe3L",
    "status": "succeeded",
    "url": "https://frameport.ai/v1/files/file_8Hc2RkQw5ZpT1mVb7nXe3L?expires=1795779600&signature=…",
    "url_expires_at": "2026-11-28T11:10:00.000Z",
    "content_type": "image/png",
    "cost_usd": 0.16
  }],
  "error": null
}

The url is signed and opens without a key for about an hour; every read of the generation signs a fresh one. Files are not kept forever, so copy the ones you keep to your own storage.

Types from the OpenAPI spec

The whole API is described in an OpenAPI 3.1 document at /openapi.json. Generate TypeScript declarations from it once, and requests and answers are typed without a hand-written SDK:

npm install --save-dev openapi-typescript typescript
npx openapi-typescript https://frameport.ai/openapi.json -o api.d.ts

The paths and components it exports go well with openapi-fetch, a small typed wrapper around fetch (npm install openapi-fetch). Paths are written as the spec writes them, with /v1:

typed.ts
import createClient from 'openapi-fetch'
import type { components, paths } from './api.js' // the api.d.ts generated above

type Generation = components['schemas']['Generation']

const client = createClient<paths>({
  baseUrl: 'https://frameport.ai',
  headers: { Authorization: `Bearer ${process.env.FRAMEPORT_API_KEY}` },
})

const { data, error } = await client.POST('/v1/images/generations', {
  body: { model: 'fp-image-1', prompt: 'Isometric illustration of a tiny bakery at dawn, warm windows, pastel palette', n: 2 },
  params: { header: { 'Idempotency-Key': crypto.randomUUID() } },
})
if (error) throw new Error(`${error.error.code}: ${error.error.message}`)
const gen: Generation = data
console.log(gen.id, gen.status, gen.reserved_usd)

A typo in a field name, a wrong aspect ratio or a missing prompt now fails at compile time. Model ids and their options change more often than the endpoints, so read those from GET /v1/models at run time rather than baking them into types; the OpenAPI page lists other generators and clients.

References and batches

Two fields do most of the work beyond a prompt:

  • reference_images: pictures to edit or to keep. Nano Banana Pro reads up to 6 and edits by instruction, Frameport Image 1 up to 10. GPT Image 2.5 Sunburst reads no pictures: it generates from the prompt only.
  • n: up to 4 images in one request, each charged on its own. If one fails and the others succeed, only those are billed.

A picture can be an https URL, an upload, a base64 data URI, or the file_… id of one of your own outputs. That last one turns the teapot above into an edit with nothing to download or host:

edit.mjs: the first image becomes a reference
import { readFile } from 'node:fs/promises'

const label = `data:image/png;base64,${(await readFile('label.png')).toString('base64')}`

const edit = await fetch(`${API}/images/generations`, {
  method: 'POST',
  headers,
  body: JSON.stringify({
    model: 'nano-banana-pro',
    prompt: 'The same teapot glazed in deep cobalt blue, with the label from the second picture on its side; everything else unchanged',
    reference_images: [gen.outputs[0].id, label], // a file id, then a local picture
    n: 2,
    aspect_ratio: '4:3',
  }),
}).then(res => res.json())
if (edit.error) throw new Error(`${edit.error.code}: ${edit.error.message}`)

Two takes on Nano Banana Pro cost $0.32; four on Frameport Image 1 cost $0.10, plus a small fee for each reference after the first on that model. Data URIs suit small pictures, since a request body is 16 MB at most; upload anything larger. The same request in Python is in the image generation API Python guide, and Nano Banana Pro vs GPT Image 2.5 helps you choose between those two.

Never ship the key to the browser

The key spends your balance, and anything sent to a browser can be read by whoever opens the page. So the browser never calls the API: it calls your server, which checks who is asking, calls the API with the key, and returns only what the page needs.

A server handler, in Web-standard Request and Response
export async function generate(request: Request): Promise<Response> {
  const { prompt } = await request.json()
  if (typeof prompt !== 'string' || !prompt.trim() || prompt.length > 2400) {
    return Response.json({ message: 'Write a prompt of up to 2,400 characters.' }, { status: 400 })
  }
  // Check the signed-in user and their allowance here, before anything is spent

  const res = await fetch('https://frameport.ai/v1/images/generations', {
    method: 'POST',
    headers: { 'Authorization': `Bearer ${process.env.FRAMEPORT_API_KEY}`, 'Content-Type': 'application/json' },
    body: JSON.stringify({ model: 'fp-image-1', prompt, max_cost_usd: 0.025 }),
  })
  const gen = await res.json()
  if (gen.error) return Response.json({ message: gen.error.message }, { status: res.status })
  return Response.json({ id: gen.id, status: gen.status }, { status: 202 })
}

Because it takes a standard Request and returns a Response, it drops into a Next.js route handler (export it as POST), a Hono route (pass it c.req.raw) or a Deno server with little change; on Cloudflare Workers, read the key from the env binding instead of process.env. Store the generation id with the user who asked, and check it on every read, so one user cannot poll another's images. max_cost_usd caps what any single request can cost. The Next.js AI image generation guide builds the whole flow in a Next.js app: the route, the progress in the page and the files served from your own domain. TypeScript types for every endpoint can come straight from the spec, as the OpenAPI client generator guide shows.

FAQ

Is there a JavaScript SDK for the image API?

You do not need one. The API is three plain HTTP calls with JSON bodies, so fetch covers it in every runtime, and openapi-typescript generates types from the published spec if you want them. openapi-fetch adds a typed client in a few lines.

How do I call GPT Image or Nano Banana from Node.js?

With the same request: change model to gpt-image-2-5-sunburst, nano-banana-pro or any other image model id. One key and one balance cover them all, so there is no separate account or SDK per maker.

Can I call the image API from the browser?

Not with your key. A key in front-end code can be copied and spent by anyone. Call the API from a server route, a server action or a function, and let the browser talk to that.

Which Node.js version do I need?

Any current release. fetch, FormData and web streams have been built in since Node 18, so the samples need no extra package; run a Node version that still gets security updates in production.

Does the image API return JSON or the image itself?

JSON. The answer is a generation with one output per image, each with a signed url and its content_type. Fetch the URL for the bytes, or stream GET /v1/generations/{id}/content with your key.

Start building.

Your API key is free. Top up from $10 when you are ready.