Next.js, Workers & Edge Runtime Guide

TypeScript & Node.js 22 Guide: Typed Fetch Client & JSON CLI Automation

Run AI Chili across Node.js 22, Next.js Route Handlers, Cloudflare Workers, and Vercel Edge using standard Web Fetch with zero npm bloat, or shell out to aichili generate --json from build scripts.

Last updated: By AI Chili Platform & Developer Experience Team Entity: AI Chili Inc. (Vancouver, BC)
Key Endpoints: REST Gateway https://aichili.ai/api/v1 · Streamable HTTP MCP https://aichili.ai/mcp · OpenAPI 3.1 /openapi.json.

Architecture & Endpoint Overview

JS / TS RuntimeIntegration ApproachDependenciesTimeout & State Pattern
Next.js App Router / EdgeTyped fetch client -> enqueue POST /generations, poll from client/cron0 npm packagesReturn job.id immediately; poll GET /generations/{id}
Cloudflare Workers / QueuesWorker submits with Idempotency-Key; Queue consumer polls status0 npm packagesSurvives Worker CPU limits cleanly
Node.js 22 Build / CI ScriptsexecFile('aichili', ['generate', '--wait', '--json', ...])brew install AI-Chili/tap/aichiliSingle command blocks until MP4 output_asset is ready

4-Step Implementation Blueprint

01 · Copy Zero-Dep Typed Client

Drop the 60-line TypeScript client below into lib/aichili.ts for strict compile-time checking across all 5 model_id values and h3-sol alias.

02 · Quote Before Enqueueing in Route Handlers

Call client.planGeneration(req) first so your Next.js or Worker endpoint can verify user quota or display exact credits.

03 · Return Job ID Immediately on Serverless

Video rendering takes 15s-90s; enqueue POST /api/v1/generations in your serverless handler and poll GET /api/v1/generations/{id} rather than holding an HTTP response open.

04 · Use aichili --json in Local Node Automation

For CLI pipelines, HyperFrames renders, or CI jobs, invoke aichili plan --json and aichili generate --wait --json directly.

1. Zero-Dependency Typed Fetch Wrapper (Next.js / Cloudflare Workers / Node 22)

Uses Web-standard fetch and AbortSignal.timeout with full TypeScript types matching /openapi.json:

export type ChiliModelId =
  | 'h3-vdn'
  | 'h3-sol'
  | 'wan3.0-video'
  | 'seedance-2.5'
  | 'minimax-h3-gmi'
  | 'avatar-talk';

export interface GenerationCreateRequest {
  mode: 't2v' | 'i2v';
  model_id: ChiliModelId;
  workflow?: 'general' | 'reference' | 'photo' | 'talk';
  idempotency_key?: string;
  params: {
    prompt: string;
    duration_s?: number;
    resolution?: string;
    ratio?: '16:9' | '9:16' | '1:1' | '4:3' | '3:4' | '21:9' | 'adaptive';
    ref_asset_ids?: string[];
    ref_roles?: Array<'reference_image' | 'reference_video' | 'first_frame' | 'last_frame'>;
    seed?: number;
  };
}

export interface GenerationPlanResponse {
  total_credits: number;
  total_duration_s: number;
  segments: number;
}

export interface GenerationJobResponse {
  id: string;
  status: 'queued' | 'running' | 'succeeded' | 'failed' | 'canceled';
  credits_cost: number;
  output_asset?: Record<string, unknown> | null;
  error_code?: string | null;
  error_message?: string | null;
}

export class AiChiliClient {
  constructor(
    private readonly apiKey: string,
    private readonly baseUrl = 'https://aichili.ai/api/v1',
  ) {}

  private async request<T>(method: string, path: string, body?: unknown): Promise<T> {
    const res = await fetch(`${this.baseUrl}${path}`, {
      method,
      headers: {
        'User-Agent': 'curl/8.4.0',
        'Authorization': `Bearer ${this.apiKey}`,
        'Accept': 'application/json',
        ...(body !== undefined ? { 'Content-Type': 'application/json' } : {}),
      },
      body: body !== undefined ? JSON.stringify(body) : undefined,
      signal: AbortSignal.timeout(25_000),
    });
    const data = await res.json();
    if (!res.ok) {
      throw new Error(`AI Chili API ${res.status}: ${data?.error?.code ?? 'error'} - ${data?.error?.message ?? ''}`);
    }
    return data as T;
  }

  planGeneration(req: GenerationCreateRequest): Promise<GenerationPlanResponse> {
    return this.request('POST', '/generations/plan', req);
  }

  createGeneration(req: GenerationCreateRequest): Promise<GenerationJobResponse> {
    return this.request('POST', '/generations', req);
  }

  getGeneration(jobId: string): Promise<GenerationJobResponse> {
    return this.request('GET', `/generations/${encodeURIComponent(jobId)}`);
  }
}

2. Programmatic CLI JSON Mode in Node.js 22 (child_process.execFile)

Ideal for build scripts and video composition pipelines with npm install -g aichili (or brew install AI-Chili/tap/aichili):

import { execFile } from 'node:child_process';
import { promisify } from 'node:util';

const execFileAsync = promisify(execFile);

async function renderBrollClip(prompt: string, idemKey: string) {
  const { stdout: planOut } = await execFileAsync('aichili', [
    'plan', '--model', 'h3-vdn', '--mode', 't2v',
    '--duration', '15', '--resolution', '768p', '--ratio', '9:16',
    '--prompt', prompt, '--json',
  ]);
  const plan = JSON.parse(planOut);
  if (plan.total_credits > 20) throw new Error(`Budget exceeded: ${plan.total_credits}`);

  const { stdout: jobOut } = await execFileAsync('aichili', [
    'generate', '--model', 'h3-vdn', '--mode', 't2v',
    '--duration', '15', '--resolution', '768p', '--ratio', '9:16',
    '--idempotency-key', idemKey, '--prompt', prompt, '--wait', '--json',
  ]);
  return JSON.parse(jobOut);
}

Recommended AI Chili Engines for TypeScript & Node 22

Frequently Asked Questions

Can I call https://aichili.ai/api/v1/* directly from browser client code?

Never expose your chili_sk_* secret key in public browser bundles. Call AI Chili from a Next.js Route Handler, Server Action, or Cloudflare Worker so your key stays server-side.

Does the /api/v1 gateway accept an Idempotency-Key HTTP header?

Yes. You can pass idempotency_key in the JSON body or send an Idempotency-Key HTTP header on POST /api/v1/generations, and the gateway bridges it automatically.

Can I generate TypeScript types straight from /openapi.json?

Yes. Run npx openapi-typescript https://aichili.ai/openapi.json -o src/types/aichili.d.ts to generate types directly from our live OpenAPI 3.1 spec.

Explore Other Stack Integrations