AI Video Generation API in Node.js: A Working Script
AI video API Node JS guide: submit a clip with fetch, poll with a backoff, stream the MP4 to disk, verify webhooks and type it all from OpenAPI.
Updated 5 min read
To generate AI video from Node.js, you POST a prompt to a video generation API with fetch, read the job until it settles, then stream the file to disk. On Frameport those are the same three calls for all 13 video models on one key, with no SDK: Node 18 and later have fetch built in.
This guide builds that script as one ES module: submit with retries that never charge twice, poll with a backoff and a deadline, download without holding the clip in memory, verify webhooks, and get TypeScript types from the OpenAPI spec. Every field and header is the real API's.
What you need
- Node.js 18 or later. The webhook part uses Express (
npm install express); the rest needs no package. - An API key: create an account, add funds under Billing (from $10), then create a key under API keys. It starts with
fp_live_and is shown once. - The key in an environment variable, read on your server only. Never ship it to a browser.
export FRAMEPORT_API_KEY="fp_live_..."Every snippet below goes in the same file, clip.mjs, under this helper. It sends the key, parses the JSON and turns an error answer into an exception that carries the status, the stable code and the Retry-After delay.
import { randomUUID } from 'node:crypto'
import { createWriteStream } from 'node:fs'
import { Readable } from 'node:stream'
import { pipeline } from 'node:stream/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',
}
async function api(path, init = {}) {
const res = await fetch(`${API}${path}`, { ...init, headers: { ...HEADERS, ...init.headers } })
const body = await res.json().catch(() => ({ error: { code: `http_${res.status}`, message: res.statusText } }))
if (!res.ok) {
const error = new Error(`${body.error.code}: ${body.error.message}`)
error.status = res.status
error.code = body.error.code
error.retryAfter = Number(res.headers.get('retry-after')) || 0
throw error
}
return body
}Submit a clip with fetch
POST /v1/videos/generations checks the request, holds its price on your balance and answers at once with 202 Accepted: the generation, its id, status: "queued" and reserved_usd, the price held. If you want the price first, the same body goes to POST /v1/generations/quote, which holds nothing and is not rate-limited.
Send an Idempotency-Key with every submit. A network error can hide whether the request arrived; sent again with the same key and the same body, it returns the first generation instead of starting, and charging, a second clip. That makes the retry loop below safe:
async function submit(body, idempotencyKey = randomUUID()) {
for (let attempt = 1; ; attempt++) {
try {
return await api('/videos/generations', {
method: 'POST',
headers: { 'Idempotency-Key': idempotencyKey },
body: JSON.stringify(body),
})
}
catch (error) {
// No status: the network failed. 409 request_in_progress: the first try is still being accepted.
const retry = !error.status || error.status === 429 || error.status >= 500 || error.code === 'request_in_progress'
if (!retry || attempt === 5) throw error
await sleep((error.retryAfter || 2 ** attempt) * 1000)
}
}
}
const gen = await submit({
model: 'seedance-2-5',
prompt: 'A paper boat drifts down a rain-soaked street at dusk, low tracking shot',
duration: 5,
resolution: '720p',
aspect_ratio: '16:9',
max_cost_usd: 1.35,
})
console.log(gen.id, gen.status, 'held', gen.reserved_usd)A 400 is never retried: the message names the field that is off and lists what the model takes. max_cost_usd caps the request: one that would cost more is refused with 400 max_cost_exceeded before anything is held. In production, use your own job id as the idempotency key; the same key with the same body stays safe for 24 hours (idempotency).
Poll with a backoff
A generation moves from queued to running, then ends succeeded or failed. Read it until it settles, waiting a little longer each time, and give up at a deadline: a loop with no exit can run forever.
async function wait(gen, timeoutMs = 30 * 60_000) {
const deadline = Date.now() + timeoutMs
let delay = 2000
while (gen.status === 'queued' || gen.status === 'running') {
if (Date.now() > deadline) throw new Error(`${gen.id} is still ${gen.status}`)
await sleep(delay)
delay = Math.min(delay * 1.5, 15_000)
gen = await api(`/generations/${gen.id}`)
}
return gen
}
const done = await wait(gen)
if (done.status === 'failed') {
throw new Error(done.error.message) // nothing was charged: the hold went back to the balance
}
console.log('charged', done.cost_usd)GET /v1/generations/{id} reads a generation of any type, so the same function waits for images and clip edits too. Reads are not counted against your rate limit. Giving up in your script does not stop the clip: read it later by id, or take a webhook. A generation that runs too long is ended by the API with the timeout code, and like every failure it costs nothing.
Stream the file to disk
Each finished output has a signed url that opens without a key for about an hour. Pipe the response into a file rather than buffering the whole clip in memory:
async function download(gen, path) {
const res = await fetch(gen.outputs[0].url)
if (!res.ok) throw new Error(`download failed: ${res.status}`)
await pipeline(Readable.fromWeb(res.body), createWriteStream(path))
}
await download(done, 'boat.mp4')When a link has expired, read the generation again for a fresh one, or stream GET /v1/generations/{id}/content with your key. Files are not kept forever: copy the ones you keep to your own storage (files).
Verify a webhook signature in Node
A service that runs many clips should not poll each one. Add an endpoint under Webhooks in the dashboard and each generation of the workspace ends with a signed POST: generation.succeeded or generation.failed, with the generation in data. The Frameport-Signature header reads t=<unix seconds>,v1=<hex>, an HMAC-SHA256 of the timestamp, a dot and the raw body, keyed with the endpoint's secret. Verify it on the raw bytes, which is why the route takes express.raw:
import crypto from 'node:crypto'
import express from 'express'
const SECRET = process.env.WEBHOOK_SECRET // whsec_..., shown once when you add the endpoint
function verify(raw, header = '', toleranceSeconds = 300) {
const parts = Object.fromEntries(header.split(',').map(part => part.trim().split('=')))
const age = Math.abs(Date.now() / 1000 - Number(parts.t))
if (!parts.v1 || !(age <= toleranceSeconds)) return false
const expected = crypto.createHmac('sha256', SECRET).update(`${parts.t}.`).update(raw).digest('hex')
return expected.length === parts.v1.length
&& crypto.timingSafeEqual(Buffer.from(expected), Buffer.from(parts.v1))
}
const app = express()
app.post('/hooks/generations', express.raw({ type: 'application/json' }), (req, res) => {
if (!verify(req.body, req.get('Frameport-Signature'))) return res.sendStatus(400)
const event = JSON.parse(req.body)
res.sendStatus(204) // answer within 10 seconds, then do the work
console.log(event.type, event.data.id, event.data.status)
})
app.listen(3000)A delivery that gets no 2xx is sent again after 1, 5 and 15 minutes, with the same delivery id, so keep the ids you have handled. The guide to AI video API webhooks covers retries, duplicates and catching up after an outage; the webhooks reference has every header.
TypeScript types from the OpenAPI spec
The API is described by an OpenAPI 3.1 file at /openapi.json, so you can type requests and answers without a hand-written SDK. Generate a declaration file once:
npx openapi-typescript https://frameport.ai/openapi.json -o api.d.tsimport type { components, paths } from './api.js' // the api.d.ts generated above
type VideoRequest = paths['/v1/videos/generations']['post']['requestBody']['content']['application/json']
type Generation = components['schemas']['Generation']
const body: VideoRequest = {
model: 'seedance-2-5',
prompt: 'A paper boat drifts down a rain-soaked street at dusk, low tracking shot',
duration: 5,
}
const gen: Generation = await api('/videos/generations', { method: 'POST', body: JSON.stringify(body) })Regenerate the file when the changelog announces new fields. The OpenAPI page lists other generators.
Veo, Wan, Hailuo or Runway from Node.js
The script does not change from one model to the next: swap model, then the options that model takes. Each keeps its own grid of lengths and resolutions.
| Model | model | Lengths | Resolutions | Sound | From |
|---|---|---|---|---|---|
| Seedance 2.5 | seedance-2-5 | 4 to 30 seconds | 480p and 720p | On or off, same price | $0.12 / s |
| Veo 3.1 | veo-3-1 | 4, 6 or 8 seconds | 720p, 1080p and 4K | On or off, priced apart | $0.235 / s |
| Wan 3.0 | wan-3 | 2 to 30 seconds | 480p, 720p and 1080p | On or off, same price | $0.06 / s |
| Hailuo 3 | hailuo-3 | 5 to 15 seconds | 2K | On or off, same price | $0.15 / s |
| Runway Gen-4.5 | runway-gen-4-5 | 2 to 10 seconds | 720p | No soundtrack | $0.14 / s |
| Frameport Motion 1 | fp-motion-1 | 5 to 15 seconds | 480p, 768p, 1080p and 2K | On or off, same price | $0.02 / s |
On Veo 3.1, audio: false takes the lower silent price: an 8-second clip at 1080p is $3.72 with sound and $1.88 without. Read each grid from GET /v1/models, which needs no key, rather than typing it into your code: a value off the grid comes back as a 400 naming what the model takes. To call the API from a web app with the key kept on the server, see Next.js AI image generation. Typed clients can be generated from the spec: see the OpenAPI client generator guide.
FAQ
Do I need an SDK to call an AI video API from Node.js?
No. It is HTTPS and JSON, so the built-in fetch is enough: send the key as a Bearer token and read the JSON back. For types, generate them from the OpenAPI file.
How often should I poll a video generation?
Every few seconds, backing off up to about fifteen, with a deadline. Reads are not counted against your rate limit, but for many clips at once a webhook is simpler than a loop per clip.
How do I keep a retry from charging twice?
Send an Idempotency-Key header with each submit and reuse it on the retry. The same key with the same body returns the first generation for 24 hours, so a timeout followed by a retry never starts a second clip.
Can I call the API from React or the browser?
Not with your key: it spends money, so it belongs on your server, in an API route or a worker. Let the browser call your backend, and let your backend call the API and receive the webhooks.
Can I generate images from Node.js the same way?
Yes. POST /v1/images/generations takes a model such as flux-3-image or nano-banana-pro, a prompt and n from 1 to 4, and returns a generation that the same wait function follows to the end. The images reference has the fields, and the Python version of this guide shows the same steps with requests.