Unity WebGL
React
Next.js
TypeScript
WebAssembly
JavaScript Interop
Game Engineering

Unity WebGL Integration with React and Next.js: Lifecycle, C# Interop & Memory Cleanup

16 min read
Eshan Naithani

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 CriterionPattern A: Isolated Click-to-Load <iframe>Pattern B: Direct React <canvas> (createUnityInstance)
Memory Reclamation on UnmountBrowsing-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 SafetyIsolates 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 IsolationUnity 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# CommunicationVia window.parent.postMessage() and window.addEventListener("message").Direct unityInstance.SendMessage() and .jslib CustomEvent / window callbacks.
Best Use CasePortfolio 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/:

TEXT
public/
└── webgl/
    └── ai-npc-system/
        ├── index.html                  # Standalone Unity HTML host (used by Pattern A iframe)
        ├── TemplateData/               # CSS & static template icons
        └── Build/
            ├── NPC.loader.js           # 27 KB JS bootstrapper (used by both patterns)
            ├── NPC.framework.js.br     # 76 KB Brotli-compressed Emscripten runtime
            ├── NPC.data.br             # 5.17 MB Brotli-compressed scenes & assets
            └── NPC.wasm.br             # 8.43 MB Brotli-compressed WebAssembly binary

[!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-demo rather than NPC ) 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:

TYPESCRIPT
// next.config.ts
import type { NextConfig } from "next";

const nextConfig: NextConfig = {
  async headers() {
    return [
      // CORS headers if serving builds across subdomains or external embeds
      {
        source: "/webgl/:project/Build/:path*",
        headers: [
          { key: "Access-Control-Allow-Origin", value: "*" },
          {
            key: "Access-Control-Expose-Headers",
            value: "Content-Length, Content-Encoding",
          },
        ],
      },
      // Brotli-compressed WebAssembly binary (.wasm.br)
      {
        source: "/webgl/:project/Build/:file*.wasm.br",
        headers: [
          { key: "Content-Type", value: "application/wasm" },
          { key: "Content-Encoding", value: "br" },
          { key: "Cache-Control", value: "public, max-age=31536000, immutable" },
        ],
      },
      // Brotli-compressed Emscripten framework (.framework.js.br)
      {
        source: "/webgl/:project/Build/:file*.js.br",
        headers: [
          { key: "Content-Type", value: "application/javascript" },
          { key: "Content-Encoding", value: "br" },
          { key: "Cache-Control", value: "public, max-age=31536000, immutable" },
        ],
      },
      // Brotli-compressed asset data archive (.data.br)
      {
        source: "/webgl/:project/Build/:file*.data.br",
        headers: [
          { key: "Content-Type", value: "application/octet-stream" },
          { key: "Content-Encoding", value: "br" },
          { key: "Cache-Control", value: "public, max-age=31536000, immutable" },
        ],
      },
    ];
  },
};

export default nextConfig;

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:

TSX
"use client";

import { useState, useEffect, useRef } from "react";
import { Maximize2, Loader2, AlertTriangle, PlayCircle } from "lucide-react";
import { Button } from "@/components/ui/button";
import { AspectRatio } from "@/components/ui/aspect-ratio";

interface WebGLEmbedProps {
  buildUrl: string; // e.g., "/webgl/ai-npc-system/index.html"
  title: string;
}

export function WebGLEmbed({ buildUrl, title }: WebGLEmbedProps) {
  const [hasStarted, setHasStarted] = useState(false);
  const [isLoading, setIsLoading] = useState(true);
  const [hasError, setHasError] = useState(false);
  const iframeRef = useRef<HTMLIFrameElement | null>(null);

  useEffect(() => {
    if (!hasStarted) return;

    // Listen for optional readiness message posted from inside the Unity iframe
    const handleMessage = (event: MessageEvent) => {
      if (event.origin !== window.location.origin) return;
      if (event.data?.type === "UNITY_READY") {
        setIsLoading(false);
      }
    };

    window.addEventListener("message", handleMessage);
    return () => window.removeEventListener("message", handleMessage);
  }, [hasStarted]);

  const toggleFullscreen = () => {
    const iframe = iframeRef.current;
    if (!iframe) return;

    if (iframe.requestFullscreen) {
      iframe.requestFullscreen();
    } else if ((iframe as unknown as { webkitRequestFullscreen?: () => void }).webkitRequestFullscreen) {
      (iframe as unknown as { webkitRequestFullscreen: () => void }).webkitRequestFullscreen();
    }
  };

  return (
    <div className="relative w-full rounded-xl overflow-hidden border border-border bg-black shadow-2xl group">
      <AspectRatio ratio={16 / 9} className="relative bg-zinc-950">
        {!hasStarted && (
          <div className="absolute inset-0 z-30 flex flex-col items-center justify-center bg-zinc-900/90">
            <button
              type="button"
              onClick={() => setHasStarted(true)}
              className="flex flex-col items-center group/play cursor-pointer focus:outline-none"
            >
              <div className="w-20 h-20 rounded-full bg-primary/10 border border-primary/30 flex items-center justify-center mb-4 group-hover/play:scale-110 transition-transform">
                <PlayCircle className="w-10 h-10 text-primary" />
              </div>
              <span className="text-xl font-bold text-white mb-1">Load Interactive Demo</span>
              <span className="text-xs text-muted-foreground">
                Click to initialize the Unity WebGL runtime (~14 MB Brotli).
              </span>
            </button>
          </div>
        )}

        {hasStarted && isLoading && !hasError && (
          <div className="absolute inset-0 z-10 flex flex-col items-center justify-center bg-zinc-950 text-primary">
            <Loader2 className="w-10 h-10 animate-spin mb-3" />
            <p className="text-base font-medium">Loading {title} Engine...</p>
          </div>
        )}

        {hasStarted && hasError && (
          <div className="absolute inset-0 z-10 flex flex-col items-center justify-center bg-zinc-950 text-destructive">
            <AlertTriangle className="w-10 h-10 mb-3" />
            <p className="text-base font-medium">Failed to load WebGL build.</p>
          </div>
        )}

        {hasStarted && (
          <iframe
            ref={iframeRef}
            src={buildUrl}
            title={title}
            className={`w-full h-full border-0 transition-opacity duration-500 ${
              isLoading ? "opacity-0" : "opacity-100"
            }`}
            onLoad={() => setIsLoading(false)}
            onError={() => {
              setIsLoading(false);
              setHasError(true);
            }}
            allow="autoplay; fullscreen; vr"
            scrolling="no"
          />
        )}

        {hasStarted && !isLoading && !hasError && (
          <div className="absolute bottom-4 right-4 z-20 opacity-0 group-hover:opacity-100 transition-opacity">
            <Button
              variant="secondary"
              size="icon"
              onClick={toggleFullscreen}
              title="Fullscreen"
            >
              <Maximize2 className="h-5 w-5" />
            </Button>
          </div>
        )}
      </AspectRatio>
    </div>
  );
}

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

  1. 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 createUnityInstance without a cancellation guard, two WebAssembly instances initialize concurrently on the same <canvas>, crashing with WebGL context lost or abort(OOM).
  2. Unmounting Mid-Download: createUnityInstance(canvas, config, onProgress) returns a Promise<UnityInstance> that resolves only after the .wasm and .data files finish downloading and Scene 0 initializes. If the user clicks a Next.js <Link> to navigate away while loading is at 50%, unityInstanceRef.current is still null when the useEffect cleanup function runs! You must set an isCancelled flag and, inside the .then(instance => ...) resolution handler, immediately call instance.Quit() if the component unmounted while loading was in flight.

Here is the complete, leak-safe TypeScript implementation (UnityDirectCanvas.tsx):

TSX
"use client";

import React, { useEffect, useRef, useState, useCallback } from "react";

export interface UnityInstance {
  SendMessage: (gameObjectName: string, methodName: string, value?: string | number) => void;
  SetFullscreen: (fullscreen: 0 | 1) => void;
  Quit: () => Promise<void>;
}

interface UnityConfig {
  dataUrl: string;
  frameworkUrl: string;
  codeUrl: string;
  streamingAssetsUrl?: string;
  companyName?: string;
  productName?: string;
  productVersion?: string;
  devicePixelRatio?: number;
  matchWebGLToCanvasSize?: boolean;
}

declare global {
  interface Window {
    createUnityInstance?: (
      canvas: HTMLCanvasElement,
      config: UnityConfig,
      onProgress?: (progress: number) => void
    ) => Promise<UnityInstance>;
  }
}

interface UnityDirectCanvasProps {
  loaderUrl: string;     // e.g., "/webgl/my-game/Build/Game.loader.js"
  dataUrl: string;       // e.g., "/webgl/my-game/Build/Game.data.br"
  frameworkUrl: string;  // e.g., "/webgl/my-game/Build/Game.framework.js.br"
  codeUrl: string;       // e.g., "/webgl/my-game/Build/Game.wasm.br"
  productName: string;
  productVersion?: string;
  onInstanceReady?: (instance: UnityInstance) => void;
}

export function UnityDirectCanvas({
  loaderUrl,
  dataUrl,
  frameworkUrl,
  codeUrl,
  productName,
  productVersion = "1.0.0",
  onInstanceReady,
}: UnityDirectCanvasProps) {
  const canvasRef = useRef<HTMLCanvasElement | null>(null);
  const instanceRef = useRef<UnityInstance | null>(null);
  const [progress, setProgress] = useState<number>(0);
  const [isLoaded, setIsLoaded] = useState<boolean>(false);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    let isUnmounted = false;
    let scriptElement: HTMLScriptElement | null = null;

    const initUnity = async () => {
      if (!canvasRef.current || !window.createUnityInstance) return;

      const isMobile = /iPhone|iPad|iPod|Android/i.test(navigator.userAgent);
      const config: UnityConfig = {
        dataUrl,
        frameworkUrl,
        codeUrl,
        streamingAssetsUrl: "StreamingAssets",
        companyName: "EshanNaithani",
        productName,
        productVersion,
        // Clamp devicePixelRatio to prevent 3x Retina framebuffer memory bloat
        devicePixelRatio: Math.min(window.devicePixelRatio || 1, isMobile ? 1.5 : 2.0),
      };

      try {
        const instance = await window.createUnityInstance(
          canvasRef.current,
          config,
          (p) => {
            if (!isUnmounted) {
              setProgress(Math.round(p * 100));
            }
          }
        );

        // Critical Guard: If the user navigated away in Next.js before loading finished,
        // immediately terminate the newly created instance so it doesn't leak in the background.
        if (isUnmounted) {
          await instance.Quit();
          return;
        }

        instanceRef.current = instance;
        setIsLoaded(true);
        onInstanceReady?.(instance);
      } catch (err) {
        if (!isUnmounted) {
          setError(err instanceof Error ? err.message : String(err));
        }
      }
    };

    // Load the Unity .loader.js script if not already present on window
    if (typeof window.createUnityInstance === "function") {
      initUnity();
    } else {
      scriptElement = document.createElement("script");
      scriptElement.src = loaderUrl;
      scriptElement.async = true;
      scriptElement.onload = () => {
        if (!isUnmounted) initUnity();
      };
      scriptElement.onerror = () => {
        if (!isUnmounted) setError(`Failed to load Unity loader script: ${loaderUrl}`);
      };
      document.body.appendChild(scriptElement);
    }

    // Cleanup on React component unmount or Next.js route transition
    return () => {
      isUnmounted = true;
      const activeInstance = instanceRef.current;
      instanceRef.current = null;

      if (activeInstance) {
        activeInstance.Quit().catch((quitErr) => {
          console.warn("[UnityWebGL] Error during instance.Quit():", quitErr);
        });
      }
    };
  }, [loaderUrl, dataUrl, frameworkUrl, codeUrl, productName, productVersion, onInstanceReady]);

  const sendToUnity = useCallback(
    (gameObjectName: string, methodName: string, payload?: string | number) => {
      if (instanceRef.current) {
        instanceRef.current.SendMessage(gameObjectName, methodName, payload);
      }
    },
    []
  );

  return (
    <div className="relative w-full aspect-video bg-zinc-950 rounded-xl overflow-hidden border border-border">
      {!isLoaded && !error && (
        <div className="absolute inset-0 z-10 flex flex-col items-center justify-center bg-zinc-950 text-white">
          <p className="text-sm font-medium mb-2">
            Initializing {productName} ({progress}%)
          </p>
          <div className="w-64 h-2 bg-zinc-800 rounded-full overflow-hidden">
            <div
              className="h-full bg-primary transition-all duration-150"
              style={{ width: `${progress}%` }}
            />
          </div>
        </div>
      )}

      {error && (
        <div className="absolute inset-0 z-20 flex items-center justify-center bg-zinc-950 text-destructive p-6 text-center">
          <p className="text-sm">Unity WebGL Error: {error}</p>
        </div>
      )}

      <canvas
        ref={canvasRef}
        id="unity-react-canvas"
        tabIndex={-1}
        className="w-full h-full block focus:outline-none"
      />
    </div>
  );
}

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:

TSX
import dynamic from "next/dynamic";

const UnityDirectCanvas = dynamic(
  () => import("@/components/UnityDirectCanvas").then((mod) => mod.UnityDirectCanvas),
  { 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):

JAVASCRIPT
// Assets/Plugins/WebGL/ReactBridge.jslib
mergeInto(LibraryManager.library, {
  JS_DispatchEventToReact: function (eventNamePtr, jsonPayloadPtr) {
    var eventName = UTF8ToString(eventNamePtr);
    var jsonPayload = UTF8ToString(jsonPayloadPtr);

    if (typeof window !== "undefined") {
      var parsedDetail = null;
      try {
        parsedDetail = JSON.parse(jsonPayload);
      } catch (e) {
        parsedDetail = jsonPayload;
      }

      window.dispatchEvent(
        new CustomEvent("unity-to-react", {
          detail: {
            eventName: eventName,
            data: parsedDetail
          }
        })
      );
    }
  }
});

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):

CSHARP
using System;
using System.Runtime.InteropServices;
using UnityEngine;

namespace MyGame.WebGL
{
    [Serializable]
    public struct LevelCompletedEventDto
    {
        public int levelIndex;
        public int score;
        public float durationSeconds;
    }

    public sealed class ReactBridgeManager : MonoBehaviour
    {
#if UNITY_WEBGL && !UNITY_EDITOR
        [DllImport("__Internal")]
        private static extern void JS_DispatchEventToReact(string eventName, string jsonPayload);
#endif

        private void Awake()
        {
            // Ensure GameObject name matches what React passes to unityInstance.SendMessage()
            gameObject.name = "ReactBridgeManager";
            DontDestroyOnLoad(gameObject);
        }

        /// <summary>
        /// Call from C# gameplay code to notify React components of state changes.
        /// </summary>
        public static void NotifyLevelCompleted(int levelIndex, int score, float durationSeconds)
        {
            var payload = new LevelCompletedEventDto
            {
                levelIndex = levelIndex,
                score = score,
                durationSeconds = durationSeconds
            };
            string json = JsonUtility.ToJson(payload);

#if UNITY_WEBGL && !UNITY_EDITOR
            JS_DispatchEventToReact("LEVEL_COMPLETED", json);
#else
            Debug.Log($"[ReactBridge Stub] LEVEL_COMPLETED: {json}");
#endif
        }

        /// <summary>
        /// Invoked from React via:
        /// unityInstance.SendMessage("ReactBridgeManager", "SetKeyboardCapture", 0 or 1)
        /// </summary>
        public void SetKeyboardCapture(int shouldCapture)
        {
#if UNITY_WEBGL && !UNITY_EDITOR
            WebGLInput.captureAllKeyboardInput = (shouldCapture == 1);
#endif
        }

        /// <summary>
        /// Invoked from React via:
        /// unityInstance.SendMessage("ReactBridgeManager", "ApplyConfigurationJson", jsonString)
        /// </summary>
        public void ApplyConfigurationJson(string jsonConfig)
        {
            Debug.Log($"[ReactBridge] Received config from React: {jsonConfig}");
            // Deserialize with JsonUtility.FromJson<T>(jsonConfig) and apply to gameplay systems
        }
    }
}

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:

TSX
useEffect(() => {
  const handleUnityEvent = (e: Event) => {
    const customEvent = e as CustomEvent<{ eventName: string; data: unknown }>;
    const { eventName, data } = customEvent.detail;

    if (eventName === "LEVEL_COMPLETED") {
      console.log("Unity reported level completion:", data);
      // Update React state, trigger GameAnalytics / GA4 event, or open React modal
    }
  };

  window.addEventListener("unity-to-react", handleUnityEvent);
  return () => window.removeEventListener("unity-to-react", handleUnityEvent);
}, []);

7. Troubleshooting Common React + Unity WebGL Issues

Issue / SymptomRoot CauseSolution
React <input> fields cannot be typed into while Unity is loadedUnity's WebGLInput.captureAllKeyboardInput defaults to true, calling preventDefault() on all DOM key eventsOn 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 devReact Strict Mode runs useEffect setup → cleanup → setup twice in developmentGuard 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 buildComponent touches window or navigator during Next.js static prerenderingAdd "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

Need help architecting or optimizing your Unity mobile game? Let's discuss your technical roadmap.

Share this article

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