Skip to main content

Guest Login

Guest login allows players to start playing immediately without creating an account or authenticating. This provides the lowest friction entry point for your game.

How Guest Login Works

Guest login in Moitribe SDK is implemented by simply skipping authentication after initialization. Players can use most SDK features without logging in.

// Initialize SDK
MoitribeSDK('my-game-id', 'init', {
loginCallback: (result) => {
if (result.success) {
// Player is authenticated
startGameWithProfile(result.playerdata);
} else {
// Player is not authenticated - start as guest
startGameAsGuest();
}
}
});

What Works Without Authentication

The following SDK features work without authentication:

✅ Available for Guest Players

  • Real-Time Multiplayer - Join and create rooms
  • Basic Gameplay - All client-side game logic
  • Local Storage - Client-side data persistence

❌ Requires Authentication

  • Leaderboards - Submit and view scores
  • Tournaments - Join and compete in tournaments
  • Profile Management - Access player profile data
  • Cross-Device Sync - Data doesn't sync across devices
  • Social Features - Friends, invitations, etc.
info

Guest players can fully participate in real-time multiplayer games. However, their identity is not persistent across sessions.

Basic Guest Flow

Simple Guest Start

const GAME_ID = 'my-game-id';

// Initialize SDK
MoitribeSDK(GAME_ID, 'init', {
loginCallback: (result) => {
// Always start game, regardless of auth status
startGame(result.success ? result.playerdata : null);
}
});

function startGame(playerData) {
if (playerData) {
console.log('Starting as authenticated player:', playerData.name);
enableAllFeatures();
} else {
console.log('Starting as guest player');
enableGuestFeatures();
}

// Start gameplay
initializeGameLogic();
}

Guest with Upgrade Prompt

MoitribeSDK('my-game-id', 'init', {
loginCallback: (result) => {
if (result.success) {
startGame(result.playerdata);
} else {
// Start as guest, show upgrade option
startGameAsGuest();
showOptionalLoginPrompt();
}
}
});

function showOptionalLoginPrompt() {
// Show dismissible login prompt
showBanner({
message: 'Login to save your progress and compete on leaderboards!',
buttons: [
{ text: 'Login', action: showLoginScreen },
{ text: 'Maybe Later', action: dismissBanner }
]
});
}

Guest Player Identification

Generate a temporary guest ID for tracking:

function generateGuestId() {
// Create unique guest ID
const timestamp = Date.now();
const random = Math.random().toString(36).substring(2, 15);
return `guest_${timestamp}_${random}`;
}

function startGameAsGuest() {
const guestId = generateGuestId();

// Store guest ID locally
localStorage.setItem('guestId', guestId);

console.log('Playing as guest:', guestId);
initializeGameLogic(guestId);
}

Guest with Local Storage

Use local storage to persist guest data:

function startGameAsGuest() {
// Load or create guest data
let guestData = loadGuestData();

if (!guestData) {
guestData = {
id: generateGuestId(),
createdAt: Date.now(),
highScore: 0,
gamesPlayed: 0
};
saveGuestData(guestData);
}

console.log('Guest data:', guestData);
startGame(guestData);
}

function loadGuestData() {
const data = localStorage.getItem('guestData');
return data ? JSON.parse(data) : null;
}

function saveGuestData(data) {
localStorage.setItem('guestData', JSON.stringify(data));
}

function updateGuestScore(score) {
const guestData = loadGuestData();
if (guestData) {
guestData.highScore = Math.max(guestData.highScore, score);
guestData.gamesPlayed++;
saveGuestData(guestData);
}
}

Progressive Authentication

Encourage guests to create accounts at strategic moments:

After First Game

let gamesPlayed = 0;

function onGameEnd(score) {
gamesPlayed++;

MoitribeSDK('my-game-id', 'isAuthenticated', {}, (result) => {
if (!result.success && gamesPlayed === 1) {
showDialog({
title: 'Great Job!',
message: `You scored ${score}! Create an account to save your progress and compete on leaderboards.`,
buttons: [
{ text: 'Create Account', action: showRegistration },
{ text: 'Continue as Guest', action: closeDialog }
]
});
}
});
}

After High Score

function onHighScore(score) {
MoitribeSDK('my-game-id', 'isAuthenticated', {}, (result) => {
if (!result.success) {
showDialog({
title: 'New High Score!',
message: `Amazing! You scored ${score}! Login now to save this score to the leaderboard.`,
buttons: [
{ text: 'Login', action: showLoginScreen, primary: true },
{ text: 'Not Now', action: closeDialog }
]
});
}
});
}

After Multiple Sessions

function checkAuthPromptOnStartup() {
const sessionCount = parseInt(localStorage.getItem('sessionCount') || '0');
localStorage.setItem('sessionCount', (sessionCount + 1).toString());

MoitribeSDK('my-game-id', 'isAuthenticated', {}, (result) => {
if (!result.success && sessionCount >= 3) {
showDialog({
title: 'Still Here?',
message: 'We love that you keep playing! Create an account to unlock all features.',
buttons: [
{ text: 'Create Account', action: showRegistration },
{ text: 'Stay Guest', action: closeDialog }
]
});
}
});
}

Upgrade Guest to Account

Allow guests to convert to authenticated accounts while preserving data:

function upgradeGuestToAccount(email, otp, name) {
// Get guest data
const guestData = loadGuestData();

// Create account
MoitribeSDK('my-game-id', 'createWithOtp', {
emailid: email,
otp: otp,
name: name,
callback: (result) => {
if (result.success) {
console.log('Account created successfully');

// Optionally migrate guest data to server
if (guestData) {
migrateGuestData(guestData);
}

// Clear guest data
clearGuestData();

showMessage('Welcome! Your account has been created.');
} else {
showError('Failed to create account');
}
}
});
}

