• ... • • Comments • •

Playing Chess Against AI 100% in the Browser: Stockfish 19 WASM, Difficulty Scaling, and Live Analysis

How to build a real, zero-backend Chess AI with adjustable difficulty (800 to 2800+ ELO), a live evaluation bar, and move-by-move blunder detection in under 2 MB of WebAssembly.

Guy Mograbi
Guy Mograbi
Full Stack & Cloud Engineer
Koala engineer pondering a glowing holographic chessboard running inside a web browser

Continuing my journey into what is possible with AI in the browser—after neural text-to-speech, image background removal, local WebGPU LLMs, and in-browser agent loops—I wanted to tackle a classic game: Chess.

Just like those previous demos, this one also relies on WebAssembly (WASM). While you could try prompting a 2 GB Large Language Model on WebGPU to play chess, an LLM is the wrong tool—it’s heavy, slow, and starts hallucinating illegal moves after move 10.

Instead, we can run Stockfish 19 compiled to WASM (~1.8 MB) directly inside a browser Web Worker—no servers, instant load, and grandmaster-level analysis.


Wait: Is Stockfish an AI?

Yes—Stockfish is a specialized game-playing AI, just not a generative language model (LLM).

Modern Stockfish combines two AI techniques:

  1. Heuristic Tree Search (Alpha-Beta Pruning): Rapidly explores millions of future move sequences and prunes losing lines (if you haven’t seen it, Sebastian Lague’s visual YouTube explainer on Minimax & Alpha-Beta is the best 15-minute breakdown on the internet).
  2. NNUE (Efficiently Updatable Neural Network): A compact neural network trained on millions of chess positions to evaluate who is winning and by how much—incrementally updating only the pieces that moved on each turn (deep dive on the Chess Programming Wiki).

Because it doesn’t need billions of English text parameters, the entire engine fits in ~1.8 MB instead of 1.8 GB.


The Zero-Backend Stack

Our Chess Arena runs 100% inside your browser tab using three open-source libraries:

flowchart LR
    UI["♟️ <b>Chessground Board</b><br/>Drag-and-drop UI + Arrows"] <-->|"Legal Moves & FEN"| Rules["📜 <b>chess.js</b><br/>Rules, Check, PGN"]
    Rules -->|"UCI Position"| Worker["⚙️ <b>Stockfish 19 WASM</b><br/>(Web Worker · ~1.8 MB)"]
    Worker -->|"Eval Bar + Best Move + Blunder Check"| UI
  1. chess.js (~20 KB): Enforces all chess rules, legal move generation, promotions, and checkmate/draw detection.
  2. chessground: Lichess’s official open-source board with smooth drag-and-drop, legal-move dots, and best-move hint arrows.
  3. stockfish-19-lite-single (WebAssembly): Runs off the main UI thread inside a Web Worker so the board stays 60 FPS while the engine thinks.

TIP

Why the lite-single WASM build—and is it “dumber”? The full multi-threaded Stockfish build weighs 70+ MB and requires extra browser security headers that can break normal scripts and embeds on a blog. The single-threaded lite-single build is just 1.84 MB and works on any webpage out of the box. Against supercomputers it’s ~150 ELO weaker (~3300+ ELO vs. ~3550 ELO)—which is still 400+ ELO stronger than Magnus Carlsen (~2882 ELO) while loading 40× faster.


How Difficulty & Live Coaching Work

How do you make a 3300-ELO superhuman engine play like a casual human?

If you only limit how many moves ahead Stockfish looks, it still plays ~2000 ELO chess because its neural network rarely misevaluates a board. Instead, Stockfish has a built-in Skill Level (0 to 20): when you lower it, the engine evaluates the top 4 candidate moves instead of only the best one and mixes in controlled randomness so it makes natural, human-like mistakes.

Using that, our single Stockfish worker wears two hats during a game:

  1. As Your Opponent (Handicapped): On the AI’s turn, we dial its Skill Level down to match the difficulty you picked—from ~800 ELO Beginner up to Master.
  2. As Your Coach (Full Strength): The moment the AI finishes its move, we dial Stockfish back up to full strength in the background so it can accurately update the evaluation bar, grade your moves (★ Best to ?? Blunder), and calculate your live Accuracy % and Estimated ELO.

How Complicated Was It to Build? (The Core Loop)

Surprisingly simple—and no, you don’t have to compile C++ or touch any WebAssembly toolchain yourself.

The stockfish npm package already ships pre-built .js + .wasm files in node_modules/stockfish/bin/. You just copy stockfish-19-lite-single.js and stockfish-19-lite-single.wasm into your static public/stockfish/ folder, load the .js file in a standard new Worker(...), and talk to it using plain-text UCI (Universal Chess Interface) commands over postMessage:

import { Chess } from 'chess.js';
import { Chessground } from 'chessground';

const game = new Chess();
const engine = new Worker('/stockfish/stockfish-19-lite-single.js');
engine.postMessage('uci');

// 1. Mount Lichess's board and handle human moves
const board = Chessground(document.getElementById('board')!, {
  events: {
    move: (orig, dest) => {
      game.move({ from: orig, to: dest, promotion: 'q' });
      board.set({ fen: game.fen() });

      // 2. Ask Stockfish for its reply at the chosen skill & depth
      engine.postMessage(`setoption name Skill Level value 5`);
      engine.postMessage(`position fen ${game.fen()}`);
      engine.postMessage(`go depth 6`);
    },
  },
});

// 3. Listen for Stockfish's evaluation & best move
engine.onmessage = ({ data }: MessageEvent<string>) => {
  if (data.startsWith('info') && data.includes('score cp ')) {
    const cp = Number(data.match(/score cp (-?\d+)/)?.[1] ?? 0) / 100;
    console.log('Eval (pawns):', cp);
  }
  if (data.startsWith('bestmove ')) {
    const uciMove = data.split(' ')[1]; // e.g. "e7e5"
    game.move({ from: uciMove.slice(0, 2), to: uciMove.slice(2, 4), promotion: 'q' });
    board.set({ fen: game.fen() });
  }
};

Because Stockfish speaks standard plain-text UCI over postMessage (documented in Stockfish’s official UCI & Commands guide—and if you send 'uci' to the worker, Stockfish even prints out every option name ... it supports right in the console), you never have to touch raw WebAssembly memory or C++ bindings.

Give it a game at /demos/chess—and toggle on Show Hints whenever you want to see Stockfish’s live best-move arrows on the board!