← Back to the blog

· 9 min read

Tutorial: an online leaderboard for your Godot game with Cloudflare Workers and D1

Step by step: a local high score with ConfigFile, a D1 database, a Worker of about a hundred lines and the Godot client. With an example repo and a section on how to harden it.

TutorialGodotCloudflare WorkersD1

This tutorial is the second part of An online leaderboard for my web game with Cloudflare Workers and D1, where I explain why I built it this way and which alternatives I looked at. Here we get straight to it: we’ll build, step by step, an online ranking for a Godot game, plus the local high score that goes with it.

The full code is in an example repo you can clone and copy into your game. It is independent of Cutastrophe.

What you need: Godot 4.4 or higher, Node.js 22.12 or higher (what current Wrangler requires) and a free Cloudflare account. To test locally you don’t even need the account.

1. What we’re building

A local high score per game mode and an online ranking with each player’s best score, with no accounts or passwords.

Godot (HTTPRequest) ──►  Worker /scores  ──►  D1 (scores table)

The Worker exposes two routes: GET /scores?mode=normal&limit=10 returns the top and POST /scores uploads a score. Each player is identified by a random id that the game generates and stores on their device.

2. The local high score

We start with the simplest part, which also works offline. Godot has ConfigFile, which stores key-value pairs in a text file inside user://. In a web export, Godot keeps that file in the browser’s storage, so the record survives between sessions without you doing anything.

Create scripts/records.gd and register it as an autoload named Records (Project → Project Settings → Autoload):

extends Node

## Local high scores: one key per mode, stored in user://records.cfg.
## In a web export, Godot keeps `user://` in the browser's storage, so it survives between sessions.

const PATH: String = "user://records.cfg"


## Best score saved for a mode (0 if none).
func best(mode: String) -> int:
	var cfg := ConfigFile.new()
	if cfg.load(PATH) != OK:
		return 0
	return cfg.get_value("records", mode, 0)


## Saves the score if it beats the record. Returns true when it is a new record.
func save(mode: String, score: int) -> bool:
	if score <= best(mode):
		return false
	var cfg := ConfigFile.new()
	cfg.load(PATH) # Fine if it doesn't exist yet: we start from an empty config.
	cfg.set_value("records", mode, score)
	cfg.save(PATH)
	return true

When a run ends, call Records.save("normal", score). It returns true if it’s a new record, in case you want to show a notice. One key per mode lets “normal” and “hard” keep separate records.

3. The database in D1

D1 is Cloudflare’s SQLite database. From a new server/ folder, install Wrangler (the command-line tool) and create the database:

npm install --save-dev wrangler
npx wrangler login
npx wrangler d1 create leaderboard-example

The last command prints a database_id. Save it in wrangler.toml, along with the Worker’s name:

name = "leaderboard-example"
main = "src/index.js"
compatibility_date = "2026-11-01"

[[d1_databases]]
binding = "DB"
database_name = "leaderboard-example"
database_id = "REPLACE_WITH_YOUR_DATABASE_ID"

Now the schema, in schema.sql. The table keeps one record per player and mode:

CREATE TABLE IF NOT EXISTS scores (
  player_id  TEXT    NOT NULL,
  mode       TEXT    NOT NULL CHECK (mode IN ('normal', 'hard')),
  name       TEXT    NOT NULL,
  score      INTEGER NOT NULL,
  updated_at INTEGER NOT NULL,
  PRIMARY KEY (player_id, mode)
);

CREATE INDEX IF NOT EXISTS idx_scores_mode_score ON scores (mode, score DESC);

The (player_id, mode) primary key is the most important decision: it stops a player from having two rows in the same mode. The CHECK rejects modes that don’t exist, and the index speeds up the top query. Create the table in the remote database (and, if you want to test locally, in a local one):

npx wrangler d1 execute leaderboard-example --remote --file=schema.sql
npx wrangler d1 execute leaderboard-example --local --persist-to .wrangler/state --file=schema.sql

