Building Responsive Web Apps
Always follow analyze → propose → implement. Never jump straight to code.
Minimal async-fetch pattern (use as the default data layer):
JavaScriptasync function fetchJSON(url, { signal, timeoutMs = 8000 } = {}) { const ctrl = new AbortController(); const timer = setTimeout(() => ctrl.abort(), timeoutMs); try { const res = await fetch(url, { signal: signal ?? ctrl.signal, headers: { Accept: "application/json" }, }); if (!res.ok) throw new Error(`HTTP ${res.status}`); return await res.json(); } finally { clearTimeout(timer); } }
Minimal UI state pattern (loading / error / empty / success):
JavaScriptfunction render(state) { const root = document.getElementById("app"); root.setAttribute("aria-busy", state.status === "loading"); if (state.status === "loading") root.replaceChildren(skeleton()); else if (state.status === "error") root.replaceChildren(errorView(state.error, state.retry)); else if (!state.data.length) root.replaceChildren(emptyView()); else root.replaceChildren(...state.data.map(card)); }
Copy this checklist and track progress:
Progress:
- [ ] Step 1: Analyze requirements (restate, find gaps, list assumptions)
- [ ] Step 2: Assess solutions (2-3 options, pick one, justify)
- [ ] Step 3: Present proposal and wait for confirmation if scope is ambiguous
- [ ] Step 4: Build semantic HTML + responsive CSS skeleton
- [ ] Step 5: Implement async data layer with all four UI states
- [ ] Step 6: Harden security (escaping, CSP, no secrets in client)
- [ ] Step 7: Test UI (responsive breakpoints, a11y, failure modes)
- [ ] Step 8: Summarize what was built, assumptions, and next steps
Step 1: Analyze Requirements
Output a short analysis block before any code:
- Goal: one sentence
- Users and context: who, which devices, which connection quality
- Data source: endpoint, auth, rate limits, CORS, response shape, pagination
- Constraints: no-build vs. framework, browser support, performance budget
- Assumptions: anything you're guessing; flag these explicitly
- Risks: CORS, API key exposure, rate limiting, large payloads
If the data source is unspecified, pick a well-known public API appropriate to the topic and state that choice as an assumption.
Step 2: Assess Solutions
Compare 2-3 approaches in a compact table, then recommend one:
| Option | Pros | Cons |
|---|---|---|
| Vanilla JS + CSS | Zero build, fast, easy to review | More manual DOM work |
| Lightweight lib (Alpine/Preact) | Reactive state with small footprint | Extra dependency |
| Full framework (React/Vue) | Scales for complex apps | Overkill for small tasks |
Default recommendation: vanilla JS + modern CSS for small/medium single-page UIs. Escalate to a framework only if there is routing, complex shared state, or many interactive components.
Step 3: Present Proposal
State: chosen stack, file structure, data flow, UI sections, and what will NOT be included. Keep it under ~15 lines. Proceed to implementation in the same response unless the requirements are materially ambiguous.
Step 4: Semantic HTML + Responsive CSS
- Mobile-first. Start at 320px, add
min-widthmedia queries only where layout actually breaks. - Use CSS custom properties for theming,
clamp()for fluid type, and Grid withauto-fit/minmaxfor card layouts. - Respect user preferences:
prefers-color-scheme,prefers-reduced-motion.
CSS:root { --bg: #0f1115; --fg: #e8eaed; --card: #181b21; --accent: #4f8cff; --radius: 12px; --gap: clamp(0.75rem, 2vw, 1.5rem); } @media (prefers-color-scheme: light) { :root { --bg: #f6f7f9; --fg: #14161a; --card: #fff; } } body { margin: 0; background: var(--bg); color: var(--fg); font: clamp(1rem, 0.95rem + 0.3vw, 1.125rem)/1.5 system-ui, sans-serif; } .grid { display: grid; gap: var(--gap); padding: var(--gap); grid-template-columns: repeat(auto-fit, minmax(min(100%, 260px), 1fr)); } .card { background: var(--card); border-radius: var(--radius); padding: 1rem; transition: transform .2s ease; } .card:hover { transform: translateY(-2px); } @media (prefers-reduced-motion: reduce) { * { transition: none !important; animation: none !important; } }
Step 5: Async Data Layer
Rules for every fetch:
- Timeout + abort via
AbortController. Cancel the previous request when a new one starts (search-as-you-type, filter changes). - Handle all four states: loading (skeleton, not spinner-only), error (with Retry button), empty, success.
- Debounce user-triggered requests (250-400ms).
- Cache identical GETs in memory (Map keyed by URL) to avoid redundant calls.
- Parallelize independent requests with
Promise.allSettledso one failure doesn't blank the page. - Retry transient failures (network errors, 429, 5xx) with exponential backoff, max 2-3 attempts. Never retry 4xx other than 429.
JavaScriptlet current; async function load(query) { current?.abort(); current = new AbortController(); setState({ status: "loading" }); try { const data = await fetchJSON(`${API}?q=${encodeURIComponent(query)}`, { signal: current.signal }); setState({ status: "success", data }); } catch (e) { if (e.name === "AbortError") return; // superseded, ignore setState({ status: "error", error: e, retry: () => load(query) }); } }
Step 6: Security Hardening
- Never use
innerHTMLwith API data. UsetextContent,createElement, orreplaceChildren. If HTML is unavoidable, sanitize with DOMPurify. - Encode URL params with
encodeURIComponent/URLSearchParams. - No secrets in client code. If an API needs a private key, route through a backend/proxy and say so.
- Add a CSP meta tag or header:
default-src 'self'; connect-src 'self' https://api.example.com; img-src 'self' https: data:. - Links to external sites:
rel="noopener noreferrer". - Validate response shape before rendering; don't trust fields to exist or be the expected type.
- Prefer HTTPS endpoints only.
Step 7: UI Testing
Verify and report on each:
- Responsive: 320, 768, 1280px; no horizontal scroll; tap targets at least 44px.
- States: simulate offline, slow 3G, 500 error, empty result, huge result set.
- Accessibility: keyboard-only navigation, visible focus rings,
aria-live="polite"for async updates, alt text, 4.5:1 contrast. - Performance: lazy-load images (
loading="lazy"), set imagewidth/heightto prevent layout shift.
When a test setup is warranted, provide a Playwright snippet:
JavaScripttest("shows error and retries", async ({ page }) => { await page.route("**/api/**", r => r.fulfill({ status: 500 })); await page.goto("/"); await expect(page.getByRole("alert")).toBeVisible(); await page.unroute("**/api/**"); await page.getByRole("button", { name: /retry/i }).click(); await expect(page.locator(".card").first()).toBeVisible(); });
Example 1: Input: "Build a page showing current weather for a city the user searches." Output:
- Analysis: Goal = city search → weather cards. Data = Open-Meteo (no key, CORS-enabled) with its geocoding endpoint. Assumption: metric units. Risk: ambiguous city names → show a result list.
- Proposal: Vanilla JS, single
index.html+app.js+styles.css. Debounced search, aborts stale requests, skeleton loader, error with Retry, light/dark theme. - Implementation: Complete files following Steps 4-7.
- Summary: What was built, the assumptions made, and suggested next steps (favorites via
localStorage, 5-day forecast).
Example 2:
Input: "Make a dashboard of GitHub repos for a username."
Output: Analysis flags the unauthenticated rate limit (60 req/hr) and recommends caching responses and surfacing X-RateLimit-Remaining to the user. Proposal: card grid with language badges, sorted by stars, paginated via the Link header. Implementation uses Promise.allSettled for per-repo language fetches so one failure doesn't break the grid.
- State assumptions explicitly instead of asking many questions; ask only when a wrong guess would waste significant work.
- Prefer progressive enhancement: content and layout work before JS enriches them.
- Keep state in one object and render from it; avoid scattering DOM mutations.
- Show skeletons that match final layout to prevent layout shift.
- Surface errors in human language ("Couldn't load data. Check your connection and retry."), not raw status codes.
- Keep the file count small for small apps; split into modules (
api.js,ui.js,state.js) onceapp.jspasses ~200 lines. - Use semantic elements (
<main>,<nav>,<article>,<button>) before reaching for ARIA.
- Implementing before analyzing. The proposal step is the point of this workflow; don't skip it.
- Spinner-only loading with no error or empty state, leaving users stuck on failure.
- Race conditions from not aborting stale requests, so older responses overwrite newer ones.
innerHTMLwith remote data, an XSS vector.- Embedding API keys in front-end code.
- Desktop-first CSS that gets patched for mobile with
max-widthoverrides. - Fixed pixel widths and
100vwcausing horizontal scroll. - Ignoring CORS until the end; verify the API supports browser calls during analysis, or plan a proxy.
- Unbounded fetch loops or no debounce, hammering the API and hitting rate limits.
- Div-soup buttons (
<div onclick>) that break keyboard and screen-reader access. - Over-engineering: adding a framework, bundler, or state library for a one-page data viewer.