ChessNextMove.ai
CalculatorAnalysisPuzzlesLeaderboardPricing
Try Pro

Free Stockfish API: Get the Best Move From a FEN

By Chess Next Move Team|Published November 15, 2026

Copy-paste code for Node.js and Python, the four commands that matter, and a free cloud option.

Just need one move? Use the free calculator

Smart Tactics. Human Mode. Full 3650 power.

Train the patterns that win games, and get suggestions you can actually play — not engine lines you can't reproduce.

Smart Tactics9 pattern trainers
Human ModeReal chess, not engine lines
3650 ELOFree caps at 800
Position ReaderScreenshot → board
Unlimited AI InsightsNo daily limit
FEN & PGNYour own games
Spin to win Pro from $2.99/moOne free spin · save up to 85% · price locked for lifeSpin now

14-day money-back guarantee · Cancel anytime

You have a FEN string and you want Stockfish's best move back, from code, without paying for anything. Good news: you don't need anyone's API key. Stockfish is free, open source and talks a plain-text protocol called UCI. Start the engine, send it the position, ask it to think, and read one line back: bestmove e2e4.

That is the whole trick, and it is what every chess site does behind the scenes, ours included. Below are working examples in Node.js and Python, a ten-line HTTP wrapper if you want your own /bestmove?fen= endpoint, Lichess's free cloud evaluation as a no-install option, and the one check that will save you from crashes: validating the FEN first.

One thing to be clear about up front: Chess Next Move does not offer a public API. If you only need the move for a position or two, you don't need code at all. Set the position up in the chess calculator and it shows you the move.

The four UCI commands you need

UCI (Universal Chess Interface) is a text protocol over standard input and output. You write a line, the engine writes lines back. For "best move from a FEN" you need exactly four commands:

  1. uci: says hello. The engine lists its options and ends with uciok.
  2. isready: waits until the engine has loaded. It replies readyok. Don't send a position before you see it.
  3. position fen <FEN>: sets the board. You can append moves e2e4 e7e5 to play moves on from there.
  4. go depth 18 (or go movetime 1000 for one second): starts the search. When it finishes you get bestmove.

A real session looks like this (> is what you send, < what you get back):

> uci
< id name Stockfish 19
< ...
< uciok
> isready
< readyok
> position fen r1bqkbnr/pppp1ppp/2n5/4p3/4P3/5N2/PPPP1PPP/RNBQKB1R w KQkq - 2 3
> go depth 18
< info depth 18 ... score cp 41 ... pv f1b5 g8f6 ...
< bestmove f1b5 ponder g8f6

Two details trip people up. The move comes back in UCI notation, from-square plus to-square (f1b5, or e7e8q for a promotion), not as Bb5. And the score in the info lines is from the side to move's point of view: cp 41 means the player to move is about 0.41 of a pawn better, mate 3 means they mate in three.

Step 1: get the Stockfish binary

Download it from the official site, stockfishchess.org, which has builds for Windows, macOS and Linux. On a Mac, brew install stockfish works; on Ubuntu or Debian, apt install stockfish gets you a version from the distribution, which is often a release or two behind.

Check it runs: type stockfish in a terminal, then uci. If you see uciok, you are ready. The examples below assume stockfish is on your PATH; pass the full path otherwise.

Step 2: best move from a FEN in Node.js

No packages needed, just child_process. The function starts Stockfish, waits for readyok, sends the position and resolves with the move and the last score it saw:

// best-move.mjs   usage: node best-move.mjs "<fen>" [depth]
import { spawn } from "node:child_process";

export function bestMove(fen, depth = 18, enginePath = "stockfish") {
  return new Promise((resolve, reject) => {
    const engine = spawn(enginePath);
    let buffer = "";
    let score = null;
    const timer = setTimeout(() => {
      engine.kill();
      reject(new Error("Stockfish timed out"));
    }, 30_000);

    engine.stdout.on("data", (chunk) => {
      buffer += chunk.toString();
      let i;
      while ((i = buffer.indexOf("\n")) >= 0) {
        const line = buffer.slice(0, i).trim();
        buffer = buffer.slice(i + 1);

        // Keep the score from the latest (deepest) info line.
        const m = line.match(/ score (cp|mate) (-?\d+)/);
        if (line.startsWith("info") && m) score = { type: m[1], value: Number(m[2]) };

        if (line === "readyok") {
          engine.stdin.write(`position fen ${fen}\n`);
          engine.stdin.write(`go depth ${depth}\n`);
        }
        if (line.startsWith("bestmove")) {
          clearTimeout(timer);
          engine.stdin.write("quit\n");
          resolve({ bestmove: line.split(" ")[1], score });
        }
      }
    });

    engine.on("error", (err) => {
      clearTimeout(timer);
      reject(err);
    });

    engine.stdin.write("uci\n");
    engine.stdin.write("isready\n");
  });
}

