# How to add analytics to a Three.js game

> Add the Manalens JavaScript SDK to a Three.js game built with Vite. Send level and scene events outside the render loop, and report lost WebGL contexts.

By Yos Riady. Updated 2026-11-24. Published 2026-11-24. Canonical URL: https://manalens.dev/integrations/threejs

A Three.js game sends events with the Manalens JavaScript SDK, from your own game code. There is no Three.js plugin: you create one SDK instance with the app option and call track() when the game state changes. The same code works in React Three Fiber. The with-threejs example on GitHub is a complete game built with Vite.

## Key takeaways

- A Three.js game creates one SDK instance with the app option and engine other, because there is no Three.js plugin.
- Never call track() in the setAnimationLoop() function, which runs on every frame; send events when the game state changes.
- A lost WebGL context is a canvas event, not an exception, so listen for webglcontextlost and send a critical error.

## How do I get the SDK for a Three.js game?

The Manalens JavaScript SDK is open source (MIT) on GitHub. It is not on npm yet, so install it from GitHub: npm install github:manalens/manalens-js builds the package when it installs.

1. Install the SDK from GitHub with npm install github:manalens/manalens-js.
2. Create one instance with the app option in src/analytics.ts, with your Publishable key and endpoint.
3. Call track() where the game state changes, never in the setAnimationLoop() function.
4. Send level events, asset load times, and a critical error on webglcontextlost.
5. Open the game on your project domain and check the project activity feed.

- [Manalens JavaScript SDK on GitHub](https://github.com/manalens/manalens-js)
- [Example: with-threejs](https://github.com/manalens/examples/tree/main/with-threejs)

*Install command*

```bash
npm install github:manalens/manalens-js
```

## How do I set up the SDK in a Three.js game?

Create the instance once, in its own module, and import it where the game needs it. The app option adds the platform, engine, version, and build to every event, so the App filters and errors by build work for the game. Use engine other for Three.js.

With Vite, read the Publishable key and the endpoint from VITE_ variables. Vite puts every VITE_ value in the browser bundle, so put only the Publishable key there, never a Secret key or an API key.

*src/analytics.ts*

```typescript
// src/analytics.ts
import { createAnalytics } from '@manalens/web';

export const analytics = createAnalytics({
  publishableKey: import.meta.env.VITE_MANALENS_PUBLISHABLE_KEY,
  endpoint: import.meta.env.VITE_MANALENS_ENDPOINT,
  app: { platform: 'web', engine: 'other', storefront: 'itch', app_version: '1.0.0', build: '1' },
});
```

## Why keep track() out of the render loop?

The function you pass to setAnimationLoop() runs on every frame, often 60 or more times a second. Never call track() there. Call it where the game state changes: a level starts or ends, a scene loads, the player buys an item. If the loop detects the change, set a flag in the loop and send the event once.

*Game code*

```typescript
renderer.setAnimationLoop(() => {
  world.step(clock.getDelta());
  renderer.render(scene, camera); // no track() here
});

function endLevel(level: number, attempt: number, score: number, won: boolean) {
  analytics.track(won ? 'level_complete' : 'level_fail', { level, attempt, score });
}
```

## Which game, level, and scene events should I send?

The web SDK sends page views for you, but not game events. Send the event conventions with track(): game_open at launch, session_start and session_end, and level_start, level_complete, and level_fail with level, attempt, and score. The Game KPIs and Game health dashboards count the first three. For a scene that is not a level, such as a menu or a hub, send your own snake_case event when it loads.

Page views are automatic. In a game with its own screens and no URL changes, set autoPageviews: false and send screen events with track() instead.

- [Event conventions](https://docs.manalens.dev/sdks/app-events)

*Events for a Three.js game, with their properties.*

| Event | Properties | When |
| --- | --- | --- |
| game_open | is_first_open, first_open_at | Each launch |
| session_start | none | Launch, or input after 30 minutes idle |
| session_end | duration_s | The page hides, or 30 minutes idle |
| level_start | level, attempt | A level starts |
| level_complete, level_fail | level, attempt, score | A level ends |
| error | severity, message, error_type, handled, fingerprint | An error, a failed asset, or a lost WebGL context |
| scene_loaded (your own) | scene | A menu, hub, or other scene loads |
| assets_loaded (your own) | duration_ms | The LoadingManager finishes |

*Game code*

```typescript
analytics.track('game_open', { is_first_open: true, first_open_at: new Date().toISOString() });
analytics.track('session_start');
analytics.track('level_start', { level: 1, attempt: 1 });
analytics.track('scene_loaded', { scene: 'hub' });
```

## How do I measure asset loading in Three.js?

Players who wait too long for models and textures leave before the first level. Use one LoadingManager for your loaders and send the load time when everything is loaded. A failed asset is an error event, with the asset URL as the error type, so the same missing file groups together.

*Asset loading*

```typescript
import { LoadingManager } from 'three';
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';

const startedAt = performance.now();
const manager = new LoadingManager();
manager.onLoad = () => {
  analytics.track('assets_loaded', { duration_ms: Math.round(performance.now() - startedAt) });
};
manager.onError = url => {
  analytics.track('error', { severity: 'error', message: 'Asset failed to load', error_type: url, handled: true });
};
const loader = new GLTFLoader(manager);
```

## How do I report a lost WebGL context?

The browser can take the WebGL context away after a GPU reset, a driver update, or when a page opens too many contexts. This is a canvas event, not an exception, so window error listeners never see it. Listen on the canvas and send it as a critical error, then pause the game. Three.js restores its state when the browser gives the context back.

When the tab closes, send the last events with flush(true). It uses fetch with keepalive, so the request can finish while the page unloads.

*Errors and page close*

```typescript
renderer.domElement.addEventListener('webglcontextlost', () => {
  paused = true;
  analytics.track('error', { severity: 'critical', message: 'WebGL context lost', error_type: 'WebGLContextLost', handled: true });
  void analytics.flush();
});
renderer.domElement.addEventListener('webglcontextrestored', () => { paused = false; });

window.addEventListener('pagehide', () => analytics.flush(true));
```

## How do I check that Three.js events arrive?

Serve the game over HTTPS on your project domain or a subdomain, such as play.example.com. On itch.io, *.itch.zone is in Allowed origins by default. For another game portal, add the host that serves the game frame in Project settings, Allowed origins. For a local test, use a project with the domain localhost and open the Vite dev server.

Start a level and finish it. Check that game_open, session_start, level_start, and level_complete appear in the project activity feed. Collection is queued, so allow a few seconds. Then filter by Build to check that the app context arrives.

- [How to track an HTML5 game](https://manalens.dev/integrations/html5)
- [How to track an itch.io game](https://manalens.dev/integrations/itch-io)

## Frequently asked questions

### Is there a Three.js plugin?

No. The Manalens JavaScript SDK is plain browser code with no link to a framework. Create one instance with the app option and call track() from your game code when the game state changes. The same code works in Three.js, React Three Fiber, and any other WebGL library.

### Why not track events in the animation loop?

Because the function you pass to setAnimationLoop() runs on every frame, often 60 or more times a second. One event a frame floods the queue and your reports. Call track() where the game state changes, such as a level start, a level end, or a scene load.

### How do I report a lost WebGL context?

Listen for webglcontextlost on renderer.domElement and send an error event with severity critical. It is a canvas event, not an exception, so window error listeners never see it. Pause the game until webglcontextrestored arrives, and Three.js restores its own state.

### Does it work with Vite and other bundlers?

Yes. Import createAnalytics from @manalens/web and create one instance in its own module. With Vite, read the Publishable key from a VITE_ variable. Vite puts every VITE_ value in the bundle, so never put a Secret key or an API key in one.

### Is there a complete example?

Yes. The with-threejs project in the Manalens examples repository on GitHub is a small Three.js game built with Vite. It sends game_open, the session events, level events, and errors, including a lost WebGL context. A demo mode plays by itself, so you can check a test project quickly.

## Sources

- [three.js WebGLRenderer.setAnimationLoop](https://threejs.org/docs/#api/en/renderers/WebGLRenderer.setAnimationLoop)
- [three.js LoadingManager](https://threejs.org/docs/#api/en/loaders/managers/LoadingManager)
- [MDN: webglcontextlost event](https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/webglcontextlost_event)
- [Vite: env variables and modes](https://vite.dev/guide/env-and-mode)

## Related guides

- [Example project: with-threejs](https://github.com/manalens/examples/tree/main/with-threejs)
- [How to track an HTML5 game](https://manalens.dev/integrations/html5)
- [Best analytics tools for Three.js games in 2026](https://manalens.dev/blog/best-threejs-analytics-tools)
- [Web game analytics for Poki, CrazyGames and itch.io HTML5](https://manalens.dev/blog/web-game-analytics-poki-crazygames-itch)
- [Event conventions](https://docs.manalens.dev/sdks/app-events)
