KNIGHTVISIONAPI

KNIGHTVISION / DEVELOPERS

Generate AI videos with JavaScript

Use server-side JavaScript to call Knightvision, persist a generation ID and retrieve the final video with bounded status checks.

Where this fits

A server-side JavaScript integration can use fetch to submit a video request and inspect its status. Keep the API credential in the server environment, never in a browser bundle. The example below is designed for a modern Node.js environment and makes one paid generation request when run.

Plan the approach

Separate the submission function from any user-interface polling. Save the accepted job ID immediately so another worker can continue after a restart. Abort a slow HTTP request locally if needed, but remember that cancellation of the local request does not cancel a server-side generation.

A practical workflow

  1. Set the server environment key and inspect the example’s model and output settings.
  2. Submit one request, write the job record and use the returned ID for status checks.
  3. Resolve only on complete, stop on error and preserve pending jobs when the polling deadline expires.

WORKED EXAMPLE / ILLUSTRATIVE BRIEF

Put the idea into practice

Example architecture: An authenticated route creates a project and queues work. A Node worker calls Knightvision and updates the project record; the frontend reads your own project-status endpoint.

JavaScript example

This example has been checked with mocked responses. Running it against your account submits a paid generation. It resumes the job saved in knightvision-video-job.json; use a durable project database for a production service. Reconcile an uncertain submission before starting a new job.

// Node.js 22+; save as video.mjs. Run on your server, not in a browser.
// Set KNIGHTVISION_API_KEY securely. The first run submits a paid job.
import { readFile, writeFile } from "node:fs/promises";

const base = "https://knightvision.ai/api/v1/partner";
const record = "knightvision-video-job.json";
const key = process.env.KNIGHTVISION_API_KEY;
if (!key) throw new Error("Set KNIGHTVISION_API_KEY on the server.");
const headers = { Authorization: `Bearer ${key}`, "Content-Type": "application/json" };
const payload = {
  model: "kling-v3-text-to-video",
  prompt: "A gentle camera move across a quiet coastal road at sunrise",
  duration: 5, quality: "720p", aspect_ratio: "16:9", sound: false
};

export async function run() {
  let saved;
  try {
    saved = JSON.parse(await readFile(record, "utf8"));
  } catch (error) {
    if (error.code !== "ENOENT") throw error;
  }
  let jobId;
  if (saved) {
    if (saved.state === "submitting") {
      throw new Error("Submission uncertain: check /videos before retrying.");
    }
    jobId = saved.job_id;
  } else {
    await writeFile(record, JSON.stringify({ state: "submitting", payload }), { flag: "wx" });
    const response = await fetch(base + "/generate-video", {
      method: "POST", headers, body: JSON.stringify(payload),
      signal: AbortSignal.timeout(60000)
    });
    if (!response.ok) throw new Error(`Submit HTTP ${response.status}; reconcile before retrying.`);
    jobId = (await response.json()).job_id;
    if (!jobId) throw new Error("Missing job_id; check job history before retrying.");
    await writeFile(record, JSON.stringify({ state: "accepted", job_id: jobId }));
  }
  const deadline = Date.now() + 600000;
  while (Date.now() < deadline) {
    const response = await fetch(base + "/video-status/" + jobId, {
      headers, signal: AbortSignal.timeout(30000)
    });
    if (!response.ok) throw new Error(`Status HTTP ${response.status}; resume the saved job later.`);
    const result = await response.json();
    if (result.status === "complete") return result.video_url;
    if (result.status === "error") throw new Error("Generation failed; inspect the saved job.");
    await new Promise(resolve => setTimeout(resolve, 5000));
  }
  throw new Error("Still pending; rerun to resume the saved job, not submit again.");
}

// Keep this line for a standalone script; remove it when importing run().
console.log(await run());

What to check

Test HTTP failures separately from generation failures. Avoid retry middleware that automatically repeats every POST request after a connection error.

Can I paste this code into a browser console?

No. It uses a server-side API key and file persistence. Put the integration in a trusted backend and expose only your own authorized application endpoints.

Tools and documentation

Use these product references for current settings and availability.

Bring your next idea to life.

Use one API key and a shared prepaid credit balance. No API subscription required.

Try Knightvision now