const [fen, depth] = process.argv.slice(2);
if (fen) console.log(await bestMove(fen, Number(depth) || 18));

Run it with node best-move.mjs "r1bqkbnr/pppp1ppp/2n5/4p3/4P3/5N2/PPPP1PPP/RNBQKB1R w KQkq - 2 3" and you get something like { bestmove: 'f1b5', score: { type: 'cp', value: 41 } }. The exact move and score can differ between Stockfish versions and machines.

Step 2 (Python): the same thing with subprocess

Standard library only:

# best_move.py   usage: python best_move.py "<fen>"
import subprocess
import sys


def best_move(fen, depth=18, engine_path="stockfish"):
    engine = subprocess.Popen(
        [engine_path], stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True
    )

    def send(cmd):
        engine.stdin.write(cmd + "\n")
        engine.stdin.flush()

    send("uci")
    send("isready")
    for line in engine.stdout:
        if line.strip() == "readyok":
            break

    send(f"position fen {fen}")
    send(f"go depth {depth}")
    score = None
    for line in engine.stdout:
        parts = line.split()
        if parts and parts[0] == "info" and "score" in parts:
            i = parts.index("score")
            score = (parts[i + 1], int(parts[i + 2]))  # ("cp", 41) or ("mate", 3)
        if parts and parts[0] == "bestmove":
            send("quit")
            engine.wait()
            return parts[1], score


if __name__ == "__main__":
    print(best_move(sys.argv[1]))

If you are doing anything more than one-off lookups in Python, use the python-chess library instead. It handles the UCI conversation, parses scores and gives you proper move objects:

# pip install chess
import chess
import chess.engine

board = chess.Board("r1bqkbnr/pppp1ppp/2n5/4p3/4P3/5N2/PPPP1PPP/RNBQKB1R w KQkq - 2 3")
engine = chess.engine.SimpleEngine.popen_uci("stockfish")
try:
    info = engine.analyse(board, chess.engine.Limit(depth=18))
    print("best move:", info["pv"][0])        # a chess.Move, e.g. f1b5
    print("eval for White:", info["score"].white())
finally:
    engine.quit()

engine.analyse returns the principal variation and score; engine.play with the same Limit returns just the move to play, if that is all you want.

Validate the FEN first, or Stockfish may crash

This is the part most tutorials skip, and we learned it the hard way. Stockfish trusts that the position you give it is legal. Hand it an impossible one, say the side that is not to move is already in check, and it can simply die instead of returning an error. On a server that means a dead worker and a request that never answers.

chess.js catches most bad FENs with validateFen, but not that one, so add a second test:

// fen-check.mjs   npm install chess.js
import { Chess, validateFen } from "chess.js";

export function isSafeForEngine(fen) {
  if (!validateFen(fen).ok) return false;   // bad format, missing king, pawn on rank 1/8...

  // validateFen still accepts a position where the side NOT to move is in
  // check, which can never arise in a game. Flip the turn and test it.
  const [board, turn, castling] = fen.trim().split(/\s+/);
  const other = turn === "w" ? "b" : "w";
  try {
    if (new Chess(`${board} ${other} ${castling} - 0 1`).inCheck()) return false;
  } catch {
    return false;
  }
  return true;
}

Run every FEN through it before it gets near the engine, especially if users can type their own. Puzzle editors and "set up a position" boards produce impossible positions all the time.

Turn it into your own free API endpoint

Put the two files above next to this one and you have GET /bestmove?fen=...&depth=16 on port 8080, with the FEN checked and the depth capped so nobody can ask for depth 60 and tie up your CPU:

// server.mjs   GET /bestmove?fen=...&depth=16
import http from "node:http";
import { bestMove } from "./best-move.mjs";
import { isSafeForEngine } from "./fen-check.mjs";

http.createServer(async (req, res) => {
  const url = new URL(req.url, "http://localhost");
  const fen = url.searchParams.get("fen") ?? "";
  const depth = Math.min(Number(url.searchParams.get("depth")) || 16, 22);

  if (url.pathname !== "/bestmove" || !isSafeForEngine(fen)) {
    res.writeHead(400, { "content-type": "application/json" });
    return res.end(JSON.stringify({ error: "send a legal FEN to /bestmove" }));
  }
  try {
    const result = await bestMove(fen, depth);
    res.writeHead(200, { "content-type": "application/json" });
    res.end(JSON.stringify(result));
  } catch (err) {
    res.writeHead(500, { "content-type": "application/json" });
    res.end(JSON.stringify({ error: String(err) }));
  }
}).listen(8080);

Starting a new Stockfish process per request is fine for a hobby project. Once real traffic arrives, keep a small pool of long-running engine processes and hand each request to a free one, sending ucinewgame between unrelated positions. That is how our own server-side analysis works: a handful of Stockfish processes, started on first use and reused after that.

Two options worth setting once after uci: setoption name Threads value 2 to use more cores per search, and setoption name Hash value 128 for a bigger transposition table, in megabytes. Leave some cores for the rest of your server.

No install: Lichess's cloud evaluation

If you can't run a binary (a browser extension, a serverless function), Lichess has a free public endpoint, GET https://lichess.org/api/cloud-eval?fen=.... It returns a stored evaluation: the FEN, the depth, the number of nodes searched in thousands, and one or more lines with their moves and a centipawn or mate score.

const fen = "r1bqkbnr/pppp1ppp/2n5/4p3/4P3/5N2/PPPP1PPP/RNBQKB1R w KQkq - 2 3";
const url = "https://lichess.org/api/cloud-eval?multiPv=1&fen=" + encodeURIComponent(fen);

const res = await fetch(url);
if (res.status === 404) {
  // Not in Lichess's cloud database: fall back to your own Stockfish.
} else if (res.status === 429) {
  // Rate limited: wait a full minute before the next request.
} else {
  const data = await res.json();
  const line = data.pvs[0];                 // { moves: "f1b5 g8f6 ...", cp: 41 } or { mate: 3 }
  const best = line.moves.split(" ")[0];    // UCI move, e.g. "f1b5"
  console.log(best, line.cp ?? `mate ${line.mate}`, "depth", data.depth);
}

The catch: it is a cache, not an engine. It only answers for positions someone has already analysed deeply on Lichess. Opening positions and famous games are usually there; a random middlegame from your app usually is not, and you get a 404. Treat it as a fast first try with your own Stockfish as the fallback.

Be a polite client. Lichess asks API users to make one request at a time, and if you get a 429 response, wait a full minute before trying again. Don't point a high-traffic app at it.

Don't want to write code?

If what you actually want is the best move in a position from one of your own games, skip all of this. Open the chess calculator, drag the pieces into position and press Hint. On the free plan it plays at up to 800 ELO strength; Pro unlocks the full engine and lets you paste a FEN straight in or scan a screenshot.

Want to play against the engine rather than query it? Stockfish online runs it in your browser, and our Stockfish ELO guide explains what the strength settings really do.

Stockfish API FAQ

Is there a free Stockfish API?

Stockfish itself is free and open source, and the simplest free "API" is the engine running on your own machine or server: start it, send position fen and go depth, read bestmove. For positions that are already well analysed, Lichess's cloud evaluation endpoint (lichess.org/api/cloud-eval) returns a stored evaluation for free, but only for positions in its database.

How do I get the best move from a FEN with Stockfish?

Send four commands over the engine's standard input: uci, isready, position fen <your FEN>, then go depth 18 (or go movetime 1000). Stockfish answers with info lines and finally bestmove <move>, for example bestmove f1b5. The move is in UCI format: from-square then to-square, plus a promotion letter if needed.

What does score cp mean in Stockfish output?

cp is centipawns, hundredths of a pawn, from the point of view of the side to move. score cp 41 means the side to move is slightly better; score mate 3 means it mates in three moves, and a negative mate score means it is getting mated.

Why did Stockfish crash on my FEN?

Usually because the position is illegal, for example the side that is not to move is in check, or a king is missing. Stockfish assumes it is given a legal position and can exit instead of returning an error. Validate every FEN before you send it; the chess.js check on this page catches the common cases.

Does Chess Next Move have a public API?

No. The site's engine runs for its own pages only. If you just need the best move for one position, set it up in the free chess calculator; if you need moves from code, run Stockfish yourself as shown here.

What depth should I use?

It depends on your hardware and how many requests you serve. Depth 16 to 20 is a common choice for a quick, strong answer, and go movetime 1000 gives a fixed one-second search instead. Measure on your own server and cap the depth users can request.

Need the best move right now?

Set up any position and let Stockfish 19 show you the move. No install, no API key.

Open the Calculator Stockfish Online

Put What You Learned Into Practice

Try Calculator Solve Puzzles Play vs AI

Want more? Try Pro — Try Pro for unlimited AI coaching, 3650 ELO depth, Smart Tactics & Human Mode

Learn chessHow to set up a chess boardCastlingEn passantStalemateChess notation
Chess openingsItalian GameSicilian DefenseCaro-Kann DefenseQueen's GambitFried Liver Attack
CalculatorAnalysis BoardPlay vs ComputerOpeningsSolverStockfish OnlinePuzzles2 PlayersELO TestELO CalculatorCheckmate CheckerPricingBlogAboutContactFeedbackPrivacy PolicyTerms of ServiceRefund PolicyCookie PolicyDisclaimer

© 2025 - 2026 ChessNextMove.