- addScore: Adds a score with the player’s name. This will write the score to the Upstash Redis directly from the Edge functions.
- getLeaderBoard: Returns the list of score-player pairs. This call will first check the Edge cache. If the leaderboard does not exist at the Edge Cache then it will fetch it from the Upstash Redis.
Edge caching is deprecated. Please use global database instead.
Project Setup
In this tutorial, we will use Cloudflare Workers and Upstash. You can create a free database from Upstash Console. Then create a Workers project using Wrangler. Install wrangler:npm install -g @cloudflare/wrangler
Authenticate: wrangler login
or wrangler config
Then create a project: wrangler generate edge-leaderboard
Open wrangler.toml
. Run wrangler whoami
and copy/paste your account id to
your wrangler.toml.
Find your REST token from database details page in the
Upstash Console. Copy/paste your token to your
wrangler toml as below:
The Code
The only file we need is the Workers Edge function. Update the index.js as below:Test The API
In your project folder runwrangler dev
. It will give you a local URL. You can
test your API with curl:
Add new scores:
Deploy The API
First change the type in the wrangler.toml towebpack
wrangler publish
. Wrangler will output the URL. If you want to
deploy to a custom domain see
here.