How misbahan/67-royale works
67 Royale is a single Next.js application that contains both the browser game client and the server API layer. There is no separate backend service in the repo; instead, Next.js App Router pages render the UI, and Next.js route handlers under src/app/api implement the backend behavior.
Main architectural layers:
1. Client/UI layer
• Located under frontend/src/app and frontend/src/components.
• The app includes separate user flows for:
- Solo challenge play
- Ranked PvP matchmaking
- Friendly 1v1 duel lobbies
- Leaderboards and score-sharing pages
- Tournament screens
• The components/game subtree holds the actual gameplay UI: camera feed, countdown, calibration overlay, game overlay, start/end screens, and mode selection.
• Shared UI elements live in components/ui, while leaderboard and tournament-specific panels live in their own component folders.
2. Client-side game engine / computer vision layer
• The core gameplay logic is browser-side, because it needs webcam access and low-latency per-frame tracking.
• Important code lives in src/lib/hand-tracking.ts, src/lib/brainrot-detector.ts, src/lib/pose/movenetProvider.ts, and hooks such as useHandTracking and useGameState.
• This layer consumes the webcam stream, detects hand landmarks, applies calibration, and counts valid alternations/reps.
• The README describes MediaPipe Hands and a custom alternation detector; the repo structure supports that as a client-side CV pipeline.
• This is intentionally local-first: raw camera processing happens in the browser to keep latency down and avoid sending video to the server for solo gameplay.
3. Real-time multiplayer layer
• PvP and friendly lobbies add a second runtime path: WebRTC-based peer-to-peer video.
• src/hooks/useWebRTC.ts handles client-side peer connection setup.
• Signaling and match state are mediated through Firestore-backed API routes rather than a dedicated signaling server.
• In practice:
- The clients connect directly for media transport.
- The app server coordinates lobby creation, join/ready/start state, and signaling metadata.
- TURN support is optional but important for real-world connectivity.
4. Backend/API layer
• src/app/api contains many route groups, each representing a subsystem boundary:
- Solo/challenge: create, session, submit, and challenge lookup routes
- Duel: create, join, find, ready, start, submit, session, and duel lookup routes
- Matchmaking: join, leave, status
- Leaderboard and stats: leaderboard, PvP leaderboard, score lookup, user stats
- Tournament: create, join, leave, list, start, cancel, match-start, and tournament lookup
- Seed and session-related routes
- OG image generation routes for share cards
• These route handlers are the main server-side orchestration point for validation, persistence, and state transitions.
• src/lib/jwt.ts, src/lib/rate-limit.ts, and src/lib/profanity.ts are cross-cutting server utilities used to enforce trust boundaries around submissions and usernames.
5. Data/storage layer
• Firebase Firestore is the primary persistent store.
• src/lib/firebase/client.ts and src/lib/firebase/server.ts separate browser SDK access from server/admin access.
• The backend uses Firebase Admin server-side for privileged operations; the client is limited to safer access patterns.
• The README defines the key collections:
- scores for solo leaderboard entries
- duels for private lobby sessions and WebRTC signaling subcollections
- duel_players for duel participants
- pvp_matches for ranked match records
- user_stats for player profile, ELO, wins/losses, trophies
• firestore.rules and firebase.json define the Firestore security boundary and Firebase deployment config.
Important data flows
Solo challenge flow:
• User opens a challenge page.
• Browser acquires webcam access and runs the hand-tracking / rep-detection pipeline locally.
• When the session ends, the client submits a result to server routes such as challenge/submit or score-related endpoints.
• The server validates the request, checks rate limits and JWT/session state, and stores the result in Firestore.
• Leaderboard and score pages read back aggregated results.
PvP matchmaking flow:
• Player joins matchmaking through matchmaking/join.
• The backend places or pairs players and exposes status through matchmaking/status.
• A match record is created in Firestore, and WebRTC negotiation happens between clients.
• After the match, the result is submitted to the server, which updates pvp_matches and user_stats/ELO-related data.
Friendly duel flow:
• One player creates a duel lobby and receives a shareable 6-digit code.
• The second player joins through the code.
• Readiness and start state are coordinated through duel API routes.
• WebRTC signaling is stored/relayed through Firestore-backed duel state.
• Scores are submitted separately and the server records the outcome without affecting rankings.
Tournament flow:
• The tournament subsystem exists as a separate state machine for bracketed play.
• Routes under api/tournament handle create/join/leave/list/start/cancel and match starts.
• UI under app/tournament and components/tournament renders bracket and match state.
• This appears to be a distinct domain model from duel/PvP, but it still reuses the same auth, Firestore, and submission infrastructure.
Cross-cutting boundaries
• Camera and CV processing stay on the client.
• All authoritative score submission and match state changes go through server routes.
• Firestore is the main backend state store, but protected by server-side validation and Firestore rules.
• JWT session validation and rate limiting are used to prevent score replay and spam.
• Profanity filtering is applied to usernames before they are persisted.
• Middleware in src/middleware.ts likely participates in request/session gating at the edge.
Operational/deployment shape
• The app is designed for Vercel deployment.
• Firebase provides database and related backend services.
• TURN servers are an external dependency for reliable WebRTC in restrictive networks.
• MediaPipe model assets are loaded client-side, which affects first-load latency and browser compatibility.
How to think about the diagram
A good architecture diagram for this repo should show:
• A browser client containing UI, webcam capture, hand tracking, game state, and WebRTC peers.
• A Next.js server/API boundary handling sessions, matchmaking, duel/tournament orchestration, score validation, leaderboard reads, and OG image generation.
• Firestore as the central shared state store, with separate collections for scores, duels, PvP matches, user stats, and tournament-related data.
• External services for Firebase, TURN/WebRTC relay, and model/CDN assets.
• Distinct flows for solo play versus real-time multiplayer, since only the multiplayer paths require peer connections and signaling.
Main entry points: server.ts Firestore server · page.tsx Game pages · challenge Challenge API · duel Duel API
Components 31
Browser client
Next.js App Router UI plus browser-side game/CV/runtime logic.
- App shell · Root layout, global styles, and top-level pages for the web app.
frontend/src/app/layout.tsx - Game pages · Entry pages for solo challenge, duel, PvP, leaderboard, score, and tournament flows.
frontend/src/app/page.tsx - Game UI · Gameplay screens and overlays for camera, calibration, countdown, start/end states, and mode selection.
frontend/src/components/game - Leaderboard UI · Leaderboard presentation panel used by score and ranking screens.
frontend/src/components/leaderboard - Tournament UI · Bracket, match, and tournament cards for tournament views.
frontend/src/components/tournament - Shared UI · Common header, footer, icons, and legal modal elements.
frontend/src/components/ui - Auth context · Client-side session/user context used across pages and hooks.
frontend/src/contexts/AuthContext.tsx - Game state · Coordinates client gameplay state transitions and result flow.
frontend/src/hooks/useGameState.ts - Hand tracking · Browser webcam pipeline for landmark tracking and rep detection.
frontend/src/hooks/useHandTracking.ts - WebRTC hook · Sets up peer connections for friendly duel and PvP media transport.
frontend/src/hooks/useWebRTC.ts - Tournament hook · Client-side tournament state and refresh logic.
frontend/src/hooks/useTournament.ts
Next.js API
Route handlers that validate, orchestrate, and persist game state.
- Challenge API · Create, session, lookup, and submit endpoints for solo challenge runs.
frontend/src/app/api/challenge - Duel API · Lobby creation, join/start/readiness, session, submit, and duel lookup routes.
frontend/src/app/api/duel - Matchmaking API · Join, leave, and status endpoints for ranked pairing.
frontend/src/app/api/matchmaking - Leaderboard API · Aggregated leaderboard endpoints for solo and PvP rankings.
frontend/src/app/api/leaderboard - Tournament API · Tournament lifecycle and match-start orchestration endpoints.
frontend/src/app/api/tournament - Score API · Score lookup and submission endpoints used by share pages and result views.
frontend/src/app/api/score - Session API · Session and user-state endpoint for request gating.
frontend/src/app/api/session - OG images · Open Graph image generation for share cards.
frontend/src/app/api/og - Stats API · User stats and profile endpoint used for player progress.
frontend/src/app/api/stats
Data layer
Firestore access, rules, and typed storage models.
- Firestore client · Browser Firebase access for safe client reads and auth-aware usage.
frontend/src/lib/firebase/client.ts - Firestore server · Privileged server-side Firestore access for authoritative writes and orchestration.
frontend/src/lib/firebase/server.ts - DB types · Typed Firestore/database and game model definitions.
frontend/src/types/database.ts - Rules · Security boundary for direct Firebase data access.
firestore.rules
Shared infra
Cross-cutting auth, limits, filtering, middleware, and external dependencies.
- JWT auth · Token validation for trusted submissions and gated actions.
frontend/src/lib/jwt.ts - Rate limit · Server-side abuse control for score and action submissions.
frontend/src/lib/rate-limit.ts - Profanity filter · Username moderation before persistence.
frontend/src/lib/profanity.ts - Middleware · Edge request/session gating before routes execute.
frontend/src/middleware.ts - CV models · MediaPipe and MoveNet model assets consumed client-side for low-latency tracking.
frontend/src/lib/pose/movenetProvider.ts - Firebase · Managed database and backend platform backing Firestore usage.
- TURN relay · Optional relay service for reliable WebRTC connectivity.
Connections 35
- Game pages → Game UI: renders · Pages compose the gameplay UI.
- Game pages → Leaderboard UI: renders · Leaderboard pages use shared panels.
- Game pages → Tournament UI: renders · Tournament pages use bracket and card components.
- Game pages → Shared UI: uses · All screens share common chrome and legal UI.
- Game pages → Auth context: consumes · Pages read auth/session context.
- Game UI → Game state: driven by · Gameplay screens react to client game state.
- Game state → Hand tracking: uses · Game state depends on browser CV input.
- Hand tracking → CV models: loads · Tracking pipeline uses client-side pose/model assets.
- Game state → Challenge API: submits to · Solo results are posted to challenge routes.
- Game state → Score API: submits to · Some result flows use score endpoints.
- WebRTC hook → Duel API: signals via · Duel lobby and signaling metadata are coordinated by routes.
- WebRTC hook → Matchmaking API: pairs via · Ranked pairing state is coordinated through matchmaking routes.
- WebRTC hook → TURN relay: relays via · TURN improves peer connectivity when direct P2P fails.
- Tournament hook → Tournament API: syncs with · Tournament state is coordinated through tournament routes.
- Challenge API → Firestore server: writes · Authoritative solo results and sessions are persisted server-side.
- Duel API → Firestore server: writes · Lobby state, signaling, and duel outcomes are stored server-side.
- Matchmaking API → Firestore server: writes · Matchmaking state and match records are persisted server-side.
- Leaderboard API → Firestore server: reads · Leaderboard endpoints aggregate stored results.
- Tournament API → Firestore server: writes · Tournament lifecycle and bracket state are stored server-side.
- Score API → Firestore server: reads/writes · Score lookup and submission touch authoritative storage.
- Stats API → Firestore server: reads/writes · User profile and ELO-like stats are maintained in storage.
- Session API → JWT auth: validates · Session and request trust are checked with JWT helpers.
- Challenge API → Rate limit: protects · Submission endpoints are rate-limited.
- Duel API → Rate limit: protects · Lobby and submit endpoints are rate-limited.
- Score API → Rate limit: protects · Score submission endpoints are rate-limited.
- Challenge API → Profanity filter: cleans · Submitted names are filtered before persistence.
- Duel API → Profanity filter: cleans · Lobby/player names are filtered before persistence.
- Session API → Middleware: gated by · Edge middleware participates in request/session gating.
- Challenge API → Rules: constrained by · Direct client access remains bounded by Firestore rules.
- Firestore client → Firebase: connects to · Browser SDK talks to Firebase services.
- Firestore server → Firebase: connects to · Admin SDK talks to Firebase services.
- DB types → Firestore server: types · Server storage code follows shared database models.
- DB types → Firestore client: types · Client data access follows shared database models.
- OG images → Duel API: supports · Share-card images are generated for duel flows.
- OG images → Score API: supports · Share-card images are generated for score pages.