Server
The Server class is the authoritative multiplayer server. It creates the headless BaseGame, manages client connections, processes commands, broadcasts world state, and serves the game client and its HTTP API.
Setup
import type { ServerChannel } from '@geckos.io/server'
import BaseServer from '@mavonengine/core/Networking/Server/Server'
import Player from './Server/Entities/Player'
export default class Server extends BaseServer<Player> {
protected onConnection(channel: ServerChannel): Player {
// A new client connected: return its player, the server adds it to the world
return new Player(channel.id)
}
protected onCommand(command: any, delta: number): void {
// Process an incoming client command
}
getStateSyncDistance(): number {
// Return the visibility radius (units) for state sync
return 200
}
}
import RAPIER from '@dimforge/rapier3d-compat'
RAPIER.init().then(() => {
const physicsWorld = new RAPIER.World({ x: 0, y: -9.83, z: 0 })
const server = new Server(logger, physicsWorld, {
client: { root: clientDir, dev: process.env.MAVONENGINE_DEV_CLIENT === '1' },
plugins: { root: projectRoot },
})
server.start().then(() => server.openScene('main'))
})
The constructor takes a winston logger, an optional Rapier world (see Physics) and the options below. Inside the server, the game is this.game; elsewhere use Server.instance().
start() returns a promise: with plugins: { root } the plugins are imported first, and plugins' database migrations run before their setup(), so wait for it before relying on them or on server.db.
Options
| Option | Default | Description |
|---|---|---|
httpPort | 8050 | Port of the HTTP server |
client | Serve the game client: { root, dev?, dist? }. With dev the source is served through Vite with hot reload, otherwise the built <root>/dist | |
socketPort | none when client is set, 8081 otherwise | Separate port for the geckos.io game socket, or false |
plugins | { root } to load the plugins enabled in <root>/mavonengine.json, or plugin objects. See Plugins | |
root | plugins.root | Project root with scenes/, used by openScene() |
metrics | { enabled, token, logBufferSize, requestLogSize, logIntervalMs }, see Monitoring | |
adminToken | $MAVONENGINE_ADMIN_TOKEN | The server's admin token |
latencySimulation | { fixedLatency, jitter, packetLoss }, see Latency simulation | |
database | database in mavonengine.json, else the first | Package of the database plugin to use, when more than one is enabled |
auth | auth in mavonengine.json, else the first | Package of the auth plugin to use, when more than one is enabled |
notifications | notifications in mavonengine.json, else the first | Package of the notifications plugin that notify() sends through, when more than one is enabled |
appUrl | appUrl in mavonengine.json | Where the game is, for links that leave it, like in mails. MAVONENGINE_APP_URL overrides both. Plugins get it as ctx.appUrl |
appName | appName in mavonengine.json | The game's name, e.g. in mails. Plugins get it as ctx.appName |
queue | { driver, work, concurrency, queues, pollIntervalMs, retryAfterMs }, see Job Queue | |
stopOnSignals | true | Stop gracefully on SIGINT and SIGTERM, see Stopping |
Ports
When the server serves the client, everything runs on one port (8050 by default): the client, the game socket and the HTTP API. The client needs no second origin, which makes deploying behind a reverse proxy simple.
| Port | Purpose |
|---|---|
8050 | HTTP server: client, API and the game socket |
8081 | Separate geckos.io socket, only when the client is not served or socketPort is set |
Methods to implement
| Method | Description |
|---|---|
onConnection(channel) | Called when a new client connects; return its player entity |
onCommand(command, delta) | Called for each queued command on each tick |
getStateSyncDistance() | Returns the max distance for state sync visibility |
onTick(delta) | Optional, runs every tick after the commands are processed |
Command buffer
Clients send commands (e.g. input frames) with a sequence id. The server queues them, sorts them by sequence id and processes them in order on each tick via onCommand. After a command ran, the player's lastProcessedSequenceId is updated and sent back in the state sync, so the client can drop the inputs the server has already applied. Every state update also carries it as ack, next to the server tick it was taken in, see State packet format.
Scenes
server.openScene('main') // <root>/scenes/main.json
server.openScene('main', { watch: true })
Only the scene objects with a server factory are built. While the client is served through Vite, the file is watched and reloaded when the editor saves it. See Scenes.
Database
With a database plugin such as @mavonengine/sqlite, server.db is a Kysely instance, shared with the plugins. It is undefined without one, and until start() has resolved. Name the game's own tables so they don't start with a plugin's prefix, e.g. game_scores. server.databaseProvider is the package of the plugin in use.
Job queue
server.queue runs jobs in the background of the server, with retries, backoff and delays. Jobs can be dispatched before start() and run once it is done. They are kept in the database with a database plugin, else in memory. See Job Queue.
await server.queue.dispatch(new GrantReward({ player: account.id, coins: 10 }))
Who is connected
With an auth plugin such as @mavonengine/auth, a client is checked before it gets a player, and turned away with an HTTP status when it may not connect. player.identity is then who the player is, as the auth plugin said when it connected:
protected onConnection(channel: ServerChannel): Player {
const player = new Player(channel.id)
// { id, name?, … }: the same id on every reconnect, unlike channel.id
const account = player.identity
if (account)
loadSave(player, account.id)
return player
}
It is undefined without an auth plugin, for a client the plugin let in without an identity, and for bots. The server logs the identity with each connection, and the metrics give each player its account as { id, name, guest }. server.authProvider is the package of the auth plugin in use. See Authenticating players to write one.
player.notify(notification) notifies the player's account through the project's notifications plugin, on every connection the account has open. A player without an identity is skipped, and without a notifications plugin nothing is sent and the log says so. server.notificationsProvider is the package of the notifications plugin in use.
Editor clients
A client that boots the level editor tells the server. The server removes its player, no longer counts it as a player and sends it every entity in the world. Their channel ids are in server.editorChannels.
A server in production (NODE_ENV=production) ignores clients that ask to attach the editor, since the editor is sent the whole world. With an auth plugin the editor needs a session like any client; the editor's status bar says why when the server turns it away.
HTTP endpoints
Register custom HTTP routes using onHttp before calling start():
server.onHttp((app) => {
app.get('/api/status', (req, res) => {
res.json({ players: server.game.world.entities.items.size })
})
})
Your routes run before plugin routes and before the game client, which answers every remaining page request.
Describing routes
GET /api/game/routes lists every route of the server, read from the running Express app: method, path, path parameters, whether the engine, the game or a plugin registered it, and whether it only exists in development. The dashboard's Routes tab and the editor's Server view show that list.
A route is listed without being declared anywhere. To say what it does, put describeRoute() in front of the handler. Everything in it is optional:
import { describeRoute } from '@mavonengine/core/Networking/Server/Http/RouteCatalog'
server.onHttp((app) => {
app.get('/api/scores/:id', describeRoute({
summary: 'One score',
params: { id: 'Id of the player' },
response: '`{ score }`',
}), handler)
})
It takes summary, description, params, query, response, auth and devOnly. Pass devOnly: true for a route you only register in development: a route that doesn't say is listed as served in production too.
Admin token
A game server has one admin token, for everything that changes it or tells what not everyone should know. The engine and every plugin use the same one, so no plugin needs a secret of its own:
MAVONENGINE_ADMIN_TOKEN=… npm start
or adminToken in the server's options. Requests send it as Authorization: Bearer <token>. Without a token, admin routes only answer requests from localhost.
Guard your own admin routes with server.http.requireAdmin:
server.onHttp((app) => {
app.post('/api/restart-round', server.http.requireAdmin, (_req, res) => res.json({ ok: true }))
})
- The token also reads the metrics endpoints and turns them on in production, so
mavonengine dashboardandmavonengine mcptake it for--token. The metrics token stays read-only. - Plugins get the same guard as
ctx.requireAdmin, see Plugins.@mavonengine/chatand@mavonengine/authguard their admin APIs with it, and@mavonengine/http-monitoringtakes it as the password of its login. - The database endpoints take the admin token only, since the database holds what players did.
- Routes behind the guard list who may call them in the route list.
Built-in endpoints
| Path | Description |
|---|---|
GET /api/game/health | Health check |
GET /api/game/metrics | Metrics snapshot (tick time, CPU, bandwidth, players, world, physics, job queue) |
GET /api/game/logs | Recent server log entries |
GET /api/game/requests | Recent HTTP requests |
GET /api/game/routes | Every HTTP route of the server |
GET /api/game/plugins | The project's plugins: version, target, prefabs, whether each one's server entry is running, and which one is the database, the auth and the notifications plugin |
GET /api/game/database | The database plugin, every table with the plugin it belongs to, its columns and row count, and the migrations each plugin ran. Admin token |
GET /api/game/database/tables/:name | A page of a table's rows, with ?offset= and ?limit= (default 50, at most 500). Admin token |
GET /api/game/dev/* | Scene and entity inspection, development only |
GET /api/game/dev/net/* | Recorded packets (/packets, /packets/:id) and who is sent what (/sync), development only. See network debugging |
The metrics, logs, requests, routes and plugins endpoints only answer localhost unless a token is set. See Monitoring.
Latency simulation
Test your netcode against a bad connection. The server delays pongs, state updates and incoming commands:
const server = new Server(logger, physicsWorld, {
latencySimulation: {
fixedLatency: 100, // ms
jitter: 30, // ms
packetLoss: 0.05, // 0 - 1
},
})
The server logs a warning on start while the simulation is on. Never ship it enabled.
Bandwidth tracking
The server tracks sent and received bandwidth. Access it via server.bandwidthTracker, or all metrics via server.metrics. The figures are read from the WebRTC connections' own byte counters, so they cover everything on the connection, not only state updates and commands.
ServerWorld
The server's world is a ServerWorld, which extends BaseWorld and adds player management for connected clients (world.players).
The server maintains its own Three.js scene populated with simplified hitbox meshes rather than full visual geometry. This keeps memory and CPU overhead low while still allowing authoritative raycasts, hit detection, and spatial queries directly against the scene — no need to trust client-reported positions.
Stopping
server.stop() stops the metric timers, the scene watcher, the job queue and the plugins, then closes the database. It returns a promise that settles once the database is closed, after the running jobs and every plugin's destroy() have finished, and never rejects.
The server stops itself that way when the process gets SIGINT (Ctrl+C) or SIGTERM (a deploy, docker stop, mavonengine dev restarting it), then exits. If it hasn't stopped after 2.5 seconds, the process exits anyway. Pass stopOnSignals: false when the game handles these signals itself, and call stop() there. Windows has no SIGTERM: a process killed there stops without this.