4. The Worker

Create src/index.js. We’ll build it in parts; the complete file is in the repo.

Constants and CORS. A web game runs on another origin (itch.io, your own site), so the browser blocks its requests to the Worker unless the Worker answers with CORS headers. This is what surprises people most, because it doesn’t fail when you test locally.

const MODES = ["normal", "hard"];
// Set this just above the real maximum score of YOUR game.
const MAX_SCORE = 10000;
const MAX_NAME = 16;
const MIN_SECONDS_BETWEEN_POSTS = 10;
const MAX_LIMIT = 50;

const CORS = {
  "Access-Control-Allow-Origin": "*",
  "Access-Control-Allow-Methods": "GET, POST, OPTIONS",
  "Access-Control-Allow-Headers": "Content-Type",
  "Access-Control-Max-Age": "86400",
};

Validate everything that arrives. The Worker trusts nothing that comes from the client: it checks the id format, the mode and that the score is an integer between 1 and the cap. The name is stripped of control characters and repeated spaces, and trimmed.

if (!/^[A-Za-z0-9]{16,64}$/.test(playerId)) return json({ error: "bad player_id" }, 400);
if (!MODES.includes(mode)) return json({ error: "bad mode" }, 400);
if (!Number.isInteger(score) || score <= 0 || score > MAX_SCORE) return json({ error: "bad score" }, 400);

Keep only the best score. This is where the primary key works. The upsert inserts the row and, if it already existed, keeps the higher of the two scores. There’s no need to query before writing.

await env.DB.prepare(
  `INSERT INTO scores (player_id, mode, name, score, updated_at) VALUES (?, ?, ?, ?, ?)
   ON CONFLICT (player_id, mode) DO UPDATE SET
     name = excluded.name,
     score = MAX(scores.score, excluded.score),
     updated_at = excluded.updated_at`
).bind(playerId, mode, name, score, now).run();

Notice that every value goes in with ? and .bind(), never concatenated into the query text. That way a malicious name can’t inject SQL.

The rank and the top. A player’s rank is how many scores are higher, plus one. The top is an ordered query, with a maximum limit so nobody can request the whole table.

const { results } = await env.DB.prepare(
  "SELECT name, score FROM scores WHERE mode = ? ORDER BY score DESC, updated_at ASC LIMIT ?"
).bind(mode, limit).all();

The Worker also answers 429 if the same player submits twice within 10 seconds. Later we’ll see why that is only a soft brake.

5. The client in Godot

Create scripts/leaderboard.gd and register it as the Leaderboard autoload. On startup it generates (only once) the player’s id and saves it with the name:

func _ready() -> void:
	var cfg := ConfigFile.new()
	cfg.load(PATH)
	player_id = cfg.get_value("player", "id", "")
	player_name = cfg.get_value("player", "name", "")
	if player_id.is_empty():
		var crypto := Crypto.new()
		player_id = crypto.generate_random_bytes(16).hex_encode()
		_save()

The two public functions are fetch_scores() and submit(). Both use await, so you can call them from any function without blocking the game:

func fetch_scores(mode: String, limit: int = 10) -> Variant:
	var data: Variant = await _request("/scores?mode=%s&limit=%d" % [mode, limit], HTTPClient.METHOD_GET, "")
	if data is Dictionary and data.get("scores") is Array:
		return data["scores"]
	return null

fetch_scores() returns the list, or null if the connection failed, and submit() returns a dictionary with ok, best and rank, or with error. Underneath both is _request(), which creates an HTTPRequest node, waits for the response with await http.request_completed, frees it and parses the JSON. It has an 8-second timeout so a slow server doesn’t leave the game hanging.

One constant matters: BASE_URL. To test locally it’s http://127.0.0.1:8787; when you publish, change it to your Worker’s URL.

6. A minimal interface

In the real game, the final screen has a name field and a button. The logic behind that button is mostly error handling, because the server can reject the submission or the network can fail. This is the simplified version from the repo:

func _submit() -> void:
	if _score <= 0:
		_status.text = "Play first."
		return
	var player := _name_edit.text.strip_edges()
	if player.is_empty():
		_status.text = "Type a name first."
		return
	_submit_button.disabled = true
	_status.text = "Sending..."
	var res := await Leaderboard.submit(player, _mode(), _score)
	_submit_button.disabled = false
	if res.get("ok", false):
		_status.text = "Sent! You are #%d." % int(res.get("rank", 0))
		_refresh_top()
	elif res.get("error") == "too fast":
		_status.text = "Too fast, wait a few seconds."
	else:
		_status.text = "Could not send the score."

Two habits worth copying: disable the button while sending (so you don’t submit twice) and tell the “too fast” error apart from a network failure, because the player benefits from knowing which one it is.

To see the ranking, the repo includes scripts/demo.gd, a screen built in code with a mode selector, a play button that gives a random score, the name field and the top.

7. Test and publish

Locally, from server/:

npm run db:init:local   # creates the table in a local D1
npm run dev             # Worker at http://127.0.0.1:8787
npm test                # in another terminal: Worker smoke tests

The smoke tests check that a valid score is accepted, that the rate limit answers 429, that the name is cleaned, that invalid values are rejected with 400 and that the CORS preflight answers 204. It’s also worth testing by hand that a lower score doesn’t lower the best: send 700, wait more than 10 seconds and send 300; best should stay at 700.

To publish:

npx wrangler d1 execute leaderboard-example --remote --file=schema.sql
npx wrangler deploy

deploy prints your Worker’s URL (https://...workers.dev). Put it in BASE_URL, export your game and you’re done. D1 is available on the Workers free plan; check the pricing page for the current limits.

8. How to harden it

Before thinking about improvements, a repeat of the warning: this ranking is not cheat-proof. The score is computed by the game on the player’s machine, and anyone who can see the game’s requests can replay them with other values. Whether that’s enough depends on what’s at stake. If it’s just for fun, probably yes. If there are prizes, you need more. These are the options, from least to most work; none of them is implemented in the example repo.

Tighten the cap. MAX_SCORE should be just above your game’s real maximum. To find it, compute the best possible run (with a script that simulates it, if your game allows). It narrows the room for cheating but doesn’t remove it: sending the maximum will still be possible.

Rate limit more carefully. The example’s 10-second limit is per player_id, and a new id dodges it. Cloudflare offers a rate limiting binding configured in Wrangler, but with two caveats its documentation points out: the limits are approximate and apply separately in each location, and it advises against using the IP as the key because many people share one (a school network, for example, would be blocked entirely). If you need exact counters, the alternative is a Durable Object, like the one I use in this site’s chat.

Validate the run on the server. This is the only option that attacks the root of the problem. Instead of sending the score, the game sends what the player did (the moves, together with the random seed) and the Worker recomputes the score. It only works if your game is deterministic and its logic can be reproduced on the server, which usually means rewriting it in JavaScript or compiling it to WebAssembly. For a small game it can be worth it; for a large one, almost never. And even then it doesn’t stop a program that plays perfectly.

What doesn’t work. Signing submissions with a secret key shipped inside the game, or obfuscating the requests, only adds friction: the key travels inside the exported game, and anyone who takes it apart will find it.

Clean up afterwards. A realistic fallback plan is to review the ranking from time to time and delete whatever looks suspicious directly in the database:

npx wrangler d1 execute leaderboard-example --remote --command "DELETE FROM scores WHERE score > 6000"

Change the threshold to one that makes sense for your game, and look first at which rows you would delete with a SELECT.

Wrapping up

You now have a local high score, a database, a Worker and a client, and it all fits in a handful of files. If something doesn’t work, it’s most likely CORS or the database_id; check those two first. And if you get some use out of this example in your own game, I’d love to see it.