Display website visitor locations in real-time using Cloudflare and Redis.
See it live at multiplayer-globe.pages.dev | Start hacking on it in a dev container
Inspired by Cloudflare's multiplayer-globe-template and the NuxtHub implementation.
🪶Lightweight: production build ships just 16.7kb of JS, including the WebGL renderer, svelte runtime, and realtime communication.
A /visitors
websocket endpoint is created in the src/pages/visitors.ts file.
The endpoint uses locals.upgradeWebSocket()
provided by the astro-cloudflare-websocket
adapter.
When the app.svelte component is loaded on the browser, it connects to the /visitors
websocket endpoint.
The endpoint uses the visitor location provided by Cloudflare and aggregates it in a ValKey (open source Redis) server.
Everytime a location is added or removed, the ValKey server broadcasts an event to all connected workers, acting as the single point of coordination. Each worker then forwards the locations of currently connected visitors to its connected browser over the websocket connection.
Make sure to install the dependencies with pnpm:
pnpm install
Start a valkey server with the following command:
docker run --rm -p 6379:6379 valkey/valkey:8.0.2-alpine3.21
If the valkey server is not running on the same device as the development server, you can provide the options as the following variables in .dev.vars
(see Local Development with Secrets | Cloudflare Docs):
VALKEY_HOST=db.local
VALKEY_PORT=6379
VALKEY_USERNAME=multiplayer-app
VALKEY_PASSWORD=multiplayer_password
VALKEY_DB=0
See Secrets on deployed Workers | Cloudflare Docs for information on setting up secrets for the production environment.
Start the development server on http://localhost:4321
:
pnpm dev
The production code runs on Cloudflare's workerd
runtime instead of Node.js. You can preview the website realistically with wrangler
which can run the production build locally.
pnpm exec astro build
pnpm exec wrangler pages dev
pnpm exec astro build
pnpm exec wrangler pages deploy