Plugins
An engine plugin is an npm package that adds code to the client, the game server or both, and can bring prefabs and assets. Install one with the CLI:
npx @mavonengine/cli install my-custom-plugin
Available plugins
The official plugins are listed in plugins.json at the root of the MavonEngine repository:
| Plugin | Runs on | |
|---|---|---|
@mavonengine/http-monitoring | server | The game server dashboard in the browser |
@mavonengine/chat | client and server | In-game text chat with rate limiting, mutes, proximity chat and an admin API |
@mavonengine/sqlite | server | A SQLite database for the game server and its plugins, on Node's built-in node:sqlite |
@mavonengine/auth | client and server | Player accounts with logins and sessions, so the game server knows who connects |
@mavonengine/mail | server | Mail from the game server, queued and retried, over SMTP or any nodemailer transport |
@mavonengine/notifications | client and server | Notify players in the game, by mail and kept to read later: player.notify(new LevelUp()) |
mavonengine plugins prints the list, read from GitHub each time, so a new plugin shows up as soon as it is added. The same list appears, with what your project doesn't have yet, in:
- the Plugins tab of the dashboard, where
iinstalls the selected plugin undermavonengine dev; - the Plugins view of the editor, which also shows each plugin's readme and installs any other package;
- the
available_pluginstool of the MCP server, so an assistant can suggest a plugin instead of building what one already does.
Installing from the dashboard or the editor asks first, since a package's code runs on your machine, then adds the plugin to mavonengine.json and restarts the dev servers.
To list a plugin of your own, add an entry to plugins.json: package (the npm name) is required; name, description, target, engine (the supported @mavonengine/core range), homepage and readme (the URL of its README as Markdown) are optional.
mavonengine.json
Enabled plugins are listed in mavonengine.json in the project root, next to package.json:
{
"appUrl": "https://mygame.com",
"appName": "My Game",
"plugins": {
"my-custom-plugin": { "enabled": true, "prefabs": ["Tree"], "options": { "density": 2 } }
}
}
| Field | Description |
|---|---|
enabled | false turns the plugin off without uninstalling it |
prefabs | The plugin prefabs the project uses. The editor adds a prefab when you place it. Only these prefabs' assets (plus the shared ones) go into the release |
options | Passed to the plugin as ctx.options |
Next to plugins, the file says what goes for the whole project. All of these are optional:
| Key | |
|---|---|
appUrl | Where the game is, like https://mygame.com. Links that leave the game, such as those in mails, point there. MAVONENGINE_APP_URL overrides it, for example per deployment. A production server never builds such links from the address a request names, so set it before deploying |
appName | The game's name, in mails and in the browser tab: %MAVONENGINE_APP_NAME% in the client's index.html becomes it, in dev and in the build (MavonEngine without one). mavonengine create sets it from the project's name. Rebuild the client after changing it |
database | The database plugin to use, when more than one is enabled |
auth | The auth plugin to use, when more than one is enabled |
notifications | The notifications plugin that notify() sends through, when more than one is enabled |
Without database, auth or notifications, the first plugin of that kind that is enabled is used. Server plugins get appUrl and appName as ctx.appUrl and ctx.appName; the server's appUrl and appName options win over the file.
The client reloads when the plugins change. Restart the game server to load a new server plugin.
Setting up a project
Projects made with mavonengine create are already set up. For an existing project:
// client: before new Game()
import Game from '@mavonengine/core/Game'
import plugins from 'virtual:mavonengine/plugins'
Game.usePlugins(plugins)
// server: the directory with mavonengine.json
const server = new MyServer(logger, physicsWorld, { plugins: { root: projectRoot } })
await server.start()
The client's Vite config must extend @mavonengine/core/vite.config, which provides virtual:mavonengine/plugins, serves plugin assets in dev and copies them into the release.
Writing a plugin
Add a mavonengine field to the plugin's package.json:
{
"name": "my-custom-plugin",
"type": "module",
"mavonengine": {
"target": "both",
"client": "./dist/client.js",
"server": "./dist/server.js",
"engine": "^0.0.25",
"publish": "./publish",
"assets": {
"dir": "./assets",
"shared": ["textures/bark.png"],
"prefabs": {
"Tree": ["models/tree.glb"],
"Rock": ["models/rock.glb"]
}
}
}
}
target:client,serverorboth. The matching entries are required.assets: paths relative todir(defaultassets), served at/plugins/<package>/<path>. In dev all of them; in a release only the shared ones and those of used prefabs.publish: a directory of files the project may change, such as a mail layout, see Files a project can change.
Each entry default-exports the plugin. Every hook gets the plugin's context last, with package, options, game and logger.
Client
import { defineClientPlugin } from '@mavonengine/core/Plugins/types'
export default defineClientPlugin({
assets: ctx => [{ name: 'tree', type: 'gltfModel', path: ctx.assetUrl('models/tree.glb') }],
setup(ctx) {
ctx.registerPrefab({
name: 'Tree',
spawn: position => ({ object: new Tree(position) }),
})
},
update(delta, ctx) {},
// Dev only, when the editor boots
editor(ctx) {
ctx.editor.on('objectSelected', () => {})
},
})
The client context also has plugin() to use other plugins and registerSceneObject() to add scene object types. A client plugin can also give the token the game connects with, see Authenticating players.
Server
import { defineServerPlugin } from '@mavonengine/core/Plugins/types'
export default defineServerPlugin({
setup(ctx) {},
// Runs after the server's own onHttp routes, before the game client
http(app, ctx) {
app.get('/api/my-plugin/status', (_req, res) => res.json({ ok: true }))
},
onConnection(channel, client, ctx) {},
onDisconnect(channel, ctx) {},
tick(delta, ctx) {},
// May return a promise: the database is closed once it settled
destroy(ctx) {},
})
The server context also has server, projectRoot, appUrl, appName, registerSceneObject(), requireAdmin, adminToken, db, table(), queue, identity(), plugin() and publishedFile(). ctx.queue is the server's job queue: register the plugin's job classes in setup(). Plugins reach the physics world through ctx.game.physicsWorld, see Physics.
The routes a plugin registers are listed with its name on the dashboard's Routes and Plugins tabs. Say what they do with describeRoute().
Using other plugins
A plugin offers something to other plugins with api(), and they get it with ctx.plugin('<package>'). It is undefined when that plugin isn't installed, enabled or running, or has no api, so a plugin can work without the ones it can use:
// @acme/shop: mails a receipt when the project has the mail plugin
export default defineServerPlugin({
http(app, ctx) {
app.post('/api/shop/buy', async (req, res) => {
const order = await buy(req.body)
await ctx.plugin('@mavonengine/mail')?.to(order.email).send(new Receipt(order))
res.json(order)
})
},
})
// @acme/leaderboard: offers its api
export default defineServerPlugin({
api: ctx => ({
top: (limit: number) => ctx.db!.selectFrom(ctx.table('scores')).selectAll().orderBy('score', 'desc').limit(limit).execute(),
}),
})
api() is called once for every plugin, before any plugin's setup(), so a plugin can use another's api in its own setup() whatever order they load in. On the server it runs after the database migrations, so a plugin they turned off has no api. Client and server each have their own: a plugin's client api can differ from its server api.
To give ctx.plugin() the api's type, add it to ServerPluginApis (or ClientPluginApis in the browser):
declare module '@mavonengine/core/Plugins/types' {
interface ServerPluginApis {
'@acme/leaderboard': LeaderboardApi
}
}
@mavonengine/mail, @mavonengine/notifications and @mavonengine/auth offer theirs this way.
Files a project can change
A plugin can let the project change some of its files, such as the layout of its mails. Put them in a directory of the package and name it as publish in the manifest. mavonengine asset:publish <package> copies them into the project's resources/<package>/, and the plugin finds the project's copy with ctx.publishedFile():
import { readFileSync } from 'node:fs'
const layout = readFileSync(ctx.publishedFile('layout.html') ?? new URL('../publish/layout.html', import.meta.url), 'utf8')
publishedFile() is undefined when the project has no copy, so the plugin uses its own.
Admin routes
Guard a plugin's admin routes with ctx.requireAdmin, which asks for the server's admin token, instead of giving the plugin a token of its own:
export default defineServerPlugin({
http(app, ctx) {
app.post('/api/my-plugin/reset', ctx.requireAdmin, (_req, res) => res.json({ reset: true }))
},
})
A plugin that takes the token some other way, such as the password of a login, checks it with ctx.adminToken.matches(candidate). ctx.adminToken.configured tells whether the server has one. The plugin never sees the token itself.
Database
With a database plugin in the project, ctx.db is a Kysely instance shared by the server and all plugins, and undefined without one. A plugin creates its tables with migrations, which run before setup(), and names them with ctx.table() so plugins' tables don't clash:
export default defineServerPlugin({
migrations: {
'001_init': {
async up(db, { table }) {
await db.schema.createTable(table('scores'))
.addColumn('player', 'text', c => c.primaryKey())
.addColumn('score', 'integer', c => c.notNull().defaultTo(0))
.execute()
},
},
},
})
See Database for the rules of migrations, and for the database() hook that makes a plugin a database plugin itself. Likewise, a notify() hook makes a plugin a notifications plugin.
Authenticating players
An auth plugin decides who may connect, before a client gets a player. @mavonengine/auth is one, with accounts, passwords and sessions; write your own for anything else. Its client entry gives the token the game connects with, and its server entry's authorize() checks it:
// client.ts: sent as the Authorization header of the connection request
export default defineClientPlugin({
authorization: () => {
const token = localStorage.getItem('session')
return token ? `Bearer ${token}` : undefined
},
})
// server.ts
export default defineServerPlugin({
async authorize(authorization, request, ctx) {
const account = await findSession(ctx.db, authorization)
if (!account)
return false // 401
if (account.banned)
return 403
return { id: account.id, name: account.username }
},
})
authorize() returns:
| Result | |
|---|---|
An identity, { id, name?, … } | Lets the client in as that account. It is also sent to the client, so keep it to what the player may see |
true | Lets it in without an identity, e.g. as a guest |
false | Turns it away with 401 |
| An HTTP status from 400 to 599 | Turns it away with that status, e.g. 403 for a banned account |
A throw or any other result turns that one client away with 500, and the next client is still asked.
- Reading the identity: other plugins use
ctx.identity(channel), the gameplayer.identityon the server andnetwork.identityon the client. Key anything that should outlast a connection, such as a mute or a score, onidentity.id:channel.idchanges every time the player reconnects. - Refusals on the client: they arrive as the
connectErrorevent of theNetworkManager, with thestatusthe server answered. The token is read when aNetworkManageris made, so to connect again after logging in, make a new one. - One auth plugin: only one is asked. With more than one enabled, set
"auth": "<package>"inmavonengine.json. - Fails closed: when the project has an auth plugin that doesn't run, for example because one of its migrations failed or the package named in
authisn't enabled, the server turns every client away with 503 instead of letting them in unchecked. - The editor connects like a client, so with an auth plugin it needs a token as well. When the server turns it away, the editor's status bar and Network panel say why.
A hook that throws is logged and turned off for that plugin, and the game keeps running.