Hyve Phaser Plugin
The Hyve Phaser Plugin seamlessly integrates Phaser 3 games with the Hyve platform. It automatically handles authentication and provides two core features:
- Persistent Game Data: Save player progress, settings, and scores to cloud or local storage
- Telemetry Tracking: Track game events and player actions for analytics
Authentication happens automatically when your game loads - no manual setup required.
Installation
npm install @hyve-sdk/phaser
# or
pnpm add @hyve-sdk/phaser
# or
yarn add @hyve-sdk/phaser
Quick Setup
Add the plugin to your Phaser game configuration:
import { AUTO, Game } from "phaser";
import HyvePhaserPlugin from "@hyve-sdk/phaser";
import { MainScene } from "./scenes/MainScene";
const config: Phaser.Types.Core.GameConfig = {
type: AUTO,
width: 800,
height: 600,
parent: "game-container",
plugins: {
global: [{
key: "HyvePhaserPlugin",
plugin: HyvePhaserPlugin,
start: true,
data: {
isDev: true, // Use dev or prod environment
debug: true, // Enable debug logging
storageMode: 'cloud' // Default storage: 'cloud' or 'local'
}
}]
},
scene: [MainScene]
};
export default new Game(config);
Configuration Options
| Option | Type | Default | Description |
|---|---|---|---|
isDev | boolean | true | Use development (localhost:8081) or production environment |
debug | boolean | false | Enable console logging |
storageMode | 'cloud' | 'local' | 'cloud' | Default storage for game data (can be overridden per call) |
Authentication (Automatic)
The plugin handles authentication automatically - do not call authentication methods manually.
Required URL Parameters
Your game must be loaded with these URL parameters:
https://yourgame.com?hyve-access=JWT_TOKEN&game-id=YOUR_GAME_ID
| Parameter | Description |
|---|---|
hyve-access | JWT authentication token from Hyve platform |
game-id | Your game's unique identifier |
What Happens Automatically
When your game loads:
- Plugin extracts JWT token and game ID from URL
- User is authenticated (backend validates JWT)
- All telemetry and API calls are automatically authenticated
- User ID is extracted from JWT by the backend
Checking Authentication Status (Optional)
const hyve = this.plugins.get('HyvePhaserPlugin');
if (hyve.isAuthenticated()) {
console.log('User ID:', hyve.getUserId());
console.log('Game ID:', hyve.getGameId());
}
Persistent Game Data
Save player progress, settings, and scores with cloud or local storage. All data is automatically scoped to your game and the authenticated user.
Storage Modes
| Mode | Syncs Cross-Device | Requires Auth | Works Offline | Use For |
|---|---|---|---|---|
cloud | ✅ Yes | ✅ Yes | ❌ No | Progress, high scores, unlocks |
local | ❌ No | ❌ No | ✅ Yes | Settings, preferences |
Basic Usage
const hyve = this.plugins.get('HyvePhaserPlugin');
// Save to cloud (syncs across devices)
await hyve.saveGameData('high_score', 1500, 'cloud');
await hyve.saveGameData('current_level', 10, 'cloud');
// Save locally (device-specific, works offline)
await hyve.saveGameData('sound_enabled', true, 'local');
await hyve.saveGameData('graphics_quality', 'high', 'local');
// Get saved data
const scoreData = await hyve.getGameData('high_score', 'cloud');
if (scoreData) {
console.log('High score:', scoreData.value);
}
Save Complex Data
Store any JSON-serializable value: numbers, strings, booleans, arrays, or objects.
// Save array
await hyve.saveGameData('unlocked_levels', [1, 2, 3, 5, 8], 'cloud');
// Save object
await hyve.saveGameData('player_progress', {
level: 10,
xp: 2500,
coins: 150,
achievements: ['first_win', 'speed_demon']
}, 'cloud');
Batch Operations
Save or retrieve multiple values at once (max 100 per batch).
// Batch save
await hyve.batchSaveGameData([
{ key: 'level_1_score', value: 1000 },
{ key: 'level_2_score', value: 1500 },
{ key: 'level_3_score', value: 2000 }
], 'cloud');
// Batch get
const scores = await hyve.getMultipleGameData([
'level_1_score',
'level_2_score',
'level_3_score'
], 'cloud');
Complete Example
export class GameScene extends Scene {
private hyve!: HyvePhaserPlugin;
private score: number = 0;
private highScore: number = 0;
async create() {
this.hyve = this.plugins.get('HyvePhaserPlugin') as HyvePhaserPlugin;
await this.loadGameData();
}
async loadGameData() {
// Load high score from cloud
const scoreData = await this.hyve.getGameData('high_score', 'cloud');
if (scoreData) {
this.highScore = scoreData.value;
}
// Load settings from local storage
const settingsData = await this.hyve.getGameData('settings', 'local');
if (settingsData) {
this.applySettings(settingsData.value);
}
}
updateScore(points: number) {
this.score += points;
// Auto-save new high score to cloud
if (this.score > this.highScore) {
this.highScore = this.score;
this.hyve.saveGameData('high_score', this.highScore, 'cloud');
}
}
}
Telemetry Tracking
Track game events and player actions for analytics. All events are automatically authenticated and linked to the player.
Basic Usage
const hyve = this.plugins.get('HyvePhaserPlugin');
// Simple event
await hyve.sendTelemetry('game', 'player', 'jump');
// Event with details
await hyve.sendTelemetry(
'game', // location
'player', // category
'jump', // action
'double_jump', // subCategory (optional)
'successful', // subAction (optional)
{ key: 'space' }, // eventDetails (optional)
{ height: 200 }, // customData (optional)
'web' // platformId (optional)
);
Common Event Examples
const hyve = this.plugins.get('HyvePhaserPlugin');
// Game start
await hyve.sendTelemetry('game', 'gameplay', 'start', 'level_1', null, null,
{ mode: 'campaign', difficulty: 'normal' }, 'web');
// Level complete
await hyve.sendTelemetry('game', 'level', 'complete', `level_${levelNum}`, null, null,
{ score: this.score, stars: 3, time: levelTime }, 'web');
// Player action
await hyve.sendTelemetry('game', 'player', 'collect', 'power_up', 'speed_boost',
{ method: 'collision' }, { item_id: 'speed_001', value: 50 }, 'web');
// UI interaction
await hyve.sendTelemetry('ui', 'button', 'click', 'main_menu', 'start_game',
{ button_id: 'btn_start' }, null, 'web');
// Performance tracking
await hyve.sendTelemetry('game', 'performance', 'fps_check', null, null, null,
{ fps: Math.round(this.game.loop.actualFps) }, 'web');
API Reference
Core Methods
| Method | Returns | Description |
|---|---|---|
isAuthenticated() | boolean | Check if user is authenticated |
getUserId() | string | null | Get authenticated user's ID |
getGameId() | string | null | Get the game ID from URL |
sendTelemetry(...) | Promise<boolean> | Send telemetry event (see Telemetry section) |
saveGameData(key, value, storage?) | Promise<Response> | Save persistent data |
getGameData(key, storage?) | Promise<GameDataItem | null> | Get persistent data |
batchSaveGameData(items, storage?) | Promise<Response> | Save multiple values (max 100) |
getMultipleGameData(keys, storage?) | Promise<GameDataItem[]> | Get multiple values |
deleteGameData(key, storage?) | Promise<boolean> | Delete persistent data |
callApi<T>(endpoint, options?) | Promise<T> | Make authenticated API call |
Events
import { HyveEvents } from '@hyve-sdk/phaser';
// Listen for plugin ready
this.game.events.on(HyveEvents.PLUGIN_READY, (plugin) => {
console.log('Plugin ready');
});
// Listen for authentication
this.game.events.on(HyveEvents.AUTHENTICATED, (event) => {
if (event.success) {
console.log('User authenticated:', event.userId);
}
});
// Listen for telemetry events
this.game.events.on(HyveEvents.TELEMETRY_SENT, (event) => {
console.log('Event tracked:', event.eventName);
});
this.game.events.on(HyveEvents.TELEMETRY_ERROR, (event) => {
console.error('Telemetry error:', event.error);
});
Available Events
PLUGIN_READY- Plugin initializedAUTHENTICATED- Authentication completedTELEMETRY_SENT- Telemetry sent successfullyTELEMETRY_ERROR- Telemetry failedAPI_CALL_SUCCESS- API call succeededAPI_CALL_ERROR- API call failed
Troubleshooting
Missing URL Parameters
Ensure your game URL includes both required parameters:
http://localhost:3001?hyve-access=JWT_TOKEN&game-id=my-game
Check if parameters are present:
const hyve = this.plugins.get('HyvePhaserPlugin');
if (!hyve.hasJwtToken()) {
console.error('Missing hyve-access URL parameter');
}
if (!hyve.getGameId()) {
console.error('Missing game-id URL parameter');
}
Telemetry Not Working
- Verify URL parameters are present (see above)
- Check network tab for
/api/v1/telemetry/sendrequests - Listen for error events:
this.game.events.on(HyveEvents.TELEMETRY_ERROR, (event) => {
console.error('Telemetry error:', event.error);
});
TypeScript Types
import HyvePhaserPlugin, { HyveEvents } from '@hyve-sdk/phaser';
const hyve = this.plugins.get('HyvePhaserPlugin') as HyvePhaserPlugin;