Server¶
The server: one per gamemode. It owns the players, vehicles, peds, zones and worlds, fires events, and runs the network.
const server = new Server({ port: 7777, name: "My server" });
server.on("playerJoin", (player) => player.send(`Welcome, ${player.name}`));
server.listen();
Constructor¶
new Server(options?)¶
Creates the server. Nothing is listening until listen().
Parameters
| Name | Type | Description |
|---|---|---|
options |
ServerOptions |
Optional. See below. |
ServerOptions
| Field | Type | Default | Description |
|---|---|---|---|
port |
number |
7777 |
UDP port to listen on. |
name |
string |
The server's name, shown on the loading screen and in the pause menu. | |
maxPlayers |
number |
32 |
Player slots. |
startMoney |
number |
0 |
Money each player starts with. |
indicators |
{ keys?, autoCancel?, sound? } |
all on | Vehicles' indicators. keys: drivers work them with keys, by default , (left), . (right) and ; (hazards), each again to turn it off. Players can rebind these in Settings, Controls (actions). autoCancel: left or right go off by themselves after the turn, as a real stalk does. sound: the driver's tick, a client file, or false for none (default: SAGL's own). vehicle.indicators sets them whatever these say. |
carjacking |
boolean |
true |
Players can pull each other out of vehicles (F at a vehicle another player drives), as in SA-MP: their game drags them out, on every screen. playerCarjack hears it. |
splash |
boolean \| { timeoutMs? } |
false |
Players' loading screen stays up after they join, as a splash screen, until you hide it (player.splash.hide()); set the scene behind it first. timeoutMs (default 30000) hides it anyway, with a warning. |
gameEntrances |
boolean |
true |
The game's own entrances (yellow door markers into its interiors) work. Off, only the server puts players in interiors (player.interior), as SA-MP's DisableInteriorEnterExits. |
skinAnimations |
boolean |
false |
Players walk and run like their skin rather than CJ (per player: player.skinAnimations). |
weather |
number |
Weather.SunnyLA |
World 0's weather. |
time |
{ hour, minute, frozen? } |
12:00, frozen | In-game time at startup. |
trustedProxies |
string[] |
Proxy mode: only accept players through these IPs, trusting the player IP they forward. | |
tickMs |
number |
5 |
How often the network is serviced, in milliseconds. |
clientFiles |
string |
A directory players download and cache: client files. | |
branding |
Branding |
The server's logo, background and colours. | |
auth |
AuthMiddleware |
Signing in: checks each player's token as they connect. See Signing in. | |
query |
QueryInfo and values, players, http |
What it tells anyone who asks without joining: see Query. |
Example
const server = new Server({
port: 7777,
name: "Example Roleplay",
maxPlayers: 64,
startMoney: 500,
time: { hour: 20, minute: 0, frozen: false },
clientFiles: new URL("./client", import.meta.url).pathname,
branding: { logo: "branding/logo.png", primary: "#2fb3a0" },
});
Lifecycle¶
listen(options?)¶
Starts accepting players, and the operator console on stdin. Stops cleanly on SIGINT and SIGTERM.
Parameters
| Name | Type | Description |
|---|---|---|
options.console |
boolean |
Start the console. Default true. |
Returns the server.
Throws Error if the UDP port can't be opened.
Example
server.listen(); // with the console
server.listen({ console: false }); // e.g. under a process manager
close()¶
Disconnects everyone and stops the network and console.
Example
Events¶
on(event, listener)¶
Listens to an event. See Events for every event and its arguments.
Parameters
| Name | Type | Description |
|---|---|---|
event |
string |
The event's name, e.g. "playerJoin". |
listener |
function |
Called with the event's arguments. |
Returns the server, so calls chain.
Example
server
.on("playerJoin", (p) => server.broadcast(`${p.name} joined`))
.on("playerQuit", (p, reason) => server.broadcast(`${p.name} left (${reason})`));
off(event, listener)¶
Stops a listener added with on.
Parameters
| Name | Type | Description |
|---|---|---|
event |
string |
The event's name. |
listener |
function |
The same function that was passed to on. |
Example
const greet = (p: Player) => p.send("Hi!");
server.on("playerSpawn", greet);
setTimeout(() => server.off("playerSpawn", greet), 60_000);
Players¶
players¶
Every connected Player.
Example
player(id)¶
A connected player by id.
Parameters
| Name | Type | Description |
|---|---|---|
id |
number |
The player's id (player.id). |
Returns the player, or undefined if nobody has that id.
Example
server.console.command("heal", "heal <id>", ([id]) => {
const p = server.player(Number(id));
if (!p) throw new Error("no such player");
p.health = 100;
});
broadcast(text, color?, options?)¶
Shows a message to every player.
Parameters
| Name | Type | Description |
|---|---|---|
text |
string |
The message. {RRGGBB} colours what follows; {key:ID} shows an action's key. |
color |
number |
Optional 0xRRGGBB, e.g. Color.Green. Default white. |
options.markdown |
boolean |
The text is markdown (bold, italic, code, links) instead of {RRGGBB} colours. |
Example
randomSkin()¶
Returns a random valid ped model id.
Example
Name tags¶
How everyone's name tags show: within distance m (default 70), hidden
behind buildings and objects (lineOfSight, default true), with their id
(ids, default true), with health and armour bars under them (bars,
default false). Setting it changes what's given. Each player's own tag:
player.nameTag.
Gang zones¶
server.createGangZone(area: { minX, minY, maxX, maxY }, color): GangZone
server.gangZones: GangZone[]
zone.show(player?) / zone.hide(player?)
zone.flash(color) / zone.stopFlash()
zone.color; zone.shownTo(player); zone.destroy()
Coloured rectangles on the radar and the maps (SA-MP's gang zones: turfs,
no-go areas). A zone shows to no one until show(): to one player, or
(none given) everyone, players joining later too. flash makes it
alternate with another colour, for everyone who sees it. Colours are
0xRRGGBBAA or "#RRGGBB[AA]"; see-through ones suit them.
const turf = server.createGangZone({ minX: 2400, minY: -1750, maxX: 2550, maxY: -1630 }, 0x00ff0060);
turf.show();
turf.flash(0xff000080); // a gang war
stuntBonus¶
The game's stunt bonuses for everyone (SA-MP's EnableStuntBonusForAll),
players joining later too; default true. player.stuntBonus changes one
player's.
auth, authTimeout¶
server.auth = async ({ token }) => { /* ... */ }; // or null: anyone can join
server.authTimeout = 15_000;
Signing in: a function that checks each player's token (sagl.exe
--token) as they connect, and lets them in (with a name, account id and
metadata) or turns them away. authTimeout is how long it may take, in
ms. See Signing in.
query¶
What the server tells anyone who asks without joining: server lists, websites, the game's browser. It covers the gamemode's description, links, tags and values, how much of the player list to show, and an optional HTTP endpoint. See Query.
Claims¶
claims¶
First come, first served: one player at a time holds a thing (a payphone, a seat, a job), by any key.
| Member | Description |
|---|---|
take(key, player, { ms? }) |
True if they now hold it (it was free, or already theirs); false if someone else does. Let go after ms, if given. |
release(key, player?) |
Lets go of it (only if player holds it, when given). |
holder(key) |
Who holds it, or null. |
What a player held is free when they leave.
server.channel("payphone").on((player, msg) => {
if (player.isNear(PHONE, 2) && server.claims.take("payphone", player, { ms: 15_000 })) {
server.channel("payphone").broadcast({ answeredBy: player.id });
}
});
Explosions¶
createExplosion(position, type?, { to? })¶
An explosion at a spot, as SA-MP's CreateExplosion: the game's own
(ExplosionType: Grenade, Molotov, Rocket, Car, Small, Tiny...),
its blast, fire and damage, in the games of to (default everyone). It's
no one's: a player it hurts is hurt as by a fall (no attacker).
Objects, pickups and labels¶
createObject(model, position, rotation?, options?),
createPickup(options) and labels.add(text, at, options?): see
Objects, pickups and labels.
Vehicles¶
createVehicle(model, position, heading?, options?)¶
createVehicle(model: number, position: Vector3, heading?: number, options?: VehicleOptions): Vehicle
Creates a Vehicle for everyone, standing on the ground at
position.
Parameters
| Name | Type | Description |
|---|---|---|
model |
number |
Vehicle model, 400-611 (e.g. 411 Infernus, 522 NRG-500). |
position |
Vector3 |
Where, in world coordinates. |
heading |
number |
Degrees, 0 north, anticlockwise. Default 0. |
options |
VehicleOptions |
Optional. See below. |
VehicleOptions
| Field | Type | Description |
|---|---|---|
colors |
[number, number] |
Primary and secondary colour from the game's palette, 0-126. Random if left out. |
radio |
number |
RadioStation. Left out: the game's choice for the model. |
world |
number |
Virtual world. Default 0. |
ambient |
boolean |
Treat it as traffic: removed when nobody is near. |
respawnDelay |
number |
Seconds after it's wrecked or abandoned that it's put back new. Left out: never. |
plate |
string |
Licence plate, up to 8 of A-Z, 0-9 and space. Random if left out. |
Returns the new vehicle.
Throws RangeError if the model isn't a vehicle.
Example
const car = server.createVehicle(411, { x: 2493, y: -1660, z: 13.3 }, 90, {
colors: [1, 1],
plate: "EXAMPLE",
respawnDelay: 120,
});
vehicles¶
Every vehicle, ambient traffic included.
Example
vehicle(id)¶
Parameters
| Name | Type | Description |
|---|---|---|
id |
number |
The vehicle's id. |
Returns the vehicle, or undefined.
destroyVehicle(vehicle)¶
Removes a vehicle for everyone; the same as vehicle.destroy().
Parameters
| Name | Type | Description |
|---|---|---|
vehicle |
Vehicle |
The vehicle to remove. Its occupants are put out first. |
Peds¶
createPed(model, position, heading?, options?)¶
Creates a Ped (an NPC) for everyone. The nearest player's game runs its AI.
model is a ped model (skin), or one of the story's characters by name:
"ryder", "sweet", "smoke", "cesar", "ogloc", "tenpen",
"woozie", "truth"... They aren't models of their own: each player's
game loads them into one of its ten special-character slots, as the game's
missions do, so at most ten different characters can be near a player at
once (more wait for a slot). A name the game hasn't makes a ped nobody
sees (and says so in their client log). ped.character is the name.
const ryder = server.createPed("ryder", { x: 2459, y: -1691, z: 13.5 }, 0, { mission: true });
await ryder.say({ dialogue: "RYD2_AA", table: "RYDER2" });
Parameters
| Name | Type | Description |
|---|---|---|
model |
number | string |
Ped model (skin), or a story character's name. |
position |
Vector3 |
Where its feet are. |
heading |
number |
Degrees. Default 0. |
options |
PedOptions |
Optional. See below. |
PedOptions
| Field | Type | Default | Description |
|---|---|---|---|
world |
number |
0 |
Virtual world. |
weapon |
number |
0 |
Weapon in its hand. |
health |
number |
100 |
|
behaviour |
"stand" | "wander" |
"stand" |
What it does when nothing's happening. |
mission |
PedSettings | true |
A mission character: see mission settings. | |
visibleTo |
Player[] | "world" |
"world" |
Who sees it: see ped.visibleTo. |
controller |
Player |
Whose game runs it: see ped.controller. |
Returns the new ped.
Throws RangeError if the model isn't a ped.
Example
const guard = server.createPed(280, { x: 1550, y: -1675, z: 16.2 }, 90, {
weapon: Weapon.Pistol,
health: 200,
});
peds, ped(id), destroyPed(ped)¶
Every ped (the ambient population included), one by id, and removing one
(the same as ped.destroy()).
Example
Zones, garages and cull zones¶
createZone(shape)¶
createZone(shape: { center: Vector3; radius: number; world?: number }
| { min: Vector3; max: Vector3; world?: number }): Zone
Watches an area: a sphere or an axis-aligned box. Players moving in, out
and around it fire zoneEnter, zoneLeave and zoneMove.
Parameters
| Name | Type | Description |
|---|---|---|
shape.center, shape.radius |
Vector3, number |
A sphere. |
shape.min, shape.max |
Vector3 |
Or a box between two corners. |
shape.world |
number |
Only players in this world trigger it. Default: any. |
Returns the new Zone.
Example
const bank = server.createZone({ center: { x: 1462, y: -1012, z: 26.8 }, radius: 5 });
server.on("zoneEnter", (p, z) => { if (z === bank) p.send("Welcome to the bank"); });
zones, destroyZone(zone)¶
Every zone (garage zones included), and removing one.
garages, garage(id)¶
The game's garages, by id.
Example
vehicleColors¶
readonly vehicleColors: VehicleColors
vehicleColors.add(rgb: number): number // your colour's id, 128 up
vehicleColors.custom: number[] // your colours' ids
vehicleColors.rgb(id: number): number | undefined
Car colours: the game's (0-127), and your own. Add a colour (0xRRGGBB) and
you get an id, 128 up, that works anywhere a colour does: vehicle.colors,
createVehicle, and the mod shops' colour grid, where yours are added by
default. You can add up to 128, and adding the same colour twice gives the
same id. Players get them as they join.
const teal = server.vehicleColors.add(0x00b3b3);
const car = server.createVehicle(429, at, 0, { colors: [teal, 1] });
screenEffects¶
Screen effects (built in, or your shaders) on everyone's screen, players joining later too.
payNSpray, modShops¶
The game's Pay 'n' Sprays and mod shops, on by default.
createCullZone(zone)¶
createCullZone(zone: {
min: Vector3; max: Vector3; world?: number;
audio?: number; attributes?: number;
mirror?: { axis: 0 | 1 | 2; sign: 1 | -1; coord: number };
}): CullZone
An area with the game's interior effects. See CullZone.
Parameters
| Name | Type | Description |
|---|---|---|
min, max |
Vector3 |
The box. |
world |
number |
Default: every world. |
audio |
number |
AudioZone: interior music and ambience. |
attributes |
number |
ZoneAttribute bits. |
mirror |
object |
A mirror plane across axis at coord, facing sign. |
Returns the new cull zone.
Example
server.createCullZone({
min: { x: 285, y: -41, z: 1000 }, max: { x: 300, y: -30, z: 1005 },
audio: AudioZone.AmmuNation,
attributes: ZoneAttribute.NoRain | ZoneAttribute.CameraCloseIn,
});
destroyCullZone(zone)¶
Worlds, time and weather¶
world(id)¶
A virtual world's settings: its time, weather and population. See World.
Parameters
| Name | Type | Description |
|---|---|---|
id |
number |
The world. 0 is the default world. |
Example
setWorldView(viewer, target, visible?)¶
Lets players in viewer see (but not meet) players and vehicles in
target, one way.
Parameters
| Name | Type | Description |
|---|---|---|
viewer |
number |
The world that sees. |
target |
number |
The world it sees. |
visible |
boolean |
Default true; false stops it. |
Example
worldSees(viewer, target)¶
Returns whether viewer sees target.
population¶
World 0's ambient population (and every world's without its own). See Population.
Example
weather¶
World 0's weather (Weather).
Example
time¶
time: { hour: number; minute: number; frozen: boolean } // get
time = { hour: number; minute: number } // set
World 0's in-game time. Setting it keeps it frozen or running as it was.
Throws RangeError when set outside 00:00-23:59.
Example
trafficLights¶
World 0's traffic lights (every world's without its own): synced for everyone, held, set or retimed. See TrafficLights.
freezeTime(), unfreezeTime()¶
Stops or starts world 0's clock.
Cutscenes¶
playCutscene(players, name, options?)¶
Plays one of the game's own cutscenes (from anim/cuts.img, e.g.
"ryder2a", "sweet1a") for these players together:
- Each game loads it: their screen fades out and their controls go off.
- When everyone's has loaded (or after
loadTimeout), it starts for all of them at once. Anyone still loading misses it. doneresolves when everyone's has finished, and they're back where they were, in their own skin.
The cutscene's CJ is CJ for everyone, wearing the player's clothes if they play as CJ. (Players with other skins currently see him in his underwear. Their own skin can't stand in for him: the cutscene's animation doesn't fit other peds' skeletons.)
The game's skip button is a vote: nobody skips on their own, so everyone sees the same thing. From the start, each player sees how to vote and how the vote stands ("Skip 0/2: press Space or Enter"; also the left mouse button or a gamepad's A, as in the game).

| Option | Type | Description |
|---|---|---|
skip |
"vote" | "leader" | "anyone" | "none" |
"vote" (default): it skips once a majority of the watchers have pressed skip. "leader": the first player's press skips it. "anyone": any press. "none": no skipping. |
skipVotes |
number |
For "vote": it skips once more than this share of the watchers have voted (everyone at most). Default 0.5, a majority: 2 of 2, 2 of 3, 3 of 4. 1: everyone. |
loadTimeout |
number |
How long to wait for slow loaders (ms). Default 20 000. |
Returns a CutscenePlay:
| Member | Description |
|---|---|
done |
A promise of { skipped, players }: whether it was skipped (or stopped), and who watched it. Never rejects. |
stop() |
Ends it for everyone now. |
over |
Whether it has finished for everyone. |
In a mission, use m.cutscene(): it
plays for the party, and stops if the mission ends.
Client scripts, files and branding¶
clientScripts¶
JavaScript every player's game runs. See ClientScripts.
channel(name)¶
A named Channel to and from client scripts, made on first use.
Parameters
| Name | Type | Description |
|---|---|---|
name |
string |
1-64 characters; sagl: is reserved. |
Throws RangeError for a bad name.
Example
server.channel("chat").on((player, text) => {
server.channel("chat").broadcast({ from: player.name, text: String(text) });
});
clientFiles¶
What players download from the clientFiles directory.
Example
const total = server.clientFiles.reduce((n, f) => n + f.size, 0);
console.log(`${server.clientFiles.length} client files, ${(total / 1e6).toFixed(1)} MB`);
rescanClientFiles()¶
Reads the clientFiles directory again, for players joining from now.
Returns how many files there are.
Example
branding¶
The server's look, for players joining from now. See branding.
Branding
| Field | Type | Description |
|---|---|---|
logo |
string |
A client file: a square PNG or JPEG, up to 1 MB. |
background |
string |
A client file shown behind the loading screen. |
primary |
"#RRGGBB" | 0xRRGGBBAA |
Menu items, headings, bars. |
secondary |
"#RRGGBB" | 0xRRGGBBAA |
Behind focused items, under bars. |
showName |
boolean |
The loading screen shows the name beside the logo. Default false. |
Throws Error, saying why, if the logo isn't a square image client file
or the background isn't a client file.
Example
draw¶
Drawing on everyone's screen, players joining later included. See ScreenDraw.
map¶
Everyone's pause menu map. See GameMap.
console¶
The operator console. See Console.
options¶
The options the server was created with.
Server.protocolVersion¶
The protocol version clients must speak.