function migrateGuestData(guestData) {
// Example: Submit guest high score to leaderboard
if (guestData.highScore > 0) {
MoitribeSDK('my-game-id', 'submitscore', {
leaderboardid: 'high-scores',
score: guestData.highScore,
callback: (result) => {
console.log('Guest score migrated to leaderboard');
}
});
}
}

function clearGuestData() {
localStorage.removeItem('guestData');
localStorage.removeItem('guestId');
}

TypeScript Example

import MoitribeSDK, { SignedInProfile } from '@veniso/moitribe-js';

interface GuestData {
id: string;
createdAt: number;
highScore: number;
gamesPlayed: number;
}

const GAME_ID = 'my-game-id';

function initializeGame(): void {
MoitribeSDK(GAME_ID, 'init', {
loginCallback: (result: { success: boolean; playerdata?: SignedInProfile }) => {
if (result.success && result.playerdata) {
startAuthenticatedGame(result.playerdata);
} else {
startGuestGame();
}
}
});
}

function startGuestGame(): void {
const guestData = getOrCreateGuestData();
console.log('Starting as guest:', guestData.id);

// Show guest mode indicator
showGuestBanner();

// Initialize game
initializeGameLogic(guestData);
}

function getOrCreateGuestData(): GuestData {
const stored = localStorage.getItem('guestData');

if (stored) {
return JSON.parse(stored) as GuestData;
}

const newGuest: GuestData = {
id: generateGuestId(),
createdAt: Date.now(),
highScore: 0,
gamesPlayed: 0
};

localStorage.setItem('guestData', JSON.stringify(newGuest));
return newGuest;
}

function generateGuestId(): string {
return `guest_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;
}

function startAuthenticatedGame(player: SignedInProfile): void {
console.log('Starting as authenticated player:', player.name);
initializeGameLogic(player);
}

Guest Mode UI

Show clear indicators that player is in guest mode:

<div id="guest-banner" style="display: none;">
<div class="banner-content">
<span> Playing as Guest</span>
<button onclick="showLoginScreen()">Login to Save Progress</button>
<button onclick="dismissGuestBanner()"></button>
</div>
</div>

<script>
function showGuestBanner() {
document.getElementById('guest-banner').style.display = 'block';
}

function dismissGuestBanner() {
document.getElementById('guest-banner').style.display = 'none';
localStorage.setItem('guestBannerDismissed', 'true');
}

function shouldShowGuestBanner() {
return !localStorage.getItem('guestBannerDismissed');
}
</script>

Feature Gating for Guests

Restrict certain features to authenticated players:

function submitScore(score) {
MoitribeSDK('my-game-id', 'isAuthenticated', {}, (result) => {
if (result.success) {
// Authenticated - submit to server
MoitribeSDK('my-game-id', 'submitscore', {
leaderboardid: 'high-scores',
score: score,
callback: (submitResult) => {
showMessage('Score submitted to leaderboard!');
}
});
} else {
// Guest - save locally only
updateGuestScore(score);

showDialog({
title: 'Score Not Saved',
message: 'Login to submit your score to the global leaderboard!',
buttons: [
{ text: 'Login Now', action: showLoginScreen },
{ text: 'Maybe Later', action: closeDialog }
]
});
}
});
}

function viewLeaderboard() {
MoitribeSDK('my-game-id', 'isAuthenticated', {}, (result) => {
if (result.success) {
loadLeaderboard();
} else {
showDialog({
title: 'Login Required',
message: 'Create an account to view leaderboards and compete with other players.',
buttons: [
{ text: 'Create Account', action: showRegistration },
{ text: 'Cancel', action: closeDialog }
]
});
}
});
}

Best Practices

1. Make Guest Mode Obvious

Clearly indicate when players are in guest mode:

function updateAuthIndicator() {
MoitribeSDK('my-game-id', 'isAuthenticated', {}, (result) => {
const indicator = document.getElementById('auth-indicator');

if (result.success) {
indicator.textContent = '👤 Logged In';
indicator.className = 'authenticated';
} else {
indicator.textContent = ' Guest';
indicator.className = 'guest';
}
});
}

2. Time Authentication Prompts

Don't interrupt gameplay - show prompts at natural breaks:

function onGameEnd() {
// Natural moment to prompt for login
checkAndPromptAuthentication();
}

function onPauseMenu() {
// Another good moment
showAuthenticationOption();
}

3. Preserve Guest Data

Don't lose guest progress when upgrading:

function preserveGuestProgress(callback) {
const guestData = loadGuestData();

if (guestData) {
// Store guest data temporarily
sessionStorage.setItem('guestDataToMigrate', JSON.stringify(guestData));
}

callback();
}

4. Highlight Benefits

Show what players gain by authenticating:

function showAuthenticationBenefits() {
showDialog({
title: 'Create Your Account',
message: `
✅ Save progress across devices
✅ Compete on global leaderboards
✅ Join tournaments
✅ Add friends and invite them to play
✅ Never lose your progress
`,
buttons: [
{ text: 'Create Account', action: showRegistration },
{ text: 'Continue as Guest', action: closeDialog }
]
});
}
tip

Guest mode is perfect for hyper-casual games and demos. For games with progression systems or social features, gently encourage players to create accounts after they're engaged with the gameplay.

When to Use Guest Login

✅ Good Use Cases

  • Hyper-casual games (quick play sessions)
  • Game demos and trials
  • Single-player puzzle games
  • Casual arcade games
  • Games with no progression system

⚠️ Consider Authentication For

  • Games with player progression
  • Multiplayer competitive games
  • Games with in-game purchases
  • Games with social features
  • Games requiring moderation

Next Steps

Learn about authenticated features:

Related topics: