How We Hosted 10 Interactive 3D & Simulation Workbenches Inside One Cloudflare Workers App Without Blowing the Bundle

2026-12-05来源 dev.toEnglish
How We Hosted 10 Interactive 3D & Simulation Workbenches Inside One Cloudflare Workers App Without Blowing the Bundle

The short answer: if you want to serve ten heavy, browser-native 3D and simulation workspaces from a single full-stack Cloudflare Workers application, keep every rendering engine strictly behind a client-only dynamic adapter boundary. Server-render the metadata, access rules, and curriculum shell at the edge; lazy-load Three.js, physics loops, and course data into isolated client chunks only after hydration.

That single architectural boundary is what allowed us to ship See It. Know It.—an interactive visual learning platform currently hosting 10 live courses and 234 interactive lessons spanning mechanical engineering, home electricity, Arduino/ESP32 robotics, seismic waves, networking protocols, distributed systems, algorithms, and Bitcoin cryptography—inside one TanStack Start + Cloudflare Workers codebase without tripping over Worker isolate memory limits or breaking SSR.

The Real Engineering Constraint: Heavy Client Engines Meet Lean Edge Isolates

Most interactive learning demos live on standalone single-page sites. When you build one 3D car engine viewer or one network packet visualizer, bundling Three.js into the root entry point is annoying but survivable.

Things change quickly when ten distinct interactive workbenches share one domain, one authentication system, one database, and one checkout flow:

  • Spark to Wheels (32 lessons): interactive 3D combustion, transmission, differential, and suspension models.
  • How It's Wired (37 lessons): 3D home electrical panels, breakers, RCD fault simulations, and switching circuits.
  • Learn Arduino (16 lessons), RoverKit (10 stages), and Robotics Lab (12 lessons): 3D microcontrollers, autonomous robot car assembly, and cel-shaded PCB workbenches.
  • Earthquake Simulator (6 free lessons): 3D geological fault cutaway, P/S/Love/Rayleigh seismic wave particle motion, and building resonance charts.
  • Protocol Explorer (39 lessons), Designed to Scale (40 lessons), Byte-Sized Algorithms (24 lessons), and Learn Bitcoin (18 labs using real cryptographic primitives via @noble/curves).

At the same time, our backend runs on TanStack Start (Vite 8 + @cloudflare/vite-plugin) deployed to Cloudflare Workers (workerd) with Cloudflare D1 (SQLite + Drizzle ORM) and Better Auth. Cloudflare Workers isolates operate within tight memory budgets (128 MB baseline per isolate) and do not expose browser globals like window, document, HTMLCanvasElement, or WebGL contexts.

If even one course accidentally pulls Three.js or a large lesson dataset into the server bundle:

  1. SSR crashes on missing DOM/WebGL globals, or forces fragile shims.
  2. The Worker bundle balloons, increasing memory pressure under concurrent requests.
  3. Learners visiting the homepage or reading a course overview download megabytes of unrelated 3D geometry for courses they never opened.

The Unified Shell + Dynamic Adapter Pattern

Instead of maintaining ten separate micro-frontends or ten custom route implementations, we unified every course page behind a single route (src/routes/{-$locale}.courses.$slug.tsx) and a single client shell (CoursePlayerShell).

The key file is components/courses/course-loader.ts, which defines a strict contract (CourseAdapterProps) and a lazy loader map (ADAPTER_LOADERS):

import type { ComponentType } from 'react'; export interface CourseAdapterProps { courseSlug: string; unlocked: boolean; freeLessonCount: number; courseLang: string; onRequestUpgrade: (lessonId?: string) => void; requestedLessonId?: string | null; } export type CourseAdapterComponent = ComponentType<CourseAdapterProps>; type AdapterLoader = () => Promise<{ default: CourseAdapterComponent }>; const ADAPTER_LOADERS: Record<string, AdapterLoader> = { 'spark-to-wheels': () => import('./adapters/spark-adapter'), 'how-its-wired': () => import('./adapters/wired-adapter'), 'learn-arduino': () => import('./adapters/arduino-adapter'), roverkit: () => import('./adapters/rover-adapter'), 'protocol-explorer': () => import('./adapters/protocol-adapter'), 'learn-bitcoin': () => import('./adapters/bitcoin-adapter'), 'designed-to-scale': () => import('./adapters/design-adapter'), 'robotics-lab': () => import('./adapters/robotics-adapter'), 'byte-sized-algorithms': () => import('./adapters/algorithms-adapter'), 'earthquake-simulator': () => import('./adapters/earthquake-adapter'), }; export function getCourseAdapterLoader(slug: string): AdapterLoader | null { return ADAPTER_LOADERS[slug] ?? null; } 

Notice what this contract accomplishes:

  • Static analyzability for Vite 8: Because every dynamic import() path is a static string literal, Vite cleanly splits each course—its Three.js builders, shaders, lesson text, and localized dictionaries—into its own Rollup/Rolldown client chunk.
  • Zero SSR contamination: CoursePlayerShell invokes getCourseAdapterLoader(course.slug) strictly inside a client-side useEffect hook. During SSR on Cloudflare Workers, the adapter code never executes and is never pulled into the server graph.
  • Uniform platform capabilities: Every adapter receives the exact same props for entitlement state (unlocked, freeLessonCount), active in-course language (courseLang), upgrade triggers (onRequestUpgrade), and deep-linked lessons (requestedLessonId).

Diagram of the request and rendering pipeline separating edge SSR metadata and access checks from client-side dynamic adapter chunk loading and Three.js WebGL initialization

Handling Race Conditions and Cleanup on Course Navigation

When a learner jumps quickly from Protocol Explorer to Spark to Wheels and then to Earthquake Simulator, async chunk loading can resolve out of order. A naive setState inside .then() would mount the wrong workbench on top of the current route.

Inside CoursePlayerShell, we guard adapter state with both a cancellation flag and a slug-tagged state object:

const [adapter, setAdapter] = useState<{ slug: string; Component: CourseAdapterComponent; } | null>(null); const AdapterComponent = adapter?.slug === course.slug ? adapter.Component : null; useEffect(() => { let active = true; setAdapter(null); setAdapterError(null); const loader = getCourseAdapterLoader(course.slug); if (!loader) { setAdapterError('Interactive workspace is being connected for this course.'); return; } loader() .then((mod) => { if (active) setAdapter({ slug: course.slug, Component: mod.default }); }) .catch((err) => { console.error(`[course-loader] Failed loading ${course.slug}:`, err); if (active) setAdapterError('Could not load the interactive 3D workspace. Please reload.'); }); return () => { active = false; }; }, [course.slug]); 

Tagging adapter with { slug, Component } ensures that even during synchronous React transitions before the effect cleans up, the shell never renders the previous course's component against the new course's props.

Keeping Three.js Resilient Inside React 19

Even after isolating the course chunk on the client, Three.js scenes need careful lifecycle management inside React:

  1. Mount only when <canvas> exists and clean up WebGL resources: In EarthquakeStage3D, the Three.js scene controller is instantiated asynchronously on mount and disposed on unmount so navigating between courses does not leak WebGL contexts.
  2. Keep high-frequency updates out of React re-renders: Projected 2D annotation pins over a 3D geological block move every frame when the user orbits the camera. Instead of storing 60 FPS coordinates in React state, we push frame updates directly to pin DOM refs and run a lightweight vertical de-overlapping pass (deoverlapPins) so labels stay legible without triggering React reconciliation loops.
  3. Respect prefers-reduced-motion and provide a graceful fallback: If WebGL initialization fails on a restricted device or headless browser, the stage switches to a fallback state rather than crashing the surrounding lesson text and charts.

Technical illustration contrasting a monolithic WebGL bundle with a clean client-side Three.js canvas lifecycle featuring ref-driven 2D annotation overlays and graceful fallback handling

What Lives on the Edge Server Instead?

Keeping the 3D engine off the server does not mean the server sits idle. On every request, our Cloudflare Worker handles:

  • SSR HTML and SEO metadata: Each course route renders complete structured metadata, curriculum highlights, and explanatory sections (CourseSeoSection) directly from config/courses.ts, so search engines and readers see meaningful content before the 3D chunk finishes downloading.
  • Single-source-of-truth access control: lib/course-access.ts evaluates whether a learner has full access (free course like Earthquake Simulator, active subscription, admin complimentary grant, or verified $4.99 single-course purchase) or the default first 3 free lessons.
  • Privacy-friendly analytics: A lightweight POST /api/courses/$slug/view endpoint records workspace views only after the client adapter actually loads—never counting raw SSR crawls—and deduplicates anonymous viewers via a local random UUID with zero IP addresses or browser fingerprints stored.
  • Runtime configuration from D1: Featured courses, hidden slugs, single-course pricing, and subscription settings live in Cloudflare D1 (site_settings), taking effect immediately without redeploying the Worker.

Lessons Worth Remembering Before You Build Your Own Multi-Workbench App

  1. Draw the SSR/WebGL boundary early, not after bundle bloat hits. Once Three.js imports creep into shared utility modules, untangling them from server routes is painful.
  2. Standardize the adapter interface before course #3. Defining CourseAdapterProps once meant adding our 10th course (Earthquake Simulator) required zero changes to authentication, billing, fullscreen handling, or analytics.
  3. Measure real client load, not just SSR TTFB. Fast edge HTML is great, but learners care about how quickly the 3D canvas becomes interactive. Isolating per-course chunks keeps each course's download strictly proportional to what the user actually clicked.
  4. Never gate your best demo behind a login wall. Letting anyone open the first 3 lessons of every course—or the entire Earthquake Simulator—directly in the browser lets the engineering speak for itself.

If you want to poke around the live 3D workbenches and see how fast the edge shell hands off to the client canvas, you can try any course free in your browser at See It. Know It..

原文:https://www.a8q9.cn/en/article/how-we-hosted-10-interactive-3d-simulation-workbenches-inside-one-cloudflare-wor-1206c3.html

相关文章