๐ŸŽฎ Beta Gamer

Connect 4 โ€” React integration guide

Exact files to create, what to put in each one, and how they connect together.

1

Install the SDK

npm install @beta-gamer/react
2

Create a session on your backend

โš ๏ธ Never call the Beta Gamer API directly from your frontend. Your API key must stay server-side only. Use any backend below โ€” a single serverless function is enough.
๐Ÿ“„ server/routes/game.js
app.post('/api/game/start', async (req, res) => {
  const { userId, userName, game, matchType } = req.body;
  const resp = await fetch('https://api.beta-gamer.com/v1/sessions', {
    method: 'POST',
    headers: { 'Authorization': 'Bearer bg_live_xxxx', 'Content-Type': 'application/json' },
    body: JSON.stringify({
      game, matchType, players: [{ id: userId, displayName: userName }],
    }),
  });
  const { sessionToken, sessionId } = await resp.json();
  res.json({ sessionToken, sessionId });
});
3

Create a lobby page

๐Ÿ“„ src/pages/connect4/lobby.tsx
import { useState } from 'react';
import { useRouter } from 'next/navigation';

export default function Connect4Lobby() {
  const router = useRouter();
  const [loading, setLoading] = useState(false);

  const startGame = async (matchType: 'matchmaking' | 'bot') => {
    setLoading(true);
    const res = await fetch('/api/game/connect4/start', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ matchType }),
    });
    const { sessionToken, sessionId } = await res.json();
    router.push(`/connect4/game/${sessionId}?token=${sessionToken}`);
  };

  return (
    <div>
      <h1>Play Connect 4</h1>
      <button onClick={() => startGame('matchmaking')} disabled={loading}>Find opponent</button>
      <button onClick={() => startGame('bot')} disabled={loading}>vs Bot</button>
    </div>
  );
}
4

Create the game page

๐Ÿ“„ src/pages/connect4/game/[sessionId].tsx
import { useEffect, useState } from 'react';
import { useParams, useSearchParams } from 'next/navigation';
import { BetaGamerProvider } from '@beta-gamer/react';
import { Connect4Room } from '@/components/connect4/Connect4Room';

export default function Connect4GamePage() {
  const { sessionId } = useParams<{ sessionId: string }>();
  const token = useSearchParams().get('token');
  const [status, setStatus] = useState<'checking' | 'ok' | 'ended'>('checking');

  useEffect(() => {
    if (!token) { setStatus('ended'); return; }
    fetch(`/api/v1/sessions/validate?token=${token}`)
      .then(r => r.json())
      .then(d => setStatus(d.status === 'ended' ? 'ended' : 'ok'))
      .catch(() => setStatus('ok'));
  }, [token]);

  if (status === 'checking') return <p>Loadingโ€ฆ</p>;
  if (status === 'ended') return <div><p>Session ended.</p><a href="/connect4/lobby">Play again</a></div>;

  return (
    <BetaGamerProvider token={token!} serverUrl="https://api.beta-gamer.com">
      <Connect4Room sessionId={sessionId} onLeave={() => window.location.href = '/connect4/lobby'} />
    </BetaGamerProvider>
  );
}
5

Create the Connect4Room component

๐Ÿ“„ src/components/connect4/Connect4Room.tsx
'use client';

import { useEffect, useRef, useState } from 'react';
import { useSocket, useSession } from '@beta-gamer/react';

interface Props { sessionId: string; onLeave: () => void; }

export function Connect4Room({ sessionId, onLeave }: Props) {
  const socket     = useSocket();
  const session    = useSession();
  const myPlayerId = session.players[0]?.id ?? '';

  const roomIdRef = useRef('');
  const [board, setBoard]           = useState<(string | null)[]>(Array(42).fill(null));
  const [myColor, setMyColor]       = useState<'red' | 'yellow'>('red');
  const [rows, setRows]             = useState(6);
  const [cols, setCols]             = useState(7);
  const [currentTurn, setCurrentTurn] = useState(0);
  const [players, setPlayers]       = useState<any[]>([]);
  const [winningCells, setWinningCells] = useState<number[] | null>(null);
  const [gameResult, setGameResult] = useState<{ winner: string | null; reason: string } | null>(null);

  useEffect(() => {
    if (!socket) return;

    const join = () => socket.emit('matchmaking:join', {
      username: session.players[0]?.displayName, playerId: myPlayerId, sessionId,
    });
    if (socket.connected) join(); else socket.once('connect', join);

    socket.on('game:started', (d: any) => {
      roomIdRef.current = d.roomId;
      setMyColor(d.color); setBoard(d.board);
      setRows(d.rows ?? 6); setCols(d.cols ?? 7);
      setPlayers(d.players); setCurrentTurn(d.currentTurn);
    });

    socket.on('game:move:made', (d: any) => {
      setBoard(d.board); setCurrentTurn(d.currentTurn);
    });

    socket.on('game:over', (d: any) => {
      if (d.winningCells) setWinningCells(d.winningCells);
      setGameResult({ winner: d.winner ?? null, reason: d.reason });
    });

    return () => {
      socket.off('connect', join);
      ['game:started','game:move:made','game:over'].forEach(e => socket.off(e));
    };
  }, [socket]);

  const isMyTurn = players[currentTurn]?.id === myPlayerId;

  // Player taps a column header โ€” server applies gravity
  const dropPiece = (column: number) => {
    if (!isMyTurn || gameResult || board[column] !== null) return;
    socket?.emit('game:move', { roomId: roomIdRef.current, playerId: myPlayerId, column });
  };

  return (
    <div>
      {/* Render cols column buttons, each containing rows cells */}
      {/* board is flat: position = row * cols + col */}
      {/* Highlight winningCells (4 positions) on game over */}
      <p>{isMyTurn ? 'Your turn' : "Opponent's turn"}</p>
      {gameResult && <p>Game over: {gameResult.reason}</p>}
      <button onClick={() => socket?.emit('game:resign', { roomId: roomIdRef.current, playerId: myPlayerId })}>Resign</button>
      <button onClick={onLeave}>Leave</button>
    </div>
  );
}
Full event payload reference โ†’ Connect 4 socket events
Beta Gamer GaaS API โ€” questions? support@beta-gamer.com