Unity WebGL Integration with React and Next.js: Lifecycle, C# Interop & Memory Cleanup
Embedding a Unity WebGL (Unity Web) build inside a modern React or Next.js App Router application requires more than dropping Unity's generated index.html script into a component. Unlike traditional multi-page websites where every link triggers a full browser page reload, React and Next.js are Single-Page Applications (SPAs) where components mount, re-render, and unmount dynamically while the browser tab stays alive.
If you initialize Unity's WebAssembly runtime (createUnityInstance) without handling Next.js Server-Side Rendering (SSR), React 18/19 Strict Mode double-mounting, in-flight async cancellation, and unityInstance.Quit() teardown, your web app will suffer from duplicated WebAssembly heaps, zombie background audio playing after route changes, hijacked HTML keyboard inputs, and mobile browser Out-Of-Memory (OOM) crashes.
In this engineering guide, we break down the exact production patterns for integrating Unity WebGL with React and Next.js—including the real click-to-load architecture used on eshannaithani.com to host our Playable Unity 6 AI NPC & NavMesh Demo.
Need an experienced engineer to build, optimize, or embed a Unity WebGL application? Explore our Unity WebGL Development & Optimization Services, or pair this tutorial with our Unity WebGL Performance Guide and WebGL Deployment Checklist.
1. Choosing the Right Architecture: <canvas> vs. Isolated <iframe>
Before writing React code, decide between the two proven architectures for hosting Unity WebGL inside a Next.js frontend:
| Architectural Criterion | Pattern A: Isolated Click-to-Load <iframe> | Pattern B: Direct React <canvas> (createUnityInstance) |
|---|---|---|
| Memory Reclamation on Unmount | Browsing-Context Isolation: Removing the <iframe> from the DOM tears down its child browsing context so the browser GC can reclaim the Wasm ArrayBuffer and WebGL context (provided the parent page removes message listeners and holds no contentWindow references). | Requires await unityInstance.Quit(): Must explicitly terminate the runtime on unmount; even after Quit(), some browser engines retain parts of the JS/Wasm heap until full tab navigation. |
| React Strict Mode Safety | Isolates Unity loader globals inside the iframe document rather than the parent React window. | Requires explicit ref guards so two Wasm heaps are not initialized concurrently on the same canvas. |
| Keyboard Focus Isolation | Unity only captures keyboard input when the iframe is focused; host page <input> forms work normally. | Unity captures all page keyboard events unless WebGLInput.captureAllKeyboardInput = false is toggled in C#. |
| React ↔ C# Communication | Via window.parent.postMessage() and window.addEventListener("message"). | Direct unityInstance.SendMessage() and .jslib CustomEvent / window callbacks. |
| Best Use Case | Portfolio demos, embedded browser games, educational sandboxes, and multi-route Next.js apps. | 3D product configurators, digital twins, and web apps where React components act as the live HUD over the 3D viewport. |
Both patterns are production-valid. Below, we implement both approaches step by step.
2. Exporting the Unity Web Build & Next.js Directory Structure
When exporting from Unity (File > Build Profiles > Web), place the build output inside your Next.js public/ directory (or on an external S3/CloudFront CDN).
For example, in this repository (eshannaithani.com), our AI NPC Behavior System WebGL Demo is structured under public/webgl/ai-npc-system/:
[!IMPORTANT] Avoid Spaces in Build Filenames: When naming your build output folder or target in Unity's Build Profile window, use URL-safe slugs (
ai-npc-demorather thanNPC) so CDN path matchers and Next.js header glob patterns do not require URL percent-encoding (%20).
3. Configuring Next.js HTTP Headers (next.config.ts)
If you export a compressed Unity WebGL build (Brotli .br or Gzip .gz / .unityweb) and serve it from Next.js (public/) or a custom Node server, the browser will fail to parse the files unless the server attaches the matching Content-Encoding and Content-Type headers.
Specifically, WebAssembly.instantiateStreaming() requires Content-Type: application/wasm on the .wasm route so the browser can compile WebAssembly bytecode while bytes are still downloading.
Here is the production headers() configuration in next.config.ts:
4. Pattern A: The Click-to-Load Sandboxed <iframe> Component (WebGLEmbed.tsx)
On pages where the playable build accompanies technical documentation—such as our AI NPC Architecture Case Study—auto-initializing WebGL on page load hurts Core Web Vitals (LCP and TBT) and triggers mobile Safari memory pressure before the visitor even scrolls to the demo.
Instead, our production src/components/WebGLEmbed.tsx component uses a Click-to-Load Gate that mounts the <iframe> only when the user clicks Load Interactive Demo, tracks the start event in analytics, and provides a fullscreen control:
5. Pattern B: Direct <canvas> Mounting & Safe Lifecycle Cleanup in React
When building a web application where React components directly overlay the Unity viewport (for example, a React inventory sidebar or telemetry inspector driving a live 3D Unity scene), mount the <canvas> directly via window.createUnityInstance.
Solving the Two Biggest React + Unity Lifecycle Bugs
- React 18/19 Strict Mode Double-Mount: In development mode, React mounts, immediately unmounts, and re-mounts every component to test cleanup resilience. If you call
createUnityInstancewithout a cancellation guard, two WebAssembly instances initialize concurrently on the same<canvas>, crashing withWebGL context lostorabort(OOM). - Unmounting Mid-Download:
createUnityInstance(canvas, config, onProgress)returns aPromise<UnityInstance>that resolves only after the.wasmand.datafiles finish downloading and Scene 0 initializes. If the user clicks a Next.js<Link>to navigate away while loading is at 50%,unityInstanceRef.currentis stillnullwhen theuseEffectcleanup function runs! You must set anisCancelledflag and, inside the.then(instance => ...)resolution handler, immediately callinstance.Quit()if the component unmounted while loading was in flight.
Here is the complete, leak-safe TypeScript implementation (UnityDirectCanvas.tsx):
Importing Dynamically in Next.js App Router (ssr: false)
To guarantee Next.js never attempts to evaluate your WebGL player during server pre-rendering, import it with next/dynamic and ssr: false:
6. Passing Data Between React (TypeScript) and Unity (C#)
Production web games and 3D tools need clean two-way communication between React state and Unity C# scripts.
1. Unity C# → React via .jslib and DOM CustomEvent
Instead of polluting the global window object with dozens of fragile callback functions, dispatch a standard browser CustomEvent from a Unity .jslib plugin (Assets/Plugins/WebGL/ReactBridge.jslib):
2. Unity C# Receiver & Sender (ReactBridgeManager.cs)
Attach this MonoBehaviour to a scene GameObject named ReactBridgeManager. It sends structured events to React via [DllImport("__Internal")] and receives calls from React via SendMessage (plus toggles WebGLInput.captureAllKeyboardInput so HTML inputs work):
3. Subscribing to Unity Events Inside React (useEffect)
In your parent React component, listen to the "unity-to-react" event and clean up the listener on unmount:
7. Troubleshooting Common React + Unity WebGL Issues
| Issue / Symptom | Root Cause | Solution |
|---|---|---|
React <input> fields cannot be typed into while Unity is loaded | Unity's WebGLInput.captureAllKeyboardInput defaults to true, calling preventDefault() on all DOM key events | On HTML input onFocus, call unityInstance.SendMessage("ReactBridgeManager", "SetKeyboardCapture", 0); on canvas click or input onBlur, pass 1. |
Game audio keeps playing after clicking a Next.js <Link> | React unmounted the <canvas> DOM element without calling unityInstance.Quit() (or unmount occurred before loading finished) | Call await instance.Quit() in the useEffect cleanup function and inside the post-load if (isUnmounted) guard (shown in Section 5). |
Two loading bars or abort(OOM) in npm run dev | React Strict Mode runs useEffect setup → cleanup → setup twice in development | Guard script injection and instance resolution with an isUnmounted boolean flag per effect lifecycle, or use the isolated <iframe> pattern (WebGLEmbed.tsx). |
ReferenceError: window is not defined during next build | Component touches window or navigator during Next.js static prerendering | Add "use client" at the top of the file and only access window inside useEffect or event handlers. |
Frequently Asked Questions
Explore Playable Case Studies & WebGL Services
- Unity 6 NPC AI System Architecture & Live WebGL Demo — See the click-to-load
WebGLEmbed.tsxarchitecture running a real Unity 6 FSM and NavMesh simulation inside this Next.js site. - Case Study: How I Built Bird Sort Mania in Unity in 20 Days — Multi-platform Android and WebGL shipping case study.
- Unity WebGL Performance Guide: Wasm, Memory & Caching — Deep dive into WebAssembly streaming compilation, Brotli compression, and IndexedDB caching.
- Unity WebGL Performance & Deployment Checklist — Pre-release QA checklist and benchmark templates.
- Unity WebGL Development & Optimization Services — Hire a specialist to embed Unity WebGL into your React/Next.js product, shrink download sizes, and eliminate mobile browser crashes.
Get Practical Unity Development Insights
Technical guides on Unity performance, AI gameplay systems, mobile monetization, and game development.
Unsubscribe at any time. Your data is never shared.
Recommended Reading
More articles in Unity WebGL
Unity WebGL Performance & Deployment Checklist
A complete, bookmarkable pre-launch checklist for Unity WebGL games covering Player Settings, Brotli CDN headers, memory budgets, browser compatibility matrices, and before/after benchmark templates.
Unity WebGL Performance Guide: Reduce Load Time & Memory Usage
An engineering guide to Unity WebGL performance covering WebAssembly streaming compilation, Brotli HTTP headers, IndexedDB caching, GPU texture compression, .jslib interop, and browser memory profiling.
Unity WebGL Game Optimization Guide: Tuning Size & Performance for Browser Portals
A comprehensive guide on optimizing Unity WebGL browser games for GamePix, Poki, and CrazyGames. Master sub-15MB initial loader shells, Wasm code stripping, Basis Universal textures, and Addressable streaming.