Skip to content

Instantly share code, notes, and snippets.

@joshuacrowley
Created July 15, 2026 21:50
Show Gist options
  • Select an option

  • Save joshuacrowley/e95118ecb3f297aff7dbd70a42b84adf to your computer and use it in GitHub Desktop.

Select an option

Save joshuacrowley/e95118ecb3f297aff7dbd70a42b84adf to your computer and use it in GitHub Desktop.
html-prototypes-skill.md
name html-prototypes
description Build single-file HTML AI prototypes — self-contained design artifacts that non-technical people can run by serving a folder and opening a page in a browser. Use when creating, remixing, or debugging an HTML prototype, or when helping someone understand what a prototype idea will require (API keys, servers, proxies). Covers ESM/CDN loading, browser-direct vs proxied API access, key handling, async polling, and communicating requirements to non-technical users.

Building single-file HTML prototypes

An HTML prototype is a design artifact, not a product. The goal is a working thing someone can feel in the browser today, iterate on by taste, and remix tomorrow. One file, no build step, no install — that's what makes it shareable ("just send the file"), remixable ("copy it and change things"), and legible to both humans and AI agents.

If the codebase you're in already has working prototypes, open a similar one and copy its approach — verified working code beats anything you remember. This is the intended workflow, not a shortcut. That especially applies to model names and API details, which churn fast and which both humans and models hallucinate.

The one hard constraint

One .html file = the whole app. All CSS in one <style> block, all JS in one <script> at the end of <body>. No build step, no npm install, no framework — vanilla JS and hand-written CSS with design tokens. Supporting files are allowed only as optional plumbing (a tiny Node proxy script, a deployed worker, a README); the HTML file must still be the complete app.

Start here: requirements triage

Before writing code, work out which tier the idea needs, and tell the user in plain language what they'll need before you build. This is the single most important thing when working with non-technical users — a surprise "blocked by CORS policy" error at run time is how prototypes die.

Tier What it needs When
0 — Just a file Nothing. Drag into a browser. No API calls (UI experiments, players, compare tools)
1 — Static server python3 -m http.server 8000 or npx serve, open http://localhost:8000/... Any API work. Browser-direct APIs work at this tier
2 — Local proxy A ~100-line zero-dependency Node script run with node proxy.mjs APIs that don't send CORS headers
3 — Cloud worker A deployed worker (Cloudflare or similar, one-time setup) When the API needs public URLs for input media, or the prototype must work away from localhost

Rules of thumb:

  • Default to Tier 1. Even prototypes that would work from file:// should be served — websocket APIs need a real origin and some APIs reject file:// outright. Add a runtime guard:
    if (location.protocol === 'file:') {
      showToast('Serve this over http://localhost — this API blocks pages opened as files', 'error');
    }
  • Test each API from the browser before building around it. A one-off fetch in the console tells you in ten seconds whether it sends CORS headers. Roughly: Google Gemini, OpenAI, Anthropic (with its browser-access header), and fal.ai work browser-direct; Luma and some Replicate paths need a proxy. Verify — this changes.
  • CORS in one sentence for users: "Some AI services only accept requests from real websites, not from a page on your computer — so we run a tiny relay program that passes your requests along." The proxy never holds keys; it forwards the browser's own Authorization header.

Working with a non-technical user

  • Open with a "what you'll need" list: which API keys (with the URL where they get each one), whether a terminal command is needed, and a one-line reason for each.
  • Keys live in the browser, entered by the user. Never bake keys into the file or ask users to edit code. Build a settings modal (gear button) with type="password" inputs, links to each provider's key page, and copy stating "stored only in this browser's localStorage".
  • Humanize every error. Substring-match known failures and translate to actionable advice; log the raw error to a visible log panel, toast the humanized one:
    function humanizeError(raw) {
      const s = String(raw);
      if (s.includes('401')) return 'Your API key was rejected — re-paste it in Settings.';
      if (s.includes('429')) return 'The service is busy (rate limited). Wait ~30s and try again.';
      if (s.includes('Failed to fetch')) return 'Could not reach the API. Is the proxy running? Are you on http://localhost (not file://)?';
      return s;
    }
  • Show your plumbing status. If a local server/proxy is required, poll a /health endpoint and show an "OK / not running" pill. Say so in the README and in any directory/index page that links to the prototype.
  • Make the request visible. A debug view showing the exact prompt/payload being sent (data URIs abbreviated, keys redacted) builds trust and teaches users how the AI is actually being asked.
  • Interaction choices are defaults to iterate, not commitments. Ship a working feel, then let the user adjust by taste. For genuine either/or interaction questions, ship two sibling files (thing.html / thing-variant.html) so the user can A/B by feel.

House style (the file anatomy)

<!DOCTYPE html><html><head>
  <meta charset/viewport> <title>
  <link rel="icon" href="data:,">                      <!-- suppress favicon 404 -->
  Google Fonts links (preconnect + css2)
  <style> :root { design tokens } ... all CSS ... </style>
</head><body>
  ... all markup, including hidden modals + toast container ...
  <script type="module"> ... entire app ... </script>
</body></html>

Inside the script, a fixed banner-commented section order:

// ============ STATE ============
const state = { apiKey: localStorage.getItem('myapp_api_key') || '', isRunning: false, jobs: [] };
// ============ ELEMENTS ============
const el = { generateBtn: document.getElementById('generateBtn'), /* every node, once */ };
// ============ UTILITIES ============   showToast, log, fileToBase64, sleep
// ============ SETTINGS ============    modal open/save, key guards
// ============ <FEATURES> ============  one section per feature
// ============ INIT ============
init();

Conventions that earn their keep:

  • Single mutable state object; imperative renderX() functions. No reactivity, no virtual DOM. Expose window.__myapp = state so browser automation and debugging can reach it.
  • CSS design tokens in :root (--bg, --panel, --border, --text, --muted, --accent, --good, --bad, --radius-*, --transition-*), plus * { box-sizing: border-box; margin: 0; padding: 0 }. Give each prototype its own palette and font personality.
  • Status feedback trio: (1) a showToast(msg, type) bottom pill that auto-removes after ~4s; (2) a status pill with setStatus(kind, text) and a live elapsed-seconds counter during long generations; (3) for API-heavy tools, a timestamped monospace log panel recording every request and status transition.
    function showToast(message, type = 'info') {
      const t = document.createElement('div');
      t.className = `toast ${type}`;
      t.textContent = message;
      el.toastContainer.appendChild(t);
      setTimeout(() => t.remove(), 4000);
    }
  • Buttons narrate: disable + swap label during async work ('Generating...'), always restore in finally. Guard re-entry with an isRunning flag.
  • Modals: fixed overlay + .visible class toggle; close on ✕, backdrop click (e.target === overlay), and Escape.
  • localStorage keys are prefixed snake_case (myapp_gemini_key). Deliberately reuse key names across sibling prototypes so users enter keys once for a family of tools. Auto-open settings on boot if keys are missing; give the settings button a has-keys accent class when configured.
  • Persist settings always; work products cautiously. Base64 images blow the localStorage quota — strip media before saving (keep hosted URLs), and catch QuotaExceededError. For real file persistence, use OPFS with an IndexedDB fallback. Most prototypes are deliberately session-scoped: persistence is opt-in complexity.

Dependencies: the loading ladder

  1. Default: zero dependencies. Raw fetch beats an SDK for most APIs.
  2. Pinned ESM from a CDN when a library earns its place:
    import { GoogleGenAI } from 'https://esm.sh/@google/genai@1.30.0';
    import * as THREE from 'https://esm.sh/three@0.160.0';
    import { OrbitControls } from 'https://esm.sh/three@0.160.0/examples/jsm/controls/OrbitControls.js?deps=three@0.160.0';
    Always pin the version in the URL. For subpath imports on esm.sh, add ?deps=pkg@version so the subpath resolves against the same package instance (avoids the classic two-copies-of-Three bug).
  3. Import maps (<script type="importmap">) when several ESM deps or bare specifiers help readability.
  4. Classic <script src> for non-ESM libraries and web components.
  5. Lazy await import() for heavy libraries (e.g. ffmpeg.wasm) — load on first use, catch failure, degrade gracefully ("stitching unavailable; download clips individually").
  6. Prefer boring. A contentEditable div with custom logic has outlived fragile rich-text ESM libraries; hand-rolled beats clever when the file must survive being remixed.

Talking to AI APIs

Async generation = create + poll. Nearly every generative API (video especially) follows this shape:

const createRes = await fetch(CREATE_URL, {
  method: 'POST',
  headers: { 'Authorization': `Bearer ${key}`, 'Content-Type': 'application/json' },
  body: JSON.stringify({ input }),
});
let job = await createRes.json();
if (!createRes.ok) throw new Error(job?.detail || job?.error?.message || `HTTP ${createRes.status}`);

const POLL_MS = 2500, TIMEOUT_MS = 10 * 60 * 1000, t0 = Date.now();
while (!['succeeded', 'completed', 'failed', 'canceled'].includes(job.status)) {
  if (Date.now() - t0 > TIMEOUT_MS)
    throw new Error(`Still running after 10 min. Job ${job.id} — check the provider dashboard.`);
  await new Promise(r => setTimeout(r, POLL_MS));
  job = await (await fetch(pollUrl, { headers: { 'Authorization': `Bearer ${key}` } })).json();
  setStatus('running', `Generating… (${job.status}, ${Math.round((Date.now() - t0) / 1000)}s)`);
}

Details that matter:

  • If you're polling through a proxy, watch for absolute poll URLs in the create response — rewrite them onto your proxy base.
  • On timeout, include the job ID and the provider's dashboard URL in the error so the user's work (and money) isn't lost.
  • Some APIs offer a sync shortcut (e.g. a Prefer: wait header) that blocks the create call until done — ideal for fast/cheap models, no polling loop at all.
  • On rate-limit errors, retry with escalating backoff and narrate it in the UI.

Structured output: use the API's schema mechanism (responseMimeType: 'application/json' + responseSchema, or the provider's equivalent) and defensively strip markdown fences before parsing:

text = text.trim().replace(/^```(?:json)?\s*/, '').replace(/\s*```$/, '');
const data = JSON.parse(text);

Media in: FileReader.readAsDataURL(file) then .split(',')[1] for base64 payloads; inline data URIs are fine to ~9MB; above that, use the provider's file-upload endpoint (multipart FormData — set no Content-Type header, the browser adds the boundary) or a small public media host, and pass URLs.

Every API has quirks. Undocumented input rules, error codes that mean "your prompt didn't reference the attachment", response shapes that vary between versions. Expect them: log raw errors somewhere visible, humanize them for users, and when a working prototype exists, copy its integration code rather than re-deriving it.

Cheap draft → expensive final is the strongest product pattern in this practice: parse/plan with a fast text model, generate approval drafts on the cheap tier, spend on the premium model only for keepers. Track which model made each result; show per-model costs in the picker when known. Related: run batches with Promise.allSettled so one failure doesn't kill the rest, and model each generation as a job card ({id, status, prompt, config, result, error, timestamps}) rendered as a history list.

Prompt engineering lives in code: named template constants, a composePrompt() that builds the final prompt from UI state, a live preview of the composed prompt, and lint checks for the API's known input rules with a one-click scaffold fix.

The proxy, when you need one

A CORS proxy is ~65 lines of zero-dependency Node — copy one from an existing prototype repo if available. The anatomy:

// node proxy.mjs — relay /api/* to the real API host, adding CORS
import http from 'node:http';
import https from 'node:https';

http.createServer((req, res) => {
  res.setHeader('access-control-allow-origin', '*');
  res.setHeader('access-control-allow-methods', 'GET, POST, DELETE, OPTIONS');
  res.setHeader('access-control-allow-headers', 'Authorization, Content-Type, Accept, Prefer');
  if (req.method === 'OPTIONS') { res.writeHead(204); return res.end(); }  // answer preflight ourselves

  const upstream = https.request({
    hostname: 'api.example.com',
    path: req.url.replace(/^\/api/, '/v1'),
    method: req.method,
    headers: { 'content-type': req.headers['content-type'] || 'application/json',
               'authorization': req.headers.authorization || '' },  // pass the CLIENT's key through
  }, (up) => { res.writeHead(up.statusCode, up.headers); up.pipe(res); });
  req.pipe(upstream);
}).listen(3001, () => console.log('Proxy running at http://localhost:3001/api/*'));

Principles: the proxy never holds keys (it forwards the browser's own Authorization header); it answers OPTIONS preflight itself; it strips host/origin/referer/accept-encoding before forwarding; it can double as the static file server so one command runs everything. For always-on plumbing or public-URL media hosting, promote the same logic to a deployed worker (Cloudflare Workers + R2 works well) and put the setup instructions in the worker file's header comment — the deployment doc lives in the code.

Media techniques worth knowing

  • Canvas → video ("bake"): drive an animation in real time with requestAnimationFrame, record via canvas.captureStream(30) + MediaRecorder. Negotiate MIME best-first (video/mp4;codecs=avc1.42E01E → … → video/webm) with MediaRecorder.isTypeSupported — support diverges across browsers. Stop the recorder ~150ms after the last frame so it flushes.
  • Downloads: const a = document.createElement('a'); a.download = name; a.href = url; a.click(); remote files via fetch → blob → URL.createObjectURL (and revoke after). Sanitize filenames with name.replace(/[^a-z0-9]/gi, '_').
  • Drag-drop upload: dragover preventDefault + highlight class; drop reads e.dataTransfer.files[0]; pair with a hidden <input type="file">, resetting e.target.value = '' so re-selecting the same file fires.
  • img.crossOrigin = 'anonymous' before canvas-reading any remote image, or the canvas taints.
  • Timeline/drag UIs: absolutely-positioned blocks in a scrollable track, timeToPx/pxToTime converters, Pointer Events + setPointerCapture, one global rAF tick for playhead/redraws — and never re-render the DOM node you pointer-captured mid-drag.
  • Virtual trimming: a selection is just {start, end}; loop a normal <video> via timeupdate. No re-encode needed for a prototype.
  • Webcam/mic: getUserMedia + MediaRecorder → blob → base64 → send to a multimodal model. Voice-input-as-prompt (record → transcribe → use as the prompt) is a reliably delightful feature.

Shipping

  • Filenames: lowercase-with-hyphens that say what the thing does (voice-comic-generator.html). Remixes live beside their originals with descriptive names — remixing is the point, encourage it.
  • A directory page: if the collection grows, keep a plain static index.html linking every prototype with a one-paragraph description, tags, and a "needs local plumbing" flag. Hand-edited is fine.
  • A short README per batch: what each prototype does, how it works, the exact run commands.
  • Verify in a real browser before calling it done. Serve the folder, open the page, exercise the main flow end to end with a real key. There is no test suite; the browser is the test.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment