Troubleshooting
This guide covers common issues and solutions when using the Moitribe JavaScript SDK.
Installation Issues
Module Not Found Error
Problem: Cannot find module '@veniso/moitribe-js'
Solutions:
# Check if package is installed
npm list @veniso/moitribe-js
# Reinstall if missing
npm install @veniso/moitribe-js
# Clear cache and reinstall
rm -rf node_modules package-lock.json
npm install
The SDK is a private package. Ensure you have access credentials configured in your .npmrc file.
TypeScript Type Errors
Problem: TypeScript cannot find type definitions
Solutions:
// tsconfig.json
{
"compilerOptions": {
"target": "ES2015",
"module": "ESNext",
"moduleResolution": "node",
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"skipLibCheck": true
}
}
// Ensure proper import
import MoitribeSDK, { GameInitParams } from '@veniso/moitribe-js';
Authentication Issues
Login Callback Never Called
Problem: loginCallback in init() never executes
Solutions:
// Check browser console for errors
console.log('Initializing SDK...');
MoitribeSDK('your-game-id', 'init', {
loginCallback: function(result) {
console.log('Login callback called:', result);
}
});
// Verify network connectivity
fetch('https://api.moitribe.com/v6/api/gsReq.php')
.then(() => console.log('Network OK'))
.catch(err => console.error('Network error:', err));
Ensure you're using the correct game ID from your Moitribe dashboard.
OTP Not Received
Problem: OTP email/SMS not delivered
Solutions:
// Check if OTP generation succeeded
MoitribeSDK(GAME_ID, 'genOtp', {
emailid: 'user@example.com', // or phno: '+1234567890'
callback: function(result) {
if (result.success) {
console.log('OTP sent successfully');
// Show success message to user
} else {
console.error('OTP generation failed:', result.message);
// Show error message and retry option
}
}
});
Common causes:
- Invalid email format or phone number
- Rate limiting (wait 60 seconds between requests)
- Email in spam folder
- Phone number not in E.164 format
Social Login Fails
Problem: Social login returns error
Solutions:
// Verify social platform data structure
const socialData = {
socialplat: 'google', // or 'facebook'
id: '123456789',
name: 'John Doe',
email: 'john@example.com',
picture: 'https://example.com/avatar.jpg'
};
// Validate required fields
const required = ['socialplat', 'id', 'name', 'email'];
const missing = required.filter(field => !socialData[field]);
if (missing.length > 0) {
console.error('Missing required fields:', missing);
return;
}
MoitribeSDK(GAME_ID, 'loginWithSocial', {
social: socialData,
callback: function(result) {
console.log('Social login result:', result);
}
});
Leaderboard Issues
Score Submission Fails
Problem: submitscore returns error
Solutions:
// Validate score before submission
function submitScore(leaderboardId, score) {
if (typeof leaderboardId !== 'string' || !leaderboardId.trim()) {
console.error('Invalid leaderboard ID');
return;
}
if (typeof score !== 'number' || isNaN(score)) {
console.error('Invalid score value');
return;
}
MoitribeSDK(GAME_ID, 'submitscore', {
leaderboardid: leaderboardId,
score: score,
scoretag: 'optional-metadata', // Optional
callback: function(result) {
if (result.success) {
console.log('Score submitted successfully');
} else {
console.error('Score submission failed:', result.message);
// Retry logic if needed
}
}
});
}
Common causes:
- Invalid leaderboard ID
- Score is not a number
- Player not authenticated
- Network connectivity issues
Leaderboard Data Not Loading
Problem: loadleaderboardtopscores returns empty or error
Solutions:
// Check leaderboard metadata first
MoitribeSDK(GAME_ID, 'loadleaderboardmetadata', {
onlyData: true,
callback: function(result) {
if (result.success && result.leaderboards) {
const leaderboard = result.leaderboards.find(lb => lb.id === 'your-leaderboard-id');
if (leaderboard) {
console.log('Leaderboard found:', leaderboard);
loadScores(leaderboard.id);
} else {
console.error('Leaderboard not found');
}
}
}
});
function loadScores(leaderboardId) {
MoitribeSDK(GAME_ID, 'loadleaderboardtopscores', {
leaderboardid: leaderboardId,
collection: 1, // 0 = Social, 1 = Global
timespan: 0, // 0 = All-time, 1 = Weekly, 2 = Daily
maxresults: 25,
onlyData: true,
callback: function(result) {
console.log('Scores loaded:', result);
}
});
}
Real-Time Multiplayer Issues
Room Creation Fails
Problem: createstandardroom or createendlessroom fails
Solutions:
// Validate room parameters
function createStandardRoom() {
const params = {
variant: 0,
min_automatch_players: 2,
max_automatch_players: 4,
onRoomCreated: function(success, room) {
if (success) {
console.log('Room created:', room);
} else {
console.error('Room creation failed');
// Retry with different parameters
}
},
onMessageReceived: function(data, senderId, isReliable) {
console.log('Message received:', { data, senderId, isReliable });
}
};
// Validate parameters
if (params.min_automatch_players > params.max_automatch_players) {
console.error('Min players cannot exceed max players');
return;
}
MoitribeSDK(GAME_ID, 'createstandardroom', params);
}
Common causes:
- Invalid player count parameters
- Missing required callbacks
- Network connectivity issues
- Server-side room limits
Messages Not Received
Problem: onMessageReceived callback not triggered
Solutions:
// Ensure message callback is properly set
const roomParams = {
// ... other parameters
onMessageReceived: function(data, senderId, isReliable) {
console.log('Message received:', {
data: data,
senderId: senderId,
isReliable: isReliable,
dataType: data.constructor.name
});
// Handle ArrayBuffer data
if (data instanceof ArrayBuffer) {
const view = new DataView(data);
// Process binary data
}
}
};
// Test message sending
function testMessage() {
const testData = new ArrayBuffer(4);
const view = new DataView(testData);
view.setUint32(0, 12345, true);
MoitribeSDK(GAME_ID, 'standardmessage', {
messageData: testData,
participantIds: [], // Empty for broadcast
isReliable: true
});
}
Connection Drops Frequently
Problem: Room connections disconnect frequently
Solutions:
// Implement reconnection logic
class RoomManager {
constructor() {
this.reconnectAttempts = 0;
this.maxReconnectAttempts = 5;
this.reconnectDelay = 1000;
}
joinRoom(roomId) {
const params = {
// ... room parameters
onRoomDisconnected: () => {
console.log('Room disconnected, attempting to reconnect...');
this.handleReconnection(roomId);
},
onRoomConnected: () => {
console.log('Room connected successfully');
this.reconnectAttempts = 0;
}
};
MoitribeSDK(GAME_ID, 'joinstandardroominvcode', {
invitationID: roomId,
...params
});
}
handleReconnection(roomId) {
if (this.reconnectAttempts < this.maxReconnectAttempts) {
this.reconnectAttempts++;
const delay = this.reconnectDelay * Math.pow(2, this.reconnectAttempts - 1);
setTimeout(() => {
console.log(`Reconnection attempt ${this.reconnectAttempts}...`);
this.joinRoom(roomId);
}, delay);
} else {
console.error('Max reconnection attempts reached');
// Show error to user
}
}
}
Tournament Issues
Tournament Join Fails
Problem: groupTournamentJoin returns error
Solutions:
// Check tournament availability first
function joinTournament(tournamentId) {
// Get tournament metadata
MoitribeSDK(GAME_ID, 'groupTournamentData', {
tournamentid: tournamentId,
callback: function(result) {
if (result.success && result.tournament) {
const tournament = result.tournament;
// Check if tournament is active
if (tournament.status !== 'active') {
console.error('Tournament is not active:', tournament.status);
return;
}
// Check if player is eligible
if (tournament.participants && tournament.participants.length >= tournament.maxParticipants) {
console.error('Tournament is full');
return;
}
// Join tournament
MoitribeSDK(GAME_ID, 'groupTournamentJoin', {
tournamentid: tournamentId,
callback: function(joinResult) {
if (joinResult.success) {
console.log('Successfully joined tournament');
} else {
console.error('Failed to join tournament:', joinResult.message);
}
}
});
}
}
});
}
Performance Issues
Slow Loading Times
Problem: SDK operations take too long
Solutions:
// Implement caching for frequently accessed data
class DataCache {
constructor() {
this.cache = new Map();
this.cacheTimeout = 5 * 60 * 1000; // 5 minutes
}
set(key, data) {
this.cache.set(key, {
data: data,
timestamp: Date.now()
});
}
get(key) {
const cached = this.cache.get(key);
if (!cached) return null;
if (Date.now() - cached.timestamp > this.cacheTimeout) {
this.cache.delete(key);
return null;
}
return cached.data;
}
}
const dataCache = new DataCache();
// Cached leaderboard loading
function loadLeaderboardScores(leaderboardId) {
const cacheKey = `scores_${leaderboardId}`;
const cached = dataCache.get(cacheKey);
if (cached) {
console.log('Loading from cache...');
return Promise.resolve(cached);
}
return new Promise((resolve) => {
MoitribeSDK(GAME_ID, 'loadleaderboardtopscores', {
leaderboardid: leaderboardId,
collection: 1,
timespan: 0,
maxresults: 25,
onlyData: true,
callback: function(result) {
if (result.success) {
dataCache.set(cacheKey, result.scores);
resolve(result.scores);
} else {
resolve([]);
}
}
});
});
}
Memory Usage High
Problem: Memory usage increases over time
Solutions:
// Implement object pooling for frequently created objects
class ObjectPool {
constructor(createFn, resetFn, initialSize = 10) {
this.createFn = createFn;
this.resetFn = resetFn;
this.pool = [];
for (let i = 0; i < initialSize; i++) {
this.pool.push(this.createFn());
}
}
get() {
return this.pool.length > 0 ? this.pool.pop() : this.createFn();
}
release(obj) {
this.resetFn(obj);
this.pool.push(obj);
}
}
// Pool for message objects
const messagePool = new ObjectPool(
() => ({ data: null, timestamp: 0, senderId: null }),
(obj) => {
obj.data = null;
obj.timestamp = 0;
obj.senderId = null;
}
);
// Use pooled objects in message handler
function handleMessage(data, senderId, isReliable) {
const message = messagePool.get();
message.data = data;
message.timestamp = Date.now();
message.senderId = senderId;
// Process message...
// Release back to pool
messagePool.release(message);
}
Browser Compatibility Issues
CORS Errors
Problem: Cross-origin requests blocked
Solutions:
// Check if running in development
const isDevelopment = window.location.hostname === 'localhost' ||
window.location.hostname === '127.0.0.1';
if (isDevelopment) {
console.log('Running in development mode');
// CORS should not be an issue in development
} else {
console.log('Running in production mode');
// Ensure your domain is whitelisted in Moitribe dashboard
}
// Test API connectivity
function testConnectivity() {
return fetch('https://api.moitribe.com/v6/api/gsReq.php', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
test: true
})
})
.then(response => {
if (response.ok) {
console.log('API connectivity OK');
return true;
} else {
console.error('API connectivity failed:', response.status);
return false;
}
})
.catch(error => {
console.error('Network error:', error);
return false;
});
}
Internet Explorer Issues
Problem: SDK doesn't work in IE11
Solutions:
<!-- Include polyfills for IE11 -->
<script src="https://polyfill.io/v3/polyfill.min.js?features=Promise,ArrayBuffer,DataView"></script>
<script src="node_modules/@veniso/moitribe-js/dist/moitribe-sdk.min.js"></script>
<script>
// Check browser compatibility
if (typeof ArrayBuffer === 'undefined' || typeof DataView === 'undefined') {
console.error('Browser not supported');
// Show upgrade browser message
document.getElementById('browser-warning').style.display = 'block';
} else {
// Initialize SDK
MoitribeSDK('your-game-id', 'init', {
loginCallback: function(result) {
console.log('SDK initialized:', result);
}
});
}
</script>
<style>
#browser-warning {
display: none;
background: #ff6b6b;
color: white;
padding: 20px;
text-align: center;
font-family: Arial, sans-serif;
}
</style>
<div id="browser-warning">
<h2>Browser Not Supported</h2>
<p>Please upgrade to a modern browser to use this application.</p>
<p>Recommended browsers: Chrome, Firefox, Safari, Edge</p>
</div>
Debugging Tips
Enable Debug Logging
// Enable debug logging in development
if (window.location.hostname === 'localhost') {
// Set log level if SDK supports it
if (window.MoitribeLogger) {
window.MoitribeLogger.setLevel('debug');
}
}
// Create debug wrapper
function debugLog(method, params, result) {
if (window.location.hostname === 'localhost') {
console.group(`Moitribe SDK: ${method}`);
console.log('Parameters:', params);
console.log('Result:', result);
console.groupEnd();
}
}
// Wrap SDK calls
function debugSDK(gameId, method, params, callback) {
const wrappedCallback = function(result) {
debugLog(method, params, result);
if (callback) callback(result);
};
MoitribeSDK(gameId, method, params, wrappedCallback);
}
Network Monitoring
// Monitor network requests
class NetworkMonitor {
constructor() {
this.requests = [];
this.errors = [];
}
logRequest(method, params) {
this.requests.push({
method: method,
params: params,
timestamp: Date.now()
});
}
logError(method, error) {
this.errors.push({
method: method,
error: error,
timestamp: Date.now()
});
}
getStats() {
return {
totalRequests: this.requests.length,
totalErrors: this.errors.length,
errorRate: (this.errors.length / this.requests.length * 100).toFixed(2) + '%',
recentErrors: this.errors.slice(-5)
};
}
}
const networkMonitor = new NetworkMonitor();
// Use with SDK calls
function monitoredSDKCall(gameId, method, params, callback) {
networkMonitor.logRequest(method, params);
MoitribeSDK(gameId, method, params, function(result) {
if (!result.success) {
networkMonitor.logError(method, result.message);
}
if (callback) callback(result);
});
}
// Check network stats periodically
setInterval(() => {
console.log('Network Stats:', networkMonitor.getStats());
}, 30000); // Every 30 seconds
Getting Help
If you're still experiencing issues:
- Check the Console: Always check browser console for error messages
- Verify Network: Ensure you can reach
api.moitribe.com - Review Parameters: Double-check all method parameters
- Test Isolation: Create a minimal test case to isolate the issue
- Contact Support: Reach out to the Veniso development team with:
- SDK version (1.4.2)
- Browser and version
- Error messages from console
- Steps to reproduce
- Code example (minimal)
When reporting issues, include the full error object from the callback, not just the message. This helps identify the root cause.
Common Error Codes
| Error Code | Description | Solution |
|---|---|---|
NETWORK_ERROR | Cannot reach Moitribe servers | Check internet connection and firewall |
INVALID_GAME_ID | Game ID not found | Verify game ID in dashboard |
NOT_AUTHENTICATED | Player not logged in | Call authentication methods first |
INVALID_PARAMETERS | Method parameters invalid | Check parameter types and values |
RATE_LIMITED | Too many requests | Wait and retry with exponential backoff |
ROOM_FULL | Room at capacity | Join different room or wait |
TOURNAMENT_ENDED | Tournament no longer active | Check tournament schedule |
For complete error code reference, see API Reference - Constants.