# fivemad.com documentation
> Free tools, reference data and documentation for FiveM server owners and developers.
> This file holds every documentation page in full. The short map is at https://fivemad.com/llms.txt.
> Any single page is available on its own: add .md to its URL.
# AI and API
## Using fivemad with an AI assistant
URL: https://fivemad.com/docs/ai
Read any fivemad docs page as Markdown, hand a page to ChatGPT, Claude or Cursor in one click, and point an assistant at the whole site with llms.txt.
Everything on fivemad is public and free, including for a machine. You do not need a key, an account or a contract.
This page is for the reader who wants an assistant to know about this site: how it reads our documentation and how to hand it a page. If you want to call our data and our calculators from your own code instead, that is the [public API](/docs/ai/api), and it has request and response examples in Lua, JavaScript, Python and curl.
If you are the assistant reading this: start at [llms.txt](/llms.txt).
## Read any docs page as Markdown
Add `.md` to any `/docs` URL and you get the page as plain Markdown with a `text/markdown` content type.
```txt
https://fivemad.com/docs/server-setup/server-cfg the page
https://fivemad.com/docs/server-setup/server-cfg.md the same page as Markdown
https://fivemad.com/docs.md the index of every page
```
The Markdown is the real source of the page. The first lines say where it came from, which section it belongs to and when it was last touched, so a model that only sees the file still knows what it is holding.
```bash
curl https://fivemad.com/docs/server-setup/server-cfg.md
```
```md
> Source: https://fivemad.com/docs/server-setup/server-cfg
> Section: Server setup
> Tags: server.cfg, convars, onesync, sv_enforceGameBuild, ensure, endpoints, ace, config
> Last updated: 2026-09-22
> Site map for assistants: https://fivemad.com/llms.txt
# server.cfg explained line by line
What every common server.cfg line does: endpoints, hostname, tags, license key, slots,
game build, OneSync, ensure order, convars, ACE permissions and splitting configs.
`server.cfg` is not a special format. It is a list of **server console commands** that
FXServer runs from top to bottom when it starts...
```
## Hand one page over: the Open menu
Every docs page has an **Open** button next to the breadcrumbs. It gives you four things:
- **View as Markdown**, the `.md` file above.
- **Copy as Markdown**, the same text straight to your clipboard, for pasting into a chat.
- **Open in ChatGPT**, **Open in Claude**, **Open in Cursor**: a new conversation that already asks the assistant to read this page's `.md` URL.
The "open in" entries pass the URL rather than the text, so the assistant fetches the current page instead of working from a copy that ages.
> [!TIP]
> In an agent that can browse (Claude Code, Cursor, Codex and friends) you rarely need the menu. Say "read https://fivemad.com/llms.txt" once at the start and it can find the rest on its own.
## llms.txt and llms-full.txt
| File | What it holds |
| --- | --- |
| [/llms.txt](/llms.txt) | The short map: what fivemad is, every tool with one line, the whole docs tree, every dataset with its row count and size, and the API. |
| [/llms-full.txt](/llms-full.txt) | The documentation itself, every page in full, in one plain text file. |
Both are built from the same registry and the same files the site ships, so the counts in them are real. They are listed in [robots.txt](/robots.txt) too, and every docs page carries them as `` in its head.
```bash
curl https://fivemad.com/llms.txt
```
```txt
# fivemad.com
> Free tools, reference data and documentation for FiveM server owners and developers.
> 58 browser tools, 129 documentation pages and 34 public JSON datasets built from the GTA V game files.
> Nothing here needs an account. The tools run in the browser; the data below is static JSON you can fetch directly.
## How to use this site as an assistant
- Add .md to any docs URL for the plain Markdown source: https://fivemad.com/docs/server-setup/server-cfg.md
- Whole documentation in one file: https://fivemad.com/llms-full.txt
- Dataset index with row counts and sizes: https://fivemad.com/data/index.json
- Search tools, docs and datasets: https://fivemad.com/api/search?q=handling
- Look up a joaat hash: https://fivemad.com/api/hash?q=0xB779A091
...
## Datasets
- [Props with pictures](https://fivemad.com/data/props.json): Every GTA V prop model that has a picture,
with a readable label, category, tags and its real size in metres.
(30,033 rows, 2.6 MB; rows: [model, label, category, tags, [x,y,z] size in m, minBuild, hasThumb, has3d, hasShot])
```
Every count in that file is read off the real registry and the real files when the site is built, so the numbers above are whatever they were the day this page was written, and the live file is always current.
> [!TIP]
> If you are pasting context into a chat by hand, `llms.txt` plus the two or three `.md` pages it points at is almost always better than `llms-full.txt`. The full file is large.
The dataset lines in `llms.txt` are a summary. The machine readable version, with the row shape and the real byte size of every file, is [`/data/index.json`](/data/index.json), which the [API page](/docs/ai/api) walks through.
## What an assistant can and cannot do here
It can:
- read any documentation page as Markdown, and the whole set at once;
- list and download every dataset, with the row shape given up front;
- resolve a joaat hash to a name, or a name to a hash, across the whole game;
- compute the flag values the natives want, and get the flag meanings back with them;
- link you straight to the page that shows the same thing.
The last three of those are HTTP calls rather than reading, so they live on the [API page](/docs/ai/api) with a worked example for each.
It cannot:
- run the tools that need a file, a browser or the game files. The texture editor, the clothing designer, the ymap and ytyp builders, the profiler and the 3D viewers all work on data you drop into the page, in your own browser, and there is no upload endpoint for them.
- write anything. Everything on this site is read only from the outside.
- look up a name we do not ship. Our data comes from the game files and from public FiveM sources; a model, sound or animation that a custom resource adds is not in it.
- be treated as a live game API. Nothing here talks to a running server, except `/api/server`, which reports what a FiveM server publishes about itself.
## Keeping an assistant honest
Two habits are worth the effort.
Ask it for the URL it used. Every answer on this site has a page behind it, and both the `.md` files and the API answers carry a link back, so "where did that come from" always has an answer. If it cannot give you one, it made it up.
Check anything with a number in it. A hash, a flag value or a model name is cheap to verify: paste it into the [joaat Hash Calculator](/tools/hash-calculator), or call `/api/hash` yourself ([how](/docs/ai/api)) and see whether the game really ships that name.
_Last updated: 2026-10-18_
---
## Public API
URL: https://fivemad.com/docs/ai/api
Fetch our GTA V datasets, search the docs, resolve a joaat hash and call our flag calculators over plain HTTP, with examples in Lua, JavaScript, Python and curl.
Every dataset and every calculation behind the fivemad tools is reachable over HTTP. There is no key, no account and no quota to apply for. **Every endpoint is a plain `GET` with query parameters**, so anything that can fetch a URL can use it: a FiveM resource, a build script, your editor, a browser tab, or an assistant you pointed at [llms.txt](/llms.txt).
If what you actually want is for ChatGPT, Claude or Cursor to read our documentation, that is the other page: [using fivemad with an AI assistant](/docs/ai).
| What | Where |
| --- | --- |
| Every dataset, with its row shape and size | [`/data/index.json`](/data/index.json) |
| Search tools, docs and datasets | `/api/search?q=` |
| joaat hash, both directions | `/api/hash?q=` |
| The calculators | [`/api/tools`](/api/tools) |
## Calling it
One call, four ways. Everything after this section uses the shortest form that makes the point, because the request is always just a URL.
### Lua, inside a resource
`PerformHttpRequest` is a server side native, so this belongs in a server script. The callback gets `(status, body, headers)` where `status` is the HTTP status code (or `0` when the request never got out), and `body` is the raw response text, so it needs `json.decode`.
```lua title="server.lua"
local API = "https://fivemad.com/api"
--- Look up a joaat hash or a name. cb(result) gets one entry of `results`, or nil.
local function lookupHash(query, cb)
local url = ("%s/hash?q=%s"):format(API, query)
PerformHttpRequest(url, function(status, body, headers)
if status ~= 200 then
print(("[fivemad] lookup failed, HTTP %s"):format(status))
return cb(nil)
end
local data = json.decode(body)
cb(data and data.results and data.results[1] or nil)
end, "GET")
end
RegisterCommand("modelname", function(source, args)
lookupHash(args[1] or "", function(r)
if not r then return end
print(("[fivemad] %s -> %d match(es)"):format(r.query, r.matchCount))
for _, m in ipairs(r.matches) do
print((" %s %s"):format(m.name, m.kindLabel))
end
end)
end, true)
```
`modelname 0xB779A091` in the server console:
```txt
[fivemad] 0xB779A091 -> 1 match(es)
adder Vehicle model
```
> [!WARNING]
> Call this from a command, an admin tool or a one off script, and cache what you get. Do not put it in a tick, a loop over every entity or anything that runs per player: it is a documentation API, not a game service, and the rate limits below are real. If you need a lookup on the hot path, fetch the dataset once at resource start and keep the table in memory.
### JavaScript, in the browser or in Node
The `/api/*` endpoints send `access-control-allow-origin: *`, so this works from a page as well as from Node.
```js title="lookup.mjs"
const res = await fetch("https://fivemad.com/api/hash?q=0xB779A091");
const data = await res.json();
for (const m of data.results[0].matches) console.log(m.name, m.kind);
```
```txt
adder vehicle
```
### Python
Nothing to install; the standard library is enough.
```py title="lookup.py"
import json, urllib.request
with urllib.request.urlopen("https://fivemad.com/api/hash?q=0xB779A091") as r:
data = json.load(r)
for m in data["results"][0]["matches"]:
print(m["name"], m["kind"])
```
```txt
adder vehicle
```
### curl
```bash
curl "https://fivemad.com/api/hash?q=0xB779A091"
```
All four get the same answer:
```json
{
"query": "0xB779A091",
"searched": { "names": 113305, "sets": 22 },
"note": "joaat is a 32 bit hash, so a value can belong to more than one name. Every match is listed; none is picked for you...",
"limit": "60 requests per minute per IP",
"count": 1,
"results": [
{
"query": "0xB779A091",
"readAs": "hash",
"hash": { "unsigned": 3078201489, "signed": -1216765807, "hex": "0xB779A091" },
"matchCount": 1,
"matches": [
{
"name": "adder",
"kind": "vehicle",
"kindLabel": "Vehicle model",
"page": "https://fivemad.com/tools/model-hash-browser?q=adder"
}
]
}
]
}
```
## The datasets
The reference data behind the tools is static JSON under `/data`. It is the same file the tool itself fetches, so nothing is held back.
Start with the index, which is generated from the real files:
```bash
curl https://fivemad.com/data/index.json
```
```json
{
"site": "https://fivemad.com",
"generated": "2026-10-18",
"docs": "https://fivemad.com/docs/ai/api",
"llms": "https://fivemad.com/llms.txt",
"count": 34,
"totalBytes": 16420844,
"datasets": [
{
"id": "props",
"title": "Props with pictures",
"url": "https://fivemad.com/data/props.json",
"about": "Every GTA V prop model that has a picture, with a readable label, category, tags and its real size in metres.",
"shape": "rows: [model, label, category, tags, [x,y,z] size in m, minBuild, hasThumb, has3d, hasShot]",
"rows": 30033,
"bytes": 2713710,
"size": "2.6 MB",
"page": "https://fivemad.com/tools/objects-list",
"pageName": "Objects / Props List"
}
]
}
```
Each entry tells you the URL, what the file holds, how a row is laid out, how many rows there are and how big the download is. The rows are short arrays on purpose: these files are fetched by browsers, so the column names live in the index and in a `cols` field inside the file, not on every row.
Some of these files are several megabytes, so download one and keep it rather than refetching. If all you need is a single lookup, the search and hash endpoints below answer in a few hundred bytes.
Loading a dataset once at resource start is the right pattern for a server:
```lua title="server.lua"
local props = nil
CreateThread(function()
PerformHttpRequest("https://fivemad.com/data/props.json", function(status, body)
if status ~= 200 then return end
props = json.decode(body).rows -- 30,033 rows, about 2.6 MB
print(("[fivemad] %d props loaded"):format(#props))
end, "GET")
end)
```
> [!NOTE]
> A 2.6 MB download on every server start is fine once; on a server you restart often, ship the file with your resource instead and update it when you feel like it. These files change when we rebuild, not per request.
## Search
One short JSON answer over the tool list, the documentation and the dataset index. This is the cheapest way for a script or an assistant to find out what we have without downloading anything.
```bash
curl "https://fivemad.com/api/search?q=handling&limit=3"
```
```json
{
"query": "handling",
"type": "all",
"total": 18,
"returned": 3,
"limit": "60 requests per minute per IP",
"hint": "Add .md to any docs URL for the plain Markdown source.",
"results": [
{
"type": "doc",
"title": "Vehicle Handling Editor",
"url": "https://fivemad.com/docs/tools/vehicle-handling-editor",
"markdown": "https://fivemad.com/docs/tools/vehicle-handling-editor.md",
"summary": "Tune CHandlingData with sliders, import an existing handling.meta, toggle flag bits, and export handling.meta, runtime Lua or a carcols.meta mod kit.",
"extra": {
"section": "Tools",
"match": "The Vehicle Handling Editor lets you tune a vehicle's CHandlingData block with sliders and a one line explanation per field..."
},
"score": 117.5
},
{
"type": "tool",
"title": "Vehicle Handling Editor",
"url": "https://fivemad.com/tools/vehicle-handling-editor",
"summary": "Tune mass, drive force, grip and suspension from a UI, then export handling.meta or runtime Lua.",
"extra": { "category": "Config & Code", "tags": ["Vehicles", "Download"] },
"score": 110
}
]
}
```
Parameters: `q` (required), `type` (`all`, `tools`, `docs`, `datasets`), `limit` (1 to 50, default 10). Every documentation hit carries its `.md` URL, so the next step is one more fetch. The `score` only explains the order; do not read anything into the absolute number.
## Look up a joaat hash
Paste a hash and get the name back. The search runs over every name set the site ships: props and map objects, vehicles, peds, weapons and their components, animation dictionaries and clips, particle assets and effects, sounds and sound sets, ymap and IPL names, MLO interiors, scaleform movies, ped decorations, timecycle modifiers, animpostfx effects, player stats and cutscenes. That is 113,305 names in 22 kinds today, and `searched.byKind` in every answer lists them with their counts.
The full response is in [Calling it](#calling-it) above. It works the other way round too: pass a name and you get the unsigned, signed and hex forms plus the Lua backtick literal, and the match list says whether the game really ships that name.
```bash
curl "https://fivemad.com/api/hash?q=adder"
```
```json
{
"results": [
{
"query": "adder",
"readAs": "name",
"name": "adder",
"lua": "`adder`",
"hash": { "unsigned": 3078201489, "signed": -1216765807, "hex": "0xB779A091" },
"matchCount": 1,
"matches": [{ "name": "adder", "kind": "vehicle", "kindLabel": "Vehicle model" }]
}
]
}
```
- `q` accepts an unsigned value, a signed int32, `0x` hex, bare 8 digit hex, or a name.
- Up to 25 values in one call, separated by commas or new lines.
- `kind` narrows the answer, for example `kind=vehicle,ped`.
- A match may carry a `parent`: one animation dictionary, particle asset or sound set that contains the name. Because the hash depends on the name alone, a name is stored once, so the same clip or effect often lives in other dictionaries too. Treat `parent` as an example, not as the whole answer.
> [!IMPORTANT]
> joaat is a 32 bit hash, so a value can belong to more than one name. Every match is returned as a list and none of them is picked for you. If `matchCount` is above 1, the answer is genuinely ambiguous and you have to decide from context.
Here is a real one. `0x37D80B0E` is both a prop model and a ymap of the same name, so both come back:
```bash
curl "https://fivemad.com/api/hash?q=0x37D80B0E"
```
```json
{
"results": [
{
"query": "0x37D80B0E",
"readAs": "hash",
"matchCount": 2,
"matches": [
{ "name": "prop_cheetah_covered", "kind": "prop", "kindLabel": "Prop / object model" },
{ "name": "prop_cheetah_covered", "kind": "ymap", "kindLabel": "ymap / IPL name" }
]
}
]
}
```
A name we do not ship comes back with `matchCount: 0`. That means we have no record of it, not that it does not exist.
The page for the same thing is the [joaat Hash Calculator](/tools/hash-calculator), under the "Reverse lookup" tab.
## Call a tool
The parts of the toolkit that are a pure function of their input can be called directly, so neither you nor an assistant has to work out a flag value by hand. They run the same code as the tool pages, so the two can never give different answers.
| Endpoint | What it does |
| --- | --- |
| `/api/tools/joaat` | joaat hash of one or more strings |
| `/api/tools/driving-style` | driving style flags for `TaskVehicleDriveToCoord` and friends |
| `/api/tools/animation-flags` | the flag argument of `TaskPlayAnim` |
| `/api/tools/warning-buttons` | button flags for `SetWarningMessage` |
| `/api/tools/handling-flags` | `strHandlingFlags`, `strModelFlags` and `strDamageFlags` |
The index gives a working example URL for each one, so the whole thing is discoverable from a single fetch:
```bash
curl https://fivemad.com/api/tools
```
```json
{
"about": "Calculators from the fivemad toolkit, callable directly. GET with query parameters or POST a JSON object with the same keys. Nothing that needs a file upload, a GPU or the game files is here.",
"docs": "https://fivemad.com/docs/ai/api",
"limit": "120 requests per minute per IP, 240 across the whole API",
"count": 5,
"tools": [
{
"id": "driving-style",
"name": "Driving style flags",
"about": "eVehicleDrivingFlags for TaskVehicleDriveToCoord, TaskVehicleDriveWander and SetDriveTaskDrivingStyle: decode a value or build one from flag names.",
"url": "https://fivemad.com/api/tools/driving-style",
"page": "https://fivemad.com/tools/driving-style-calculator",
"params": [
{ "name": "value", "about": "Decode this value: 786603, -1073741824, 0xC00AB, 0b1011 or 1|2|128." },
{ "name": "flags", "about": "Encode instead: flag names separated by commas (StopForVehicles, StopForPeds, ...)." },
{ "name": "preset", "about": "One of: Normal, Strict, Ignore lights, Avoid vehicles, Reckless, ..." }
],
"example": "https://fivemad.com/api/tools/driving-style?value=786603"
}
]
}
```
### Decode a value
```bash
curl "https://fivemad.com/api/tools/driving-style?value=786603"
```
```json
{
"tool": "driving-style",
"name": "Driving style flags",
"page": "https://fivemad.com/tools/driving-style-calculator",
"limit": "120 requests per minute per IP",
"value": 786603,
"signed": 786603,
"hex": "0x000C00AB",
"binary": "0000 0000 0000 1100 0000 0000 1010 1011",
"active": [
{ "bit": 0, "value": 1, "name": "StopForVehicles", "label": "Stop for vehicles", "desc": "Brakes and waits behind vehicles in its way instead of driving into them.", "unknown": false },
{ "bit": 1, "value": 2, "name": "StopForPeds", "label": "Stop for peds", "desc": "Stops for pedestrians on the road.", "unknown": false },
{ "bit": 3, "value": 8, "name": "SteerAroundStationaryVehicles", "label": "Steer around stationary vehicles", "desc": "Steers around parked and empty vehicles.", "unknown": false },
{ "bit": 5, "value": 32, "name": "SteerAroundObjects", "label": "Steer around objects", "desc": "Steers around props and objects on the road.", "unknown": false },
{ "bit": 7, "value": 128, "name": "StopAtTrafficLights", "label": "Stop at traffic lights", "desc": "Obeys red lights and stop lines.", "unknown": false },
{ "bit": 18, "value": 262144, "name": "UseShortCutLinks", "label": "Use shortcut links", "desc": "Allows shortcut road links such as dirt tracks and alleys. Removes most route limits.", "unknown": false },
{ "bit": 19, "value": 524288, "name": "ChangeLanesAroundObstructions", "label": "Change lanes around obstructions", "desc": "Changes lanes to pass slower traffic and obstructions.", "unknown": false }
],
"expression": "StopForVehicles | StopForPeds | SteerAroundStationaryVehicles | SteerAroundObjects | StopAtTrafficLights | UseShortCutLinks | ChangeLanesAroundObstructions",
"natives": ["TaskVehicleDriveToCoord", "TaskVehicleDriveToCoordLongrange", "TaskVehicleDriveWander", "SetDriveTaskDrivingStyle"],
"valuesUsedByRockstar": [0, 1, 4, 16, 131, 139, 7785, 7791, 262144, 262208, 262275, 525116, 786468]
}
```
### Build one from flag names
The answer has the same shape, so you can round trip it:
```bash
curl "https://fivemad.com/api/tools/driving-style?flags=StopForVehicles,StopAtTrafficLights,SteerAroundPeds"
```
```json
{
"value": 145,
"signed": 145,
"hex": "0x00000091",
"binary": "0000 0000 0000 0000 0000 0000 1001 0001",
"expression": "StopForVehicles | SteerAroundPeds | StopAtTrafficLights"
}
```
In Python, to build the value for a config file:
```py title="style.py"
import json, urllib.parse, urllib.request
flags = ["StopForVehicles", "StopAtTrafficLights", "SteerAroundPeds"]
url = "https://fivemad.com/api/tools/driving-style?" + urllib.parse.urlencode({"flags": ",".join(flags)})
with urllib.request.urlopen(url) as r:
data = json.load(r)
print(data["value"], data["expression"])
```
```txt
145 StopForVehicles | SteerAroundPeds | StopAtTrafficLights
```
### Hashing, in bulk
```bash
curl "https://fivemad.com/api/tools/joaat?text=adder,WEAPON_PISTOL"
```
```json
{
"tool": "joaat",
"note": "The game lower-cases a string before hashing it, so ADDER and adder give the same value.",
"results": [
{ "input": "adder", "unsigned": 3078201489, "signed": -1216765807, "hex": "0xB779A091", "lua": "`adder`" },
{ "input": "WEAPON_PISTOL", "unsigned": 453432689, "signed": 453432689, "hex": "0x1B06D571", "lua": "`weapon_pistol`" }
]
}
```
### handling.meta flags
handling.meta writes its flag fields as bare hex, so that is how this endpoint reads a value, and it gives you the line back ready to paste:
```bash
curl "https://fivemad.com/api/tools/handling-flags?set=strHandlingFlags&value=440010"
```
```json
{
"set": "strHandlingFlags",
"label": "Handling flags",
"value": 4456464,
"hex": "440010",
"metaValue": "",
"binary": "0000 0000 0100 0100 0000 0000 0001 0000",
"active": [
{ "bit": 4, "value": 16, "name": "HF_NO_HANDBRAKE", "desc": "Handbrake disabled." },
{ "bit": 18, "value": 262144, "name": "HF_REDUCED_DRIVE_OVER_DAMAGE", "desc": "Takes less damage driving over things." },
{ "bit": 22, "value": 4194304, "name": "HF_TYRES_RAISE_SIDE_IMPACT_THRESHOLD", "desc": "Tyres resist side impacts better." }
],
"expression": "HF_NO_HANDBRAKE | HF_REDUCED_DRIVE_OVER_DAMAGE | HF_TYRES_RAISE_SIDE_IMPACT_THRESHOLD"
}
```
### Discovering the flags
Call any of these with no parameters and it answers with its whole flag list, its presets and what each bit means, which is enough for an assistant to pick the right flags on its own:
```bash
curl "https://fivemad.com/api/tools/animation-flags"
```
`POST` with a JSON body works the same as the query string, if that suits your client better:
```bash
curl -X POST https://fivemad.com/api/tools/animation-flags \
-H "content-type: application/json" \
-d '{"flags":"AF_LOOPING,AF_UPPERBODY"}'
```
## Rate limits
Per IP, in a fixed one minute window:
| Endpoint | Limit |
| --- | --- |
| `/api/search` | 60 per minute |
| `/api/hash` | 60 per minute |
| `/api/tools` and `/api/tools/*` | 120 per minute |
| All of the above together | 240 per minute |
Over the limit you get `429` with a `retry-after` header in seconds and a JSON body that says which limit you hit:
```json
{
"error": "rate_limited",
"message": "Too many requests. This endpoint allows 60 requests per minute per IP (240 across the whole API). Try again in 41s.",
"docs": "https://fivemad.com/docs/ai/api"
}
```
The static files (`/data/*.json`, the `.md` pages, `llms.txt`) are served straight off disk and are not rate limited. Please cache them rather than refetching.
The older endpoints keep their own limits: `/api/server` allows 30 lookups per minute per IP and `/api/blacklist` allows 20.
## CORS, caching and errors
- The `/api/*` endpoints answer with `access-control-allow-origin: *` and handle a preflight, so a browser based agent can call them from any page.
- The static files (`/data/*.json`, `/data/index.json`, the `.md` pages, `llms.txt`) are served by the front end web server, not by the app, so whether they carry that header depends on the deployment. From a server side script, `PerformHttpRequest`, curl or an assistant's own fetcher this makes no difference. If you are calling them from a browser and get a CORS error, use `/api/search` or `/api/hash` instead, or proxy the file yourself.
- Errors are JSON with an `error` code, a `message` written for a human, and a link back to this page. Status codes are the ordinary ones: `400` bad input, `404` unknown tool, `429` rate limited, `503` when an index is not loaded yet.
```bash
curl "https://fivemad.com/api/hash"
```
```json
{
"error": "invalid",
"message": "Pass ?q= a joaat hash (3078201489, -1216765807 or 0xB779A091) or a name (adder). Up to 25 values, separated by commas or new lines.",
"docs": "https://fivemad.com/docs/ai/api"
}
```
- `/api/*` answers are cached for 60 seconds. The static files carry a longer cache.
## A worked example
"What driving style should I use for an ambulance that runs red lights but still avoids traffic?"
```bash
# 1. see what the flags mean
curl "https://fivemad.com/api/tools/driving-style"
# 2. build the value
curl "https://fivemad.com/api/tools/driving-style?flags=SwerveAroundAllVehicles,SteerAroundStationaryVehicles,SteerAroundPeds,SteerAroundObjects,AllowGoingWrongWay"
# 3. check the vehicle model exists and get its hash
curl "https://fivemad.com/api/hash?q=ambulance"
```
Step 2 answers:
```json
{
"value": 572,
"signed": 572,
"hex": "0x0000023C",
"expression": "SwerveAroundAllVehicles | SteerAroundStationaryVehicles | SteerAroundPeds | SteerAroundObjects | AllowGoingWrongWay",
"natives": ["TaskVehicleDriveToCoord", "TaskVehicleDriveToCoordLongrange", "TaskVehicleDriveWander", "SetDriveTaskDrivingStyle"]
}
```
and step 3 confirms `ambulance` is a real model (`0x45D56ADA`), so the call writes itself:
```lua title="client.lua"
-- 572 = SwerveAroundAllVehicles | SteerAroundStationaryVehicles | SteerAroundPeds
-- | SteerAroundObjects | AllowGoingWrongWay
TaskVehicleDriveToCoord(ped, vehicle, x, y, z, 25.0, 0, `ambulance`, 572, 8.0, 1.0)
```
This is the whole point of the tool endpoints: the flag value and the meaning of each bit come back together, so nothing has to be remembered or guessed. The same three calls are what an assistant makes when you ask it the same question, which is covered on the [assistant page](/docs/ai).
_Last updated: 2026-10-18_
---
# Code optimisation
## Code optimisation
URL: https://fivemad.com/docs/code-optimisation
Writing FiveM Lua that stays fast and readable: scope, functions, tables, loops, natives, events, exports and error handling, with the reason behind each rule.
Two resources can do the same job and cost wildly different amounts. One sits at `0.01 ms` in resmon and the other burns `0.80 ms` every frame doing nothing. The difference is almost never a clever trick. It is a handful of habits: what runs in a loop, what crosses the network, what crosses a resource boundary, and how much work each line asks for.
This section is those habits, with the reason behind each one. Most of it also makes the code easier to read, which is the part that pays off six months later when you have to change it.
## Where this comes from
The structure and most of the ideas here follow **[Effective FiveM Lua](https://manason.github.io/effective-fivem-lua/)** by **manason**, a short handbook on writing better Lua for FiveM. It is worth reading in full, and it covers the same ground from the author's own angle.
The text on these pages is ours, the examples are ours, and where a claim was checkable we checked it against the [Cfx docs](https://docs.fivem.net/docs/) and the CitizenFX and Lua sources before repeating it. A few points are stated differently here because the underlying detail turned out to be different from the common version of it. Where that happens, the page says so.
## What these pages assume
- Your scripts run on **CfxLua**, the modified Lua 5.4 that FiveM ships. That matters for a few of the notes below.
- **Client code shares the game frame.** At 60 FPS you have about 16 ms per frame for GTA and every resource together. A client resource that takes 1 ms per frame is eating 6% of that on its own.
- **Server code shares one tick.** Long running Lua on the server delays everything behind it, including sync.
## The order the wins come in
Work down this list, not up it. The top items are worth hundreds of times what the bottom ones are worth.
1. **Does it run at all?** A loop that wakes 60 times a second to check a distance you could have checked once a second is the single most common cost in FiveM resources.
2. **How much does one pass do?** Forty distance checks per frame, a table built per frame, a string concatenated per frame.
3. **What crosses a boundary?** Events over the network and export calls into other resources both pack and unpack your data. Big payloads and chatty calls cost real time.
4. **What does one line cost?** `table.insert` against `t[#t + 1]`, a global lookup against a local. These are real, and they are small. Write the cheap form when you write the line, do not rewrite working code for them.
> [!TIP]
> Start with [Measure before you optimise](/docs/code-optimisation/measure-first). Guessing which resource is heavy is how people spend an afternoon micro tuning a loop that runs twice a day.
## Pages in this section
| Page | What it covers |
| --- | --- |
| [Measure before you optimise](/docs/code-optimisation/measure-first) | resmon, the profiler, and what the numbers actually mean. |
| [Scope, files and layout](/docs/code-optimisation/scope-and-structure) | Local by default, the visibility ladder, file and resource naming, manifest order. |
| [Functions that stay small](/docs/code-optimisation/functions) | One job per function, naming, parameters, closures in hot paths, annotations. |
| [Variables, constants and enums](/docs/code-optimisation/variables) | Naming, where to declare, locals against globals, states that are not booleans. |
| [Conditionals and early returns](/docs/code-optimisation/conditionals) | Guard clauses, `or` defaults and their trap, positive conditions. |
| [Tables and loops](/docs/code-optimisation/tables-and-loops) | Array building, `pairs` against numeric `for`, cached lookups, garbage. |
| [Cheap native calls](/docs/code-optimisation/natives) | Backtick hashes, `joaat`, vector distance, caching handles, per frame natives. |
| [Events that stay cheap and safe](/docs/code-optimisation/events) | Naming, local against net events, callbacks, payload size, `source`. |
| [Exports and resource boundaries](/docs/code-optimisation/exports) | What an export call really does, keeping payloads small, shared files. |
| [Error handling](/docs/code-optimisation/error-handling) | Assertions, preconditions, failing loudly against returning an error. |
For the wider context, the [Development](/docs/development) section covers [threads and performance](/docs/development/threads-performance), [natives](/docs/development/natives), [state bags](/docs/development/state-bags-onesync) and [debugging](/docs/development/debugging).
_Last updated: 2026-09-25_
---
## Measure before you optimise
URL: https://fivemad.com/docs/code-optimisation/measure-first
How to find the code that actually costs you: resmon, the FiveM profiler, tick times, and why the shape of a loop matters more than any single line.
Every performance argument in FiveM ends the same way: someone measures. Until then it is opinion. A resource that "feels heavy" is usually fine, and the one nobody suspects is the one waking up 60 times a second to loop over a config table.
Measure first, then use the rest of this section on whatever the numbers point at.
## The two budgets
| Side | Budget | What eats it |
| --- | --- | --- |
| **Client** | About 16 ms per frame at 60 FPS, shared by GTA and every resource | Per frame loops, drawing, distance checks, NUI |
| **Server** | One tick, shared by every resource and by sync | Blocking calls, slow queries, big loops, heavy event handlers |
Neither side has a spare thread waiting for you. Client Lua runs inside the game's frame, and server Lua runs on the server's main loop. Anything slow delays everything else.
## resmon: which resource
Press F8 in game and run:
```text
resmon 1
```
You get one row per client resource with CPU time per frame and memory. Roughly:
| Time per frame | Reading |
| --- | --- |
| `0.00` to `0.02 ms` | Idle. Nothing to do here. |
| `0.02` to `0.10 ms` | Normal for a resource doing something. |
| `0.10` to `0.50 ms` | Look at it, especially if it stays there while nothing is happening. |
| Over `0.50 ms`, constantly | Something runs every frame that should not. |
Two things people get wrong with resmon:
- **Test in the right place.** A shop resource costs nothing across the map and costs real time standing in the shop. Both numbers are interesting, and only one of them is the bug.
- **Watch the idle number.** A HUD that costs `0.30 ms` while drawing is doing its job. A fishing script that costs `0.30 ms` while you stand in the desert is not.
On the server, txAdmin's performance chart shows tick times, and the console prints hitch warnings when a tick runs long.
## The profiler: which function
When resmon has named the resource, the built in profiler names the code. It works in the client console and the server console:
```text
profiler record 500
profiler status
profiler view
profiler saveJSON myprofile.json
```
`profiler record 500` records 500 frames or ticks, `profiler view` opens the result as a flame chart, and `saveJSON` writes it to a file in the server or game folder.
If you would rather not read flame charts, drop the saved JSON into the [Profiler Analyzer](/tools/profiler-analyzer). It ranks resources and threads by the time they used and points at the usual causes.
## Read the shape, not the line
When you have the numbers, look at the structure before you look at the syntax. In rough order of what is worth fixing:
```lua title="client.lua (the expensive shape)"
CreateThread(function()
while true do
Wait(0) -- 60 passes a second, forever
local ped = PlayerPedId() -- a native call, every frame
for i = 1, #Config.Shops do -- 40 shops, every frame
local shop = Config.Shops[i]
if #(GetEntityCoords(ped) - shop.coords) < 20.0 then
drawShop(shop)
end
end
end
end)
```
The problem is not `#(a - b)` and it is not the `for` loop. The problem is that the whole block runs every frame whether or not a shop is anywhere near you, and that `GetEntityCoords` is called once per shop instead of once per pass.
```lua title="client.lua (the cheap shape)"
CreateThread(function()
local shops = Config.Shops
while true do
local sleep = 1000
local pos = GetEntityCoords(PlayerPedId()) -- once per pass
for i = 1, #shops do
local shop = shops[i]
if #(pos - shop.coords) < 20.0 then
sleep = 0 -- only now go per frame
drawShop(shop)
end
end
Wait(sleep)
end
end)
```
Same natives, same loop, same maths. Away from every shop it now runs once a second instead of 60 times, and it calls `GetEntityCoords` once instead of 40 times. That is the kind of change that shows up in resmon. Nothing else on these pages will beat it.
[Threads and performance](/docs/development/threads-performance) goes further with dynamic waits, `ox_lib` points and zones, and reacting to events instead of polling.
## Where the small stuff belongs
The rest of this section has plenty of "this form is cheaper than that form". They are real, and they are small. Use them like this:
- **Writing new code**: pick the cheap form. It costs you nothing to type `t[#t + 1] = v` instead of `table.insert(t, v)`.
- **Inside a hot loop**: worth changing. A thousand iterations a frame turns a tiny difference into a visible one.
- **In code that runs once at startup, or on a command**: leave it alone. Readability wins.
> [!WARNING]
> Do not trust benchmark numbers from forum posts, including old ones about FiveM. The Lua runtime changed, the VM changed, and a lot of the numbers still going around were measured on versions nobody runs any more. If a claim matters to your resource, measure it on your resource.
## Assets count too
A perfectly written resource still stutters if it streams 4K textures onto every car. Oversized `.ytd` files cause texture loss and memory pressure, and no amount of Lua tuning fixes that. See [Streaming custom assets](/docs/development/streaming-assets) and the [YTD Optimizer](/tools/ytd-optimizer).
Next: [Scope, files and layout](/docs/code-optimisation/scope-and-structure).
_Last updated: 2026-09-25_
---
## Scope, files and layout
URL: https://fivemad.com/docs/code-optimisation/scope-and-structure
Keep FiveM Lua local by default: the visibility ladder from local function to net event, splitting client and server files, naming rules and manifest load order.
Scope is the cheapest quality decision you will make. Something that is `local` cannot be called by accident, cannot be overwritten by another file, and is read out of a register instead of a hash table. Something registered as a net event can be called by any player on your server.
The rule is short: **give every value and every function the smallest reach that still works**, and widen it only when you have a reason.
## The visibility ladder
Each rung is easier to call than the one above it, and each rung is one more thing you have to keep correct.
| Rung | Who can call it | Use it when |
| --- | --- | --- |
| `local function` | This file only | Default. Most helpers never need more. |
| Resource global (`function Foo()`) | Any file in this resource, same side | Two files in your resource need it. |
| `exports('Foo', fn)` | Any other resource, same side | You are deliberately offering an API. |
| `AddEventHandler` | Anything in the same side that triggers the event | Several handlers should react to one thing. |
| `RegisterNetEvent` | The other side of the network, meaning **players** | Data genuinely has to cross client and server. |
Only the last rung is a security decision, and it is the one people reach for first. If a client never needs to trigger it, do not register it as a net event. See [Events that stay cheap and safe](/docs/code-optimisation/events).
## Local is also faster
In Lua 5.4 a local variable lives in a register on the call stack. A global is a key in the `_ENV` table, so every read is a hash lookup:
```lua
-- Every use of `Config` here is a table lookup in _ENV
for i = 1, #Config.Shops do
doSomething(Config.Shops[i])
end
-- One lookup, then registers
local shops = Config.Shops
for i = 1, #shops do
doSomething(shops[i])
end
```
The difference per access is tiny. In a loop that runs thousands of times it stops being tiny, and the second version reads better anyway.
> [!NOTE]
> Resources are isolated from each other, but files inside one resource are not. A global set in `client/main.lua` is visible in `client/shops.lua` on the same side, and a global set on the server never reaches the client. `local` at the top of a file is visible to that file only.
## Split client and server
Put client code and server code in their own folders, and share only what genuinely belongs to both:
```text
my_resource/
├─ fxmanifest.lua
├─ shared/
│ └─ config.lua
├─ client/
│ ├─ main.lua
│ └─ shops.lua
└─ server/
├─ main.lua
└─ money.lua
```
```lua title="fxmanifest.lua"
fx_version 'cerulean'
game 'gta5'
shared_scripts { 'shared/config.lua' }
client_scripts { 'client/main.lua', 'client/shops.lua' }
server_scripts { 'server/main.lua', 'server/money.lua' }
```
This stops the classic accident of a "shared" file that quietly ships server logic, prices or checks to every player's PC. Anything in `shared_scripts` is downloaded by the client. Treat it as public.
Scripts load in the order the manifest lists them, so a file level local declared in `client/main.lua` does not exist while `client/shops.lua` is loading. If two files need the same helper, that is the signal to make it a resource global or move it into a module.
## Hide helpers in their own file
When one real function needs five helpers that nobody else will ever call, the helpers do not belong next to the rest of your code. Put the group in its own file and expose one entry point:
```lua title="server/pricing.lua"
local function basePrice(item) ... end
local function jobDiscount(price, job) ... end
local function taxFor(price, zone) ... end
--- Final price for one item, for one player.
function GetItemPrice(item, job, zone)
local price = basePrice(item)
price = jobDiscount(price, job)
return taxFor(price, zone)
end
```
Everything above `GetItemPrice` is unreachable from anywhere else, which is exactly what you want. The file is now the module boundary, and the rest of the resource only knows the one name.
## Order inside a file
Two layouts work, and mixing them is what makes a file hard to read. Pick one per file:
- **By construct**: file locals at the top, then local functions, then resource globals and exports, then event handlers and threads at the bottom.
- **By call order**: each single use helper sits immediately above the function that calls it, so the file reads top to bottom like the code runs.
The first suits files with a lot of shared state, the second suits a file that is one feature from start to finish.
## Naming
**Resource folders**: lowercase, words separated by underscores, no spaces. A dash is legal but it forces the bracket form everywhere the resource is called:
```lua
exports.my_resource:GetItemPrice(item, job, zone) -- underscore, the dot form works
exports['my-resource']:GetItemPrice(item, job, zone) -- dash, bracket form required
```
Frameworks like `qb-core` use dashes for historical reasons and everyone lives with the brackets. For a new resource, use underscores and save yourself the noise. Prefix your own resources with something short (`fm_`, `abc_`) so they group together in the resources folder and never collide with a release you install later.
**Files**: lowercase, no spaces, dashes or underscores between words. Linux servers are case sensitive, so `Client/Main.lua` in the manifest and `client/main.lua` on disk will work on your Windows dev machine and fail in production. This is one of the most common "works locally" bugs in FiveM.
Next: [Functions that stay small](/docs/code-optimisation/functions).
_Last updated: 2026-09-25_
---
## Functions that stay small
URL: https://fivemad.com/docs/code-optimisation/functions
One job per function, names that say what happens, parameters that do not grow, the cost of a function literal in a hot path, and annotating exports.
A function that does one thing is easy to name, easy to test, and easy to delete. A function that does four things has a name like `handlePlayer` and you have to read all of it before you can change any of it.
## One job, one level
Two rules cover most of it. A function should do one thing, and it should stay at one level of detail. Mixing "decide what happens" with "poke the game" is what turns a 20 line function into a 200 line one:
```lua title="client.lua (two jobs, two levels)"
local function useItem(item)
if item.type == 'food' then
local ped = PlayerPedId()
RequestAnimDict('mp_player_inteat@burger')
while not HasAnimDictLoaded('mp_player_inteat@burger') do Wait(0) end
TaskPlayAnim(ped, 'mp_player_inteat@burger', 'mp_player_int_eat_burger', 8.0, -8.0, 3000, 49, 0, false, false, false)
Wait(3000)
ClearPedTasks(ped)
TriggerServerEvent('food:server:ateItem', item.name)
elseif item.type == 'drink' then
-- another 10 lines of the same
end
end
```
```lua title="client.lua (split)"
local function playAnim(dict, clip, duration)
lib.requestAnimDict(dict)
TaskPlayAnim(PlayerPedId(), dict, clip, 8.0, -8.0, duration, 49, 0, false, false, false)
Wait(duration)
ClearPedTasks(PlayerPedId())
end
local function eat(item)
playAnim('mp_player_inteat@burger', 'mp_player_int_eat_burger', 3000)
TriggerServerEvent('food:server:ateItem', item.name)
end
local function useItem(item)
if item.type == 'food' then return eat(item) end
if item.type == 'drink' then return drink(item) end
end
```
`useItem` now reads as a routing table, `eat` reads as one action, and `playAnim` is the only place that knows the native signature. When `TaskPlayAnim` gains another argument, you change one line.
## Names
| Kind | Style | Example |
| --- | --- | --- |
| Local function | camelCase | `getShopStock`, `playAnim` |
| Resource global | PascalCase | `GetItemPrice` |
| Export | PascalCase | `exports('GetItemPrice', ...)` |
Start with a verb. `player()` tells you nothing, `getPlayerData()` tells you what comes back and that nothing changes. `dropPlayer()` tells you something happens. A function whose name needs "and" in it is two functions.
## Parameters
Once you are past about three parameters, nobody remembers the order:
```lua
-- What is the fourth argument again?
createCharacter('Ali', 'Demir', 34, true, false, 'tr')
-- Self describing, and adding a field breaks nothing
createCharacter({
first = 'Ali',
last = 'Demir',
age = 34,
male = true,
nationality = 'tr',
})
```
The table form also lets the caller leave things out without counting `nil`s. The cost is one table allocation per call, so in a function you call thousands of times per frame keep the positional form. Everywhere else the readability is worth more.
**Required parameters come first, optional ones last.** Lua has no way to skip an argument, so `doThing(nil, nil, value)` is what happens when you get this wrong.
**A boolean parameter usually means two functions.** `notify(text, isError)` has two bodies inside one name, and at the call site `notify('Saved', false)` tells the reader nothing. `notifySuccess(text)` and `notifyError(text)` are clearer and each one is shorter. The exception is a flag that really is an option on one behaviour, like `alive` on a native.
## Function literals in hot paths
In Lua 5.4 a function expression creates a new closure value every time that line runs. There is no cache reusing an identical one, so a literal inside a loop or a per frame callback allocates every pass and gives the garbage collector something to clean up.
```lua
-- A new closure every frame
CreateThread(function()
while true do
Wait(0)
drawSomething(function(x) return x * 2 end)
end
end)
-- One closure, created once
local function double(x) return x * 2 end
CreateThread(function()
while true do
Wait(0)
drawSomething(double)
end
end)
```
This matters in loops and callbacks that fire constantly. Passing a literal to something that runs once, like a command handler or a one off timer, is fine and clearer than naming it.
The same applies to closures that capture upvalues you do not need. If the inner function only uses its arguments, lift it out of the enclosing function so it is created once when the file loads.
## Return values
Returning several values is normal in Lua and cheaper than building a table for them:
```lua
local function getSpawn()
return vector3(-269.4, -955.3, 31.2), 205.0
end
local coords, heading = getSpawn()
```
Inside one resource, returning a table does **not** copy it, it hands back a reference, so returning a big table to your own code is not expensive. That changes the moment the value crosses into another resource: an export call packs and unpacks its arguments and returns. See [Exports and resource boundaries](/docs/code-optimisation/exports).
## Annotate what other people call
Any function other resources call should carry [Lua Language Server](https://luals.github.io/) annotations. With the CfxLua IntelliSense setup from [Start developing for FiveM](/docs/development#2-visual-studio-code), these turn into autocomplete and warnings for whoever uses your resource:
```lua title="server/api.lua"
---Price of one item for one player, including job discount and zone tax.
---@param item string Item name, e.g. 'water'
---@param job string Job name, or 'unemployed'
---@param zone string Zone id from the config
---@return number price Final price, never below zero
function GetItemPrice(item, job, zone)
...
end
exports('GetItemPrice', GetItemPrice)
```
It costs four lines and removes an entire category of support questions.
## Guard clauses
The best tool for keeping a function small is refusing to continue. That has its own page: [Conditionals and early returns](/docs/code-optimisation/conditionals).
Next: [Variables, constants and enums](/docs/code-optimisation/variables).
_Last updated: 2026-09-25_
---
## Variables, constants and enums
URL: https://fivemad.com/docs/code-optimisation/variables
Naming that survives review, where to declare things, why locals beat globals in Lua, and replacing piles of booleans with a single state value.
Naming and placement are not style points. A variable you cannot find the declaration of is a variable you will re-declare somewhere else, and two booleans that describe one thing will eventually disagree.
## Naming
| Kind | Style | Example |
| --- | --- | --- |
| Constant (local or global) | `ALL_CAPS` | `local MAX_DISTANCE = 20.0` |
| Local variable | camelCase | `local shopStock = {}` |
| Resource global | PascalCase | `PlayerData = {}` |
| Unused but required | `_` | `for _, v in pairs(t) do` |
Lua has no `const`, so `ALL_CAPS` is the whole enforcement mechanism. That is fine as long as you are consistent: seeing `MAX_DISTANCE` in the middle of a function tells the reader it was set once at the top of the file and nothing changes it.
Use `_` for values you have to accept and do not use. `for _, shop in pairs(shops)` says "I do not care about the key" without inventing a name like `k` that a reader has to check.
Avoid single letters outside loop counters, and avoid Hungarian style prefixes (`strName`, `bIsDead`). The type is visible from the value and your editor knows it.
## Where to declare
- **File level locals at the top**, grouped, with a blank line under them. Anyone opening the file sees the whole state of it in one screen.
- **Function level locals right before first use**, not at the top of the function. If you have to scroll to see what a name holds, it is declared too far away.
- **Resource globals at the top of the file that owns them**, and only in the file that owns them. A global assigned in three files has no owner and no one can change it safely.
```lua title="client/shops.lua"
local MAX_DISTANCE = 20.0
local INTERACT_KEY = 38 -- E
local shops = {}
local nearestShop = nil
```
CfxLua is Lua 5.4, so `` works and the compiler enforces it: assigning to a `` local is a compile error, not a runtime surprise. When the value is a literal the compiler folds it into the code that uses it, so it costs nothing.
> [!NOTE]
> Lua allows 200 local variables per function and per chunk. Declaring every single config entry as its own file level local is a real way to hit "too many local variables". Group related values into one table instead.
## Locals beat globals
A local lives in a register. A global is a key in the `_ENV` table, so every read and every write is a hash lookup. The difference per access is small, but it is free to avoid:
```lua
-- Three hash lookups per iteration
for i = 1, 1000 do
Config.total = Config.total + Config.prices[i]
end
-- One lookup each, then registers
local prices = Config.prices
local total = 0
for i = 1, 1000 do
total = total + prices[i]
end
Config.total = total
```
The same trick works for functions you call in a loop, including globals from the standard library:
```lua
local floor = math.floor
local insert = table.insert -- when you genuinely need insert
```
Do this inside hot code, not at the top of every file out of habit. A file with 30 hoisted stdlib names at the top is harder to read than the lookups it saves.
## Booleans that should be a state
The pattern to watch for is two or more booleans describing one thing:
```lua title="client.lua (ambiguous)"
local isWalking = false
local isRunning = false
local isSwimming = false
```
Every combination is representable, including the ones that make no sense. What does it mean when `isWalking` and `isSwimming` are both true? What does it mean when all three are false: standing still, or nobody has set them yet? Now every reader of that code has to defend against combinations you never intended, and every writer has to remember to clear the other two.
One value with named options removes the whole problem:
```lua title="client.lua (one state)"
local MOVEMENT = {
UNKNOWN = 0,
IDLE = 1,
WALKING = 2,
RUNNING = 3,
SWIMMING = 4,
}
local movement = MOVEMENT.UNKNOWN
local function setMovement(state)
if movement == state then return end
movement = state
TriggerEvent('my_resource:client:movementChanged', state)
end
```
You get an impossible state for free (`UNKNOWN`), adding `CLIMBING` is one line, and comparisons read as English. It also fits state bags and network payloads better: one small number instead of three fields that can arrive out of step. See [State bags and OneSync](/docs/development/state-bags-onesync).
Lua has no real enum type, so the table is the convention. Keep it ``, keep the values numbers if they will be sent over the network, and keep it in a shared file if both sides need it.
## Magic numbers
A number nobody can explain is a bug waiting to be copied:
```lua
TaskPlayAnim(ped, dict, clip, 8.0, -8.0, 3000, 49, 0, false, false, false)
```
`49` is an animation flag set, and the only way to know which is to look it up. Name it:
```lua
local ANIM_FLAGS = 49 -- loop + upper body + allow player control
```
Our [Animation Flags Calculator](/tools/animation-flags-calculator) builds that number from named options, and the [Driving Style Calculator](/tools/driving-style-calculator) does the same for `TaskVehicleDriveToCoord`. Control indexes like `38` have names in the [Controls Reference](/tools/controls-reference).
Next: [Conditionals and early returns](/docs/code-optimisation/conditionals).
_Last updated: 2026-09-25_
---
## Conditionals and early returns
URL: https://fivemad.com/docs/code-optimisation/conditionals
Guard clauses that keep functions flat, returning the expression instead of true or false, the or default trap, and ordering checks so the cheap one runs first.
Most unreadable Lua is not complicated logic. It is simple logic wrapped in four levels of `if`. These are the four changes that fix nearly all of it.
## Guard clauses
Handle the reasons to stop first, one per line, then write the real work at the left margin:
```lua title="server.lua (nested)"
RegisterNetEvent('shop:server:buy', function(item, amount)
local src = source
local player = GetPlayer(src)
if player then
if Items[item] then
if type(amount) == 'number' and amount > 0 then
if player.money >= Items[item].price * amount then
giveItem(src, item, amount)
takeMoney(src, Items[item].price * amount)
else
notify(src, 'Not enough money')
end
end
end
end
end)
```
```lua title="server.lua (guarded)"
RegisterNetEvent('shop:server:buy', function(item, amount)
local src = source
local player = GetPlayer(src)
if not player then return end
local def = Items[item]
if not def then return end
if type(amount) ~= 'number' or amount < 1 or amount > 100 then return end
local cost = def.price * amount
if player.money < cost then
return notify(src, 'Not enough money')
end
takeMoney(src, cost)
giveItem(src, item, amount)
end)
```
Same logic, no nesting, and every precondition is visible in the first few lines. When you add a fifth check you add a line instead of another level.
Two practical notes. Do the **cheap checks first** so the expensive ones never run on bad input: a `type()` check before a database call, not after. And do the checks **in dependency order**, so nothing reads a value that an earlier check has not confirmed yet.
## Return the expression
If both branches return a boolean, the condition already is the answer:
```lua
-- Noise
if role == 'police' or role == 'ems' then
return true
else
return false
end
-- The same thing
return role == 'police' or role == 'ems'
```
The same goes for `if x then y = true else y = false end`. Assign the comparison.
## Default values with `or`
Lua's `or` returns the first value that is not `nil` or `false`, which makes defaults short:
```lua
local function greet(name)
return 'Hello, ' .. (name or 'stranger')
end
```
> [!WARNING]
> This trap catches everyone once. `or` treats `false` exactly like `nil`, so a default for a **boolean** option silently ignores the caller.
```lua
-- Broken: passing false gives you true
local function setup(opts)
local enabled = opts.enabled or true -- always true
end
-- Correct
local function setup(opts)
local enabled = opts.enabled
if enabled == nil then enabled = true end
end
```
The same applies to numbers when `0` is meaningful in your code. `0` is truthy in Lua, so `count or 10` is safe, but `value ~= nil` is what you want whenever `false` is a legitimate value.
The related idiom `cond and a or b` is not a ternary operator. It breaks when `a` is `false` or `nil`, because the `and` fails and you get `b`:
```lua
local label = isDead and false or 'alive' -- always 'alive'
```
Use it for values you know are never `false` or `nil`, and write a real `if` otherwise.
## Prefer the positive form
`not` costs the reader a mental flip, and two of them cost a re-read:
```lua
-- Backwards
if not isOnDuty then
hideBlip()
else
showBlip()
end
-- Forwards
if isOnDuty then
showBlip()
else
hideBlip()
end
```
Name variables positively for the same reason: `isReady` reads better than `isNotReady`, and `if not isNotReady` is how you get bugs.
The exception is a guard clause, which is nearly always negative on purpose (`if not player then return end`). That is fine: there is no `else` to flip, and the negative form is the whole point.
## A lookup instead of a chain
Once an `if / elseif` chain is comparing the same variable against five constants, a table says it better and does not get longer with each new case:
```lua
-- Grows a branch per item
if item == 'water' then
restoreThirst(20)
elseif item == 'cola' then
restoreThirst(35)
elseif item == 'coffee' then
restoreThirst(15)
end
-- Grows a line per item, and the data can move to a config file
local DRINKS = { water = 20, cola = 35, coffee = 15 }
local thirst = DRINKS[item]
if thirst then restoreThirst(thirst) end
```
The table version is also a single hash lookup instead of up to five comparisons, which matters if this runs per frame or per item in a loop.
Next: [Tables and loops](/docs/code-optimisation/tables-and-loops).
_Last updated: 2026-09-25_
---
## Tables and loops
URL: https://fivemad.com/docs/code-optimisation/tables-and-loops
Building arrays without table.insert, numeric for against pairs, caching repeated lookups, keeping a size counter, and not generating garbage every frame.
Tables are the only data structure Lua has, so almost every hot loop in a FiveM resource is a table loop. None of the changes below are dramatic on their own. Together, in code that runs per frame or over a few thousand rows, they add up.
## Let arrays index themselves
Writing the indexes out is noise, and it is a chance to get them wrong:
```lua
-- Noise, and nothing checks that the numbers are in order
local spawns = {
[1] = vector3(-269.4, -955.3, 31.2),
[2] = vector3(195.1, -933.5, 30.6),
[3] = vector3(-1037.7, -2737.5, 20.1),
}
-- Same table
local spawns = {
vector3(-269.4, -955.3, 31.2),
vector3(195.1, -933.5, 30.6),
vector3(-1037.7, -2737.5, 20.1),
}
```
Write explicit keys only when the number means something, such as a seat index or a component id where `[4]` skipping `[3]` is deliberate.
## Dot for fixed keys, brackets for variable keys
```lua
local price = items.water.price -- key is known while you write it
local price = items[itemName].price -- key comes from a variable
```
They compile to the same lookup, so this is purely about the reader. `items["water"]` in the middle of a line makes people stop and check whether the key is dynamic.
## Cache repeated lookups
Every `a.b.c` is two hash lookups. Repeat it five times in one function and you have done ten:
```lua
-- Four lookup chains
if Config.Shops[id].stock > 0 and Config.Shops[id].open then
Config.Shops[id].stock = Config.Shops[id].stock - 1
end
-- One chain, then a local
local shop = Config.Shops[id]
if shop.stock > 0 and shop.open then
shop.stock = shop.stock - 1
end
```
The second version is faster and much easier to read, and because tables are references, writing to `shop.stock` still writes to the real table.
## Appending: `t[#t + 1]` over `table.insert`
For a plain append, `table.insert(t, v)` and `t[#t + 1] = v` have the same result, but `table.insert` is a C library function: it validates the argument, takes the table length through the C API, and assigns through the C API. Direct indexing is a few VM instructions and never leaves the interpreter.
```lua
-- Slightly more work per call
table.insert(results, value)
-- The direct form
results[#results + 1] = value
```
Setting a named key with `table.insert` does not work at all, whatever you may have seen. `table.insert(t, 'key', 'value')` is interpreted as "insert `'value'` at position `'key'`" and errors. Write `t.key = value`.
Keep `table.insert` for what it is actually for: inserting into the middle of an array and shifting the rest up, which is the one thing the direct form cannot do.
> [!NOTE]
> The difference is small. It is worth writing the direct form by default because it costs nothing to type, and worth changing inside a loop over thousands of rows. It is not worth a pull request across a working resource.
## Keep a counter when you are filling an array
```lua
-- The length is looked up on every pass
local out = {}
for i = 1, #source do
out[#out + 1] = transform(source[i])
end
-- No length lookup at all
local out, n = {}, 0
for i = 1, #source do
n = n + 1
out[n] = transform(source[i])
end
```
You will find claims that `#t` is a linear scan. It is not: Lua looks for the array boundary with the size it already tracks and a binary search at worst, so the cost is small and does not grow the way a scan would. The counter is still worth it in a tight loop because it replaces that search with an addition, and there is a correctness reason too: if the array can contain `nil` holes, `#t` is allowed to return any boundary, so `t[#t + 1]` can overwrite an existing value. A counter you control never does.
## Numeric `for` over `pairs` for arrays
```lua
-- Slower, and the order is not defined
for _, shop in pairs(shops) do
drawShop(shop)
end
-- Fastest, and in order
for i = 1, #shops do
drawShop(shops[i])
end
```
`pairs` returns the `next` function and calls it on every iteration, and the standard makes no promise about the order it walks a table in. For an array where the order matters, that alone is a reason to use a numeric loop. `ipairs` keeps the order and is close in speed, but it stops at the first `nil`, which silently truncates an array with a hole in it.
Use `pairs` for what it is for: hash tables with string keys, where there is no index to count.
## Do not build garbage every frame
The collector is the one cost that shows up as a stutter rather than a number. Anything allocated in a per frame loop is collected later, in a frame you did not choose:
```lua
-- A new table and a new string, 60 times a second
CreateThread(function()
while true do
Wait(0)
local pos = { x = 0.5, y = 0.9 }
drawText('Speed: ' .. math.floor(speed) .. ' km/h', pos)
end
end)
-- One table, reused, and the string only rebuilt when it changes
local pos = { x = 0.5, y = 0.9 }
local lastSpeed, label = -1, ''
CreateThread(function()
while true do
Wait(0)
local s = math.floor(speed)
if s ~= lastSpeed then
lastSpeed = s
label = 'Speed: ' .. s .. ' km/h'
end
drawText(label, pos)
end
end)
```
Strings in Lua are immutable, so every `..` creates a new one. Building a string from many parts belongs in a table plus one `table.concat`, not in a loop of concatenations:
```lua
local parts, n = {}, 0
for i = 1, #rows do
n = n + 1
parts[n] = rows[i].name
end
local line = table.concat(parts, ', ')
```
## Search once, not every time
A linear search through a config table inside a loop is the shape that quietly costs the most. Build the lookup once:
```lua
-- O(n) per call, every call
local function isBlacklisted(model)
for i = 1, #Config.Blacklist do
if Config.Blacklist[i] == model then return true end
end
return false
end
-- Built once when the file loads, O(1) per call
local blacklist = {}
for i = 1, #Config.Blacklist do
blacklist[Config.Blacklist[i]] = true
end
local function isBlacklisted(model)
return blacklist[model] == true
end
```
If the config holds model names and you compare against hashes, hash the keys once while building the set instead of hashing inside the check. See [Cheap native calls](/docs/code-optimisation/natives).
## Clean up what you keep
A table you keep adding to and never remove from is a memory leak with extra steps. Set entries to `nil` when they are done, especially tables keyed by player server id or entity handle, and clear them on `playerDropped` and `onResourceStop`. resmon's memory column is where you notice.
Next: [Cheap native calls](/docs/code-optimisation/natives).
_Last updated: 2026-09-25_
---
## Cheap native calls
URL: https://fivemad.com/docs/code-optimisation/natives
Backtick hashes, joaat, vector distance instead of GetDistanceBetweenCoords, caching ped handles safely, and keeping per frame natives behind a gate.
A native call leaves the Lua interpreter, crosses into the game or the server core, and comes back. It is not expensive on its own, and it is not free either. In a loop that runs every frame the number of native calls per pass is usually the biggest thing you control.
This page is about the cost. For what natives are and how to find them, see [Natives: talking to the game](/docs/development/natives).
## Hash strings at compile time
GTA identifies models, weapons, anim sets and much more by a 32 bit joaat hash of the name. You have three ways to produce one, and they are not equal:
```lua
local a = GetHashKey('adder') -- a native call, at runtime, every time
local b = joaat('adder') -- a CfxLua function, at runtime, no native call
local c = `adder` -- hashed while the script compiles, nothing at runtime
```
All three give the same number. The backtick form is the one to use for a name you type in the source: the Cfx docs describe it as compile time generation of hash keys with zero runtime overhead, so `` `adder` `` is a literal number by the time the script runs.
When the name comes from a variable you cannot use backticks, and then `joaat(name)` is the right call. It hashes in the Lua runtime instead of going out to a native. Note that `joaat` lowercases the input before hashing, which is also why spawn names work in any case.
```lua
-- In a loop, over a config full of names
for i = 1, #Config.Blacklist do
blacklist[joaat(Config.Blacklist[i])] = true -- hashed once, at load
end
local function isBlacklisted(model)
return blacklist[model] == true -- no hashing per call
end
```
`GetHashKey` is not broken and thousands of resources use it. There is just no case left where it is the best of the three.
## Distance without a native
Vectors are real types in CfxLua, and `#v` is the magnitude of a vector, so the distance between two points is one operator:
```lua
-- A native call with seven arguments
local d = GetDistanceBetweenCoords(x1, y1, z1, x2, y2, z2, true)
-- Vector maths in the VM
local d = #(coordsA - coordsB)
```
Most position natives already hand you a `vector3`, so the second form usually saves you unpacking as well. When you are only comparing against a radius and do not need the number itself, you can skip the square root by comparing the squared lengths:
```lua
local diff = coordsA - coordsB
if (diff.x * diff.x + diff.y * diff.y + diff.z * diff.z) < (20.0 * 20.0) then
```
That is worth it over a few thousand comparisons and not worth the loss of clarity over forty. Use `#(a - b) < 20.0` unless you have measured a reason not to.
For a flat check that ignores height, build the difference and leave `z` out of the sum, or compare `vector2(a.x, a.y)` against `vector2(b.x, b.y)`.
## The local ped
```lua
local ped = GetPlayerPed(-1) -- old, magic number
local ped = PlayerPedId() -- the current way
```
Both are natives. The important part is not which one you call, it is how often. Inside a loop, call it once per pass and reuse the handle:
```lua
CreateThread(function()
while true do
local ped = PlayerPedId() -- once per pass
local pos = GetEntityCoords(ped) -- once per pass
...
Wait(sleep)
end
end)
```
> [!WARNING]
> Do not cache a ped handle forever. The handle changes when the player respawns or the model is switched, and code holding the old one will silently do nothing. Cache it for the body of a loop pass, or use `ox_lib`'s `cache.ped`, which refreshes itself when the ped changes.
The same applies to any handle: vehicles, objects and blips are local numbers that can become invalid. Check with `DoesEntityExist(entity)` before you use one you stored.
## Drop the `Citizen.` prefix
`Wait`, `CreateThread`, `SetTimeout` and `ClearTimeout` are set up as plain global aliases of the `Citizen.*` functions in the FiveM Lua scheduler. `Wait` **is** `Citizen.Wait`, the same function object.
```lua
Citizen.CreateThread(function()
Citizen.Wait(1000)
end)
CreateThread(function()
Wait(1000)
end)
```
So this is a readability change, not a speed one. The prefixed form costs one extra table lookup per call and nothing else, which is nothing you will ever measure. Write the short form because every current example does, and be suspicious of a tutorial that still uses the long one: it is usually old enough that other things in it are out of date too.
## Per frame natives belong behind a gate
Some natives only do anything for the frame you call them in. `DrawMarker`, `DrawText`, `DisableControlAction`, `HideHudComponentThisFrame` and friends all have to run every frame to stay on screen, which means a `Wait(0)` loop, which means you must make sure that loop is not running when there is nothing to draw:
```lua
CreateThread(function()
while true do
local sleep = 500
if nearMarker then
sleep = 0
DrawMarker(...)
end
Wait(sleep)
end
end)
```
That pattern, and the `ox_lib` points and zones that replace it, are covered in [Threads and performance](/docs/development/threads-performance).
## Hoist what cannot change
Anything constant for the life of the resource should be read once, not per frame:
```lua
-- Called every frame, always the same answer
CreateThread(function()
while true do
Wait(0)
if GetCurrentResourceName() == 'my_resource' then ... end
end
end)
-- Read once at load
local RESOURCE = GetCurrentResourceName()
```
Convars, screen resolution, config values and model hashes all fall in this group. Resolution is the one exception worth a note: it can change when the player alt tabs or edits settings, so read it on a timer or on the relevant event rather than every frame.
## Load and release streamed assets
Models, anim dicts, particle assets, texture dicts and scaleforms have to be requested and waited for. Always put a timeout on the wait so a missing asset does not hang a thread forever, and release what you loaded:
```lua
local function loadModel(model)
local hash = type(model) == 'number' and model or joaat(model)
if not IsModelInCdimage(hash) then return nil end
RequestModel(hash)
local deadline = GetGameTimer() + 5000
while not HasModelLoaded(hash) do
if GetGameTimer() > deadline then return nil end
Wait(0)
end
return hash
end
-- when you are done
SetModelAsNoLongerNeeded(hash)
```
`ox_lib` ships `lib.requestModel`, `lib.requestAnimDict` and `lib.requestNamedPtfxAsset` with the timeout already handled.
Next: [Events that stay cheap and safe](/docs/code-optimisation/events).
_Last updated: 2026-09-25_
---
## Events that stay cheap and safe
URL: https://fivemad.com/docs/code-optimisation/events
Naming events so handlers stay independent, when a function beats an event, RegisterNetEvent against AddEventHandler, payload size, latent events and the source trap.
Events are how the two sides of FiveM talk, and how resources talk to each other without knowing anything about each other. They are also the place where a careless line becomes both a performance problem and an exploit.
For the mechanics of triggering and listening, see [Client, server and events](/docs/development/client-server-events). This page is about which event to use and how to name it.
## Name them `resource:side:thing`
```lua
TriggerServerEvent('fm_shops:server:boughtItem', item, amount)
TriggerClientEvent('fm_shops:client:stockChanged', -1, shopId, stock)
```
Three parts, and each one earns its place. The resource name keeps your events out of everyone else's namespace and tells the next person where the handler lives. The side tells you which script to open. The last part says what happened.
Prefix with your resource's real folder name. Generic names like `updateStock` are how two resources end up triggering each other's handlers by accident.
## Name the cause, not the effect
This is the naming rule that actually changes how code grows. An event is a fact that has happened, so name it in the past tense and describe the fact, not what you want somebody to do about it:
```lua
-- The name bakes in one handler's job
TriggerEvent('fm_chat:server:checkProfanity', message)
-- The name is the fact, and any number of handlers can care
TriggerEvent('fm_chat:server:sentMessage', src, message)
```
With the second name, the profanity filter is one handler, the logger is another, and the anti spam counter is a third. None of them knows the others exist and you can remove any of them without renaming anything. With the first name, the logger has to subscribe to an event called "check profanity", which is where a codebase starts lying to its readers.
If only one thing will ever react, you probably do not want an event at all.
## A local event with one handler should be a function
An event buys you one thing: several handlers, registered in places that do not know each other. If you are triggering and handling in the same resource, on the same side, with one handler, you are paying for a lookup and an argument pack to call a function you could have called directly.
```lua
-- Indirection for nothing
AddEventHandler('fm_shops:client:refresh', function() refreshUi() end)
TriggerEvent('fm_shops:client:refresh')
-- Just call it
refreshUi()
```
Arguments passed to `TriggerEvent` are packed with MessagePack and unpacked by each handler, so this is not purely a style point either.
## Register only what has to cross
`AddEventHandler` alone does **not** make an event reachable from the network. `RegisterNetEvent` is what opens that door:
```lua
-- Server only. A player cannot trigger this.
AddEventHandler('fm_shops:server:restock', restockAll)
-- A player can trigger this, with any arguments they like.
RegisterNetEvent('fm_shops:server:boughtItem', function(item, amount) ... end)
```
Every `RegisterNetEvent` on the server is a function you have published to every player on your server, callable with whatever arguments they choose, as often as they like. Use it only when the client genuinely has to start the conversation, and treat every argument as hostile: check the type, check the range, and look the real values up server side instead of trusting the ones you were handed.
```lua
RegisterNetEvent('fm_shops:server:boughtItem', function(item, amount)
local src = source
if type(item) ~= 'string' then return end
if type(amount) ~= 'number' or amount % 1 ~= 0 or amount < 1 or amount > 100 then return end
local def = Items[item] -- the price comes from the server, never the client
if not def then return end
...
end)
```
## `GetInvokingResource` is a boundary, not a lock
`GetInvokingResource()` returns the name of the resource that triggered the event you are handling, and returns `nil` when the trigger came from the other side of the network. That makes it useful for one thing: keeping other resources out of an event that is meant to be internal.
```lua
local ALLOWED = { fm_core = true, fm_banking = true }
AddEventHandler('fm_shops:server:adjustStock', function(shopId, delta)
local from = GetInvokingResource()
if not from or not ALLOWED[from] then return end
...
end)
```
Older artifacts returned `nil` for an event triggered from inside the same resource as the handler, so do not build your own internal flow on top of it. If the caller is your own code, call the function.
It does **not** authenticate a net event. Every client trigger returns `nil` there, so a check like "if it is `nil` then it came from a trusted place" has the logic backwards. Validation on the server is the only thing protecting a net event.
## Save `source` before you wait
On the server, `source` is a global that holds the player who triggered the current event. It is only guaranteed for the initial call: as soon as your handler calls `Wait`, or awaits a query, the global can be something else.
```lua
RegisterNetEvent('fm_shops:server:boughtItem', function(item, amount)
local src = source -- first line, every time
Wait(100)
print(src, source) -- src is still right, source may not be
end)
```
Make `local src = source` the first line of every server event handler. It costs nothing and removes a class of bug that only shows up when two players do something at the same moment.
## Ask once, with a callback
The pattern to avoid is triggering an event to ask for data and listening for a second event with the answer. It is twice the round trips, it needs two handlers, and two requests in flight at once get mixed up.
```lua
-- Ping pong
TriggerServerEvent('fm_shops:server:requestStock', shopId)
RegisterNetEvent('fm_shops:client:stockResponse', function(stock) ... end)
-- One call, with ox_lib callbacks
local stock = lib.callback.await('fm_shops:server:getStock', false, shopId)
```
FiveM has no callback system of its own, so this comes from a library: `lib.callback` in `ox_lib`, `QBCore.Functions.TriggerCallback`, `ESX.TriggerServerCallback`. Whichever framework you are on has one. Use it for "get me a value", and keep plain events for "this happened".
## Payload size and how often
Two habits cover nearly all network cost:
- **Send on change, not on a timer.** A HUD that receives the player's money every frame is sending 60 times more than a HUD that receives it when it changes.
- **Send what changed, not everything.** Pushing an entire inventory table because one item moved is the most common oversized payload in FiveM.
For values that change constantly and every nearby client cares about, a state bag is usually the better tool than an event: it syncs the value itself instead of a message about the value. See [State bags and OneSync](/docs/development/state-bags-onesync).
When you genuinely do have a lot of data to move, the latent variants exist for it. `TriggerLatentServerEvent` and `TriggerLatentClientEvent` take a bytes per second budget and spread the transfer out instead of blocking the network channel like a normal trigger would. The default is 25000 bytes per second when you pass `-1` or `0`, and the Cfx docs warn that very large values cause connectivity problems, so do not set it to ten million and call it optimisation.
```lua
TriggerLatentClientEvent('fm_shops:client:fullCatalogue', src, 50000, catalogue)
```
Next: [Exports and resource boundaries](/docs/code-optimisation/exports).
_Last updated: 2026-09-25_
---
## Exports and resource boundaries
URL: https://fivemad.com/docs/code-optimisation/exports
What an export call really costs in FiveM, keeping payloads small without making the API chatty, shared files that skip the boundary, and naming an API people can use.
An export looks like a function call and is not one. `exports.banking:GetBalance(id)` reaches into another resource, which has its own Lua state, so the arguments and the return value have to be packed on one side and unpacked on the other. The FiveM Lua scheduler does that with MessagePack, through a function reference.
None of that is slow for a call you make when a player opens a menu. It becomes the thing you measure when the call sits inside a loop, or when the payload is large.
For the basics of defining and calling exports, see [Exports and dependencies](/docs/development/exports-dependencies).
## Call it less, not smaller
The first instinct when someone hears "exports serialise" is to make the API tiny. That trades one problem for another:
```lua
-- One boundary crossing, one big payload
local data = exports.fm_core:GetPlayerData(src)
-- 200 boundary crossings
local items = {}
for i = 1, 200 do
items[i] = exports.fm_core:GetInventorySlot(src, i)
end
```
Neither extreme is the answer. The rule that holds up is **design the export around what the caller needs**, so there is one call and it returns exactly that:
```lua
exports('GetInventorySlots', function(src, from, to) ... end) -- one call, the range you want
exports('GetBalance', function(src) return accounts[src] or 0 end) -- one number, no wrapper table
```
A `GetPlayerData` style export that hands back the whole player object on every call is the shape to avoid, because every caller pays for the parts it does not use, and because the caller gets a **copy**: changing a field on the table you received does not change anything in the owning resource. That surprises people regularly.
## Inside one resource, nothing is copied
Tables are references in Lua. Returning a big table from a local function to your own code hands back a pointer, not a copy, and costs nothing. Keep that in mind before you split your own internal API into accessors "for performance": the copy only exists at the resource boundary.
## Hoist the lookup out of a loop
`exports.banking` goes through a metatable and caches the reference after the first use, so the second call is cheaper than the first. If you are calling in a loop anyway, take the handle out of it:
```lua
local banking = exports.fm_banking
for i = 1, #players do
banking:AddBalance(players[i], 100)
end
```
Better still, give the other resource a call that takes the list:
```lua
exports.fm_banking:AddBalanceBulk(players, 100)
```
One crossing instead of `n`, and the owning resource can do the whole thing in one database transaction.
## Shared files skip the boundary entirely
Constants, enums and pure helper functions do not need an export at all. A file loaded into your resource with `@resource/file` runs in **your** Lua state, so calling it is an ordinary Lua call with no packing:
```lua title="fxmanifest.lua"
shared_scripts {
'@ox_lib/init.lua',
'@fm_core/shared/enums.lua',
}
```
That is why `ox_lib` is used this way: `lib.callback`, `lib.points`, `lib.requestModel` and friends are your own code once the file is loaded. Use shared files for anything with no state of its own, and keep exports for things only the owning resource can answer, like a balance or an inventory.
Remember that a shared file is downloaded by clients. Do not put prices, checks or secrets in one. See [Scope, files and layout](/docs/code-optimisation/scope-and-structure).
## Name an API you would want to use
- **PascalCase** for export names, matching the rest of FiveM: `GetBalance`, `AddItem`, `HasLicense`.
- **Start with a verb**, and make `Get` mean "reads nothing changes" and `Set` or `Add` mean "changes something".
- **Annotate every export** with Lua Language Server comments so the people calling it get parameter hints. See [Functions that stay small](/docs/code-optimisation/functions#annotate-what-other-people-call).
- **Return something a caller can branch on.** `false` plus a reason beats an error the caller cannot catch. See [Error handling](/docs/code-optimisation/error-handling).
```lua title="server/api.lua"
---@param src number Player server id
---@param amount number Positive amount
---@return boolean ok
---@return string? reason 'invalid_amount' | 'insufficient_funds'
local function removeBalance(src, amount)
if type(amount) ~= 'number' or amount <= 0 then return false, 'invalid_amount' end
local balance = accounts[src] or 0
if balance < amount then return false, 'insufficient_funds' end
accounts[src] = balance - amount
return true
end
exports('RemoveBalance', removeBalance)
```
Keeping the real function local and exporting it separately means your own resource calls it directly, with no boundary, and only other resources pay for the crossing.
## Declare what you depend on
```lua title="fxmanifest.lua"
dependencies { 'ox_lib', 'oxmysql' }
```
FXServer starts dependencies first and refuses to start your resource if one is missing, which turns a confusing `No such export` at 3am into a clear line in the console at startup. For an optional integration, check instead of depending:
```lua
local hasTarget = GetResourceState('ox_target') == 'started'
```
Next: [Error handling](/docs/code-optimisation/error-handling).
_Last updated: 2026-09-25_
---
## Error handling
URL: https://fivemad.com/docs/code-optimisation/error-handling
Assertions for bugs, returned errors for expected failures, checking preconditions up front, using pcall honestly and writing messages you can actually debug from.
A silent failure is the most expensive bug there is. It does not show up in the console, nobody reports it for a week, and when they do the report is "the shop is weird sometimes". Deciding up front how each kind of failure behaves is most of what error handling means.
Two kinds of failure, two different answers:
| Kind | Example | Answer |
| --- | --- | --- |
| **Bug** | A function was called with a table where it expects a number | Throw. Loudly. Fix the caller. |
| **Expected failure** | The player typed an amount they cannot afford | Return a result the caller can act on. |
Mixing these up is what produces either a console full of errors nobody reads, or a resource that quietly does nothing.
## `assert` for preconditions
`assert` is shorter than the `if` it replaces and it puts the message next to the condition:
```lua
-- Noise
if type(amount) ~= 'number' then
error('amount must be a number')
end
-- Same thing
assert(type(amount) == 'number', 'amount must be a number')
```
Write the assumptions of a function at the top of it, one per line. If you cannot name an assumption, you have found something you had not thought about yet:
```lua
local function transfer(fromSrc, toSrc, amount)
assert(type(fromSrc) == 'number', 'fromSrc must be a player server id')
assert(type(toSrc) == 'number', 'toSrc must be a player server id')
assert(type(amount) == 'number' and amount > 0, 'amount must be a positive number')
assert(fromSrc ~= toSrc, 'cannot transfer to yourself')
...
end
```
Remember that `assert` evaluates its message argument whether or not the assertion fails, so do not build a string in it inside a hot loop. `assert(ok, 'bad id ' .. tostring(id))` concatenates on every successful call too.
## Fail loudly when the state makes no sense
The tempting line is `if not somethingWeird then return end`. It makes the error go away and it makes the cause impossible to find:
```lua
-- Silently does nothing, forever
local function payout(src)
if not IsPlayerDead(src) then return end
...
end
-- Says what went wrong, the first time it goes wrong
local function payout(src)
assert(IsPlayerDead(src), ('payout called for living player %s'):format(src))
...
end
```
The difference matters when the condition should be impossible. If a dead player check is a normal part of the flow, a quiet `return` is correct. If reaching that line with a living player means somebody called the function wrong, throw.
The question to ask is: **could a player cause this, or only a programmer?** Player input is an expected failure. Programmer mistakes should be loud.
## Return errors for things players do
Validation on a net event is not a bug. Players will send bad data, sometimes by accident and sometimes on purpose, and throwing an error every time floods your console and gives an attacker a way to fill your logs.
```lua
---@return boolean ok
---@return string? reason
local function buy(src, item, amount)
local def = Items[item]
if not def then return false, 'unknown_item' end
if amount < 1 or amount > def.maxStack then return false, 'invalid_amount' end
if getMoney(src) < def.price * amount then return false, 'insufficient_funds' end
...
return true
end
RegisterNetEvent('fm_shops:server:boughtItem', function(item, amount)
local src = source
if type(item) ~= 'string' or type(amount) ~= 'number' then return end
local ok, reason = buy(src, item, amount)
if not ok then
return TriggerClientEvent('fm_shops:client:purchaseFailed', src, reason)
end
end)
```
The caller decides what to do, the player gets a message instead of a hang, and nothing lands in the console. Return a short machine readable reason code rather than a sentence, so the client can translate it and so your own code can branch on it.
## Partial work: log, do not abort
When an operation covers several independent items, throwing on the first problem throws away the work that succeeded:
```lua
local failed, n = {}, 0
for i = 1, #items do
local ok, reason = sellItem(src, items[i])
if not ok then
n = n + 1
failed[n] = ('%s (%s)'):format(items[i], reason)
end
end
if n > 0 then
print(('[fm_shops] %s: %s of %s items failed: %s'):format(src, n, #items, table.concat(failed, ', ')))
end
```
Nine items sell, one is reported, and you have a line in the log naming the player and the item. That is the right shape whenever one failure does not invalidate the rest.
## `pcall` honestly
`pcall` catches an error and hands you the message instead of letting it reach the console:
```lua
local ok, result = pcall(json.decode, body)
if not ok then
print(('[fm_api] bad JSON from %s: %s'):format(url, result))
return
end
```
Use it around things that can fail for reasons outside your code: parsing data you did not create, an HTTP response, a database call, a third party export that might not be loaded.
> [!WARNING]
> Do not wrap your own logic in `pcall` to make the red text stop. That is not error handling, it is hiding the only clue you had. If you catch, log what you caught.
## Messages you can debug from
A good error message names the resource, the value and what was expected. A bad one says `attempt to index a nil value`.
```lua
-- Useless six months later
assert(shop)
-- Useful immediately
assert(shop, ('unknown shop id %s in config'):format(tostring(id)))
```
`tostring()` around the value keeps the message itself from erroring when the value is `nil`, which is the exact case you are reporting. Prefix console output with your resource name in brackets so the server console stays readable with 200 resources running.
For reading the errors you do produce, and for the tools that make them easier to find, see [Debugging](/docs/development/debugging).
_Last updated: 2026-09-25_
---
# Video tutorials
## FiveM video tutorial archive
URL: https://fivemad.com/docs/videos
A hand-picked training set of FiveM YouTube tutorials, grouped into courses from first server to Lua, NUI, streaming assets, CodeWalker and Blender with Sollumz.
Some things are easier to learn by watching someone do them. This archive collects FiveM tutorials from YouTube and puts them in order, so you get a course instead of a search results page. Every video was checked to exist and picked because it's clear, accurate enough and still useful today.
## How it's organised
The archive has ten courses. Each has a level and its lessons in a sensible order:
| Course | Level | For |
| --- | --- | --- |
| Run your first server | Beginner | Getting a server online on Windows, Linux or a VPS, license key, database, ports, updates, vMenu |
| txAdmin in depth | Beginner | The in-game menu, admins, the Discord bot, whitelisting |
| Frameworks: QBCore, Qbox and ESX | Beginner | Choosing and installing a framework, jobs, items, ox_inventory |
| Lua scripting for FiveM: the basics | Beginner | Editor setup, first resource, commands, natives, events, callbacks, threads |
| Scripting in depth | Intermediate | State bags, routing buckets, databases, exports, full job systems, JavaScript and C# |
| NUI and user interfaces | Intermediate | HTML UIs, focus and callbacks, React, loading screens |
| Streaming assets: vehicles, clothing and MLOs | Intermediate | Car packs and their meta files, textures, clothing packs, MLO installs |
| CodeWalker and map editing | Intermediate | YMAPs, adding and removing props, merging maps, MLO collisions |
| 3D modelling with Blender and Sollumz | Advanced | Props, collisions, lights, vehicles, clothing and MLO interiors |
| Performance, security and workflow | Intermediate | resmon, optimisation, stopping cheaters, git |
## How to use it
- **Pair videos with the written guides.** Each course matches a section of these docs: watch the video, then use the guide as the reference. For example the Lua course goes with [Your first resource](/docs/development/first-resource) and [Client, server and events](/docs/development/client-server-events).
- **Follow the order inside a course**, but skip what you already know.
- **Code along.** Keep a local dev server running (see [Windows setup](/docs/server-setup/windows)) and type the code yourself instead of just watching.
- **Check the date.** Every lesson shows when it was published. FiveM changes: older videos may show old txAdmin screens, `GetPlayerPed(-1)` instead of `PlayerPedId()`, or framework code from earlier versions. The ideas still hold, and the written guides show the current way.
> [!NOTE]
> The videos belong to their creators and are embedded from YouTube. The descriptions are ours. Many creators also sell resources or hosting; being listed here isn't an endorsement of anything but the video.
## About Vespura and the official channels
Tom Grobbe (Vespura), the author of vMenu, documents his work in writing at [docs.vespura.com](https://docs.vespura.com/) rather than on YouTube, so his projects appear here through other creators' install videos and in our [recommended resources](/docs/resources/recommended#vmenu) page. Cfx.re's own documentation is written too, at [docs.fivem.net](https://docs.fivem.net/docs/). The official [txAdmin channel](https://www.youtube.com/@txAdmin) has a few short videos, included in the txAdmin course.
## Missing something?
If a video goes private or a better one comes out, we update the archive. Suggestions are welcome through the fivemad Discord.
_Last updated: 2026-09-22_
---
# Getting started
## Getting started with FiveM servers and development
URL: https://fivemad.com/docs/getting-started
What FiveM, FXServer, txAdmin and Cfx.re are, how the pieces fit together, and the order to read these docs in to run a server or write scripts.
These docs take you from "I want a FiveM server" to running one, managing it with txAdmin, installing resources and frameworks, and writing your own scripts. Everything here is checked against the official Cfx.re documentation and the source repositories on GitHub. When something depends on a version, the page says so.
If you only want to get a server online today, jump to [Setting up a server on Windows](/docs/server-setup/windows) or [on Linux](/docs/server-setup/linux). If you want to write code, start with [Your first resource](/docs/development/first-resource). Come back to this page when a word stops making sense.
## The pieces and who makes them
FiveM is a modification framework for Grand Theft Auto V that lets people run their own multiplayer servers with custom code, maps, vehicles and game modes. A few names show up everywhere:
| Name | What it is |
| --- | --- |
| **Cfx.re** | The team and platform behind FiveM (GTA V) and RedM (Red Dead Redemption 2). Cfx.re is owned by Rockstar Games. The forum is [forum.cfx.re](https://forum.cfx.re), the docs are [docs.fivem.net](https://docs.fivem.net/docs/). |
| **FiveM client** | What players install. It launches their own copy of GTA V and connects to servers. |
| **FXServer** | The server program you run. Also called the "Cfx platform server". On Windows it is `FXServer.exe`, on Linux you start it through `run.sh`. |
| **Server artifacts** | The FXServer builds you download. Each build has a number, for example `2xxxx`. See [Updating artifacts safely](/docs/server-setup/updating-artifacts) and our [Artifacts page](/artifacts). |
| **txAdmin** | The web panel and in-game admin menu that ships inside FXServer. It deploys servers from recipes, restarts them, bans players and more. |
| **Cfx.re Portal** | [portal.cfx.re](https://portal.cfx.re), where you create the free server license key that every server needs. |
| **Resources** | Folders of scripts and assets that FXServer loads. Everything a server does beyond vanilla GTA is a resource. |
| **Frameworks** | Big sets of resources that add players, jobs, money and inventories, for example QBCore, Qbox and ESX Legacy. See [Frameworks](/docs/frameworks). |
> [!NOTE]
> In July 2026 Cfx.re opened early access for **FiveM for GTA V Enhanced**, which runs on the newer Enhanced edition of the game with a separate server build called **Cfx Server**. The classic FiveM, now called **Legacy**, keeps running and is still what almost every server and resource targets. These docs cover Legacy FXServer unless a page says otherwise. See [FiveM Legacy and Enhanced](/docs/server-setup#fivem-legacy-and-fivem-for-gta-v-enhanced) for what changes.
## How it fits together
When you start a server, this is what happens:
1. You run FXServer. With no arguments it starts **txAdmin**, which opens a web panel on port `40120`.
2. txAdmin (or you, by hand) starts FXServer with a `server.cfg`. That file sets the server name, the license key, player slots, endpoints and which resources to start.
3. FXServer reads the `resources` folder, loads every resource you `ensure`, and runs their **server scripts**.
4. A player connects on port `30120`. Their client downloads the **client scripts**, NUI pages and streamed assets (models, textures, maps) of your resources, then joins.
5. Client scripts and server scripts talk to each other with **events**, and to the game through **natives**.
```text title="A typical server folder after a txAdmin deploy"
FXServer/
├─ server/ the artifact: FXServer.exe (Windows) or run.sh + alpine/ (Linux)
└─ txData/
├─ admins.json txAdmin accounts
└─ MyServer.base/ your server data folder (any name you pick in the deployer)
├─ server.cfg
└─ resources/
├─ [cfx-default]/ mapmanager, spawnmanager, chat...
└─ [local]/ your own resources
```
## A learning path through these docs
Follow the sections in this order. Each page links to the next one.
### 1. Understand what you need
- [Glossary](/docs/getting-started/glossary): every term you will meet, in one place.
- [Requirements](/docs/getting-started/requirements): hardware, Windows or Linux, and the legal basics (license, Rockstar content, monetisation).
### 2. Get a server online
- [Server setup overview](/docs/server-setup), then [Windows](/docs/server-setup/windows) or [Linux](/docs/server-setup/linux).
- [server.cfg explained](/docs/server-setup/server-cfg) line by line. You can also build one with the [server.cfg Generator](/tools/server-cfg-generator).
- [Ports and networking](/docs/server-setup/ports-and-networking) and [Database setup](/docs/server-setup/database) if you plan to run a framework.
- [Common errors and fixes](/docs/server-setup/common-errors) and [Security basics](/docs/server-setup/security).
### 3. Run it day to day with txAdmin
- [txAdmin overview](/docs/txadmin), [first setup and the deployer](/docs/txadmin/first-setup), [recipes](/docs/txadmin/recipes), [everyday admin](/docs/txadmin/everyday-admin) and the [Discord bot](/docs/txadmin/discord-bot).
### 4. Add content
- [Installing resources](/docs/resources), [recommended open source resources](/docs/resources/recommended), [maps, MLOs and clothing](/docs/resources/maps-mlos-clothing) and [vehicle packs](/docs/resources/vehicle-packs).
- Pick a framework, or none: [Frameworks compared](/docs/frameworks).
### 5. Write your own scripts
- [Development overview](/docs/development) (tools and setup), then [Your first resource](/docs/development/first-resource).
- [Client, server and events](/docs/development/client-server-events), [natives](/docs/development/natives), [state bags and OneSync](/docs/development/state-bags-onesync), [NUI](/docs/development/nui).
- [Threads and performance](/docs/development/threads-performance), [exports and dependencies](/docs/development/exports-dependencies), [debugging](/docs/development/debugging).
- [Streaming custom assets](/docs/development/streaming-assets) and [publishing a resource](/docs/development/publishing).
### 6. Watch instead of read
The [video tutorial archive](/docs/videos) groups hand-picked YouTube tutorials into courses: running your first server, txAdmin, frameworks, Lua scripting, NUI, streaming assets, CodeWalker and Blender with Sollumz.
## Where to get help
- **Official docs**: [docs.fivem.net](https://docs.fivem.net/docs/) for server setup, the scripting manual and the [natives reference](https://docs.fivem.net/natives/).
- **Forum**: [forum.cfx.re](https://forum.cfx.re) has Server Discussion, Development and Releases categories. Search before you post, most errors have been seen before.
- **Framework communities**: QBCore, Qbox, ESX and Overextended each run their own Discord and docs, linked from the [frameworks pages](/docs/frameworks).
- **txAdmin**: the [txAdmin Discord](https://discord.gg/txAdmin) and the docs folder in the [txAdmin repository](https://github.com/citizenfx/txAdmin/tree/master/docs).
> [!TIP]
> When you ask for help, paste the exact error from the server console or the F8 client console, your artifact build number and your `server.cfg` (with the license key and database password removed). That answers half the questions people will ask you.
_Last updated: 2026-09-22_
---
## FiveM glossary
URL: https://fivemad.com/docs/getting-started/glossary
Plain definitions of the FiveM terms you will meet: resources, artifacts, OneSync, natives, state bags, NUI, ymap, ytyp, ydr, yft, ytd, streaming, convars, ACE.
FiveM has its own vocabulary, and GTA V adds a second one for its file formats. This page explains each term in a sentence or two and points to the page that goes deeper. Terms are grouped by topic, not alphabetically, so related ideas sit together.
## Platform and server
**Cfx.re**: The company and platform behind FiveM and RedM, owned by Rockstar Games. "Cfx" shows up in the forum (`forum.cfx.re`), the portal (`portal.cfx.re`) and join links (`cfx.re/join/abc123`).
**FXServer**: The dedicated server program. You download it as an **artifact** and run `FXServer.exe` on Windows or `run.sh` on Linux.
**Artifact**: One numbered build of FXServer, published at `runtime.fivem.net/artifacts`. There is a *recommended* build and a *latest* build. Some builds are known to be broken, so check our [Artifacts page](/artifacts) before you update. More in [Updating artifacts safely](/docs/server-setup/updating-artifacts).
**Legacy and Enhanced**: Since July 2026 there are two FiveM platforms. **Legacy** is the classic FiveM on the original PC version of GTA V and uses FXServer. **FiveM for GTA V Enhanced** runs on the Enhanced edition and uses a separate server build called **Cfx Server**. They are separate: a Legacy client cannot join an Enhanced server.
**txAdmin**: The web panel and in-game menu built into FXServer. It deploys servers from **recipes**, restarts on crash, schedules restarts, bans and warns players and runs a Discord bot. See [txAdmin](/docs/txadmin).
**Recipe**: A YAML file that tells the txAdmin deployer how to build a server: which repositories to download, which files to move, which SQL to run. See [Recipes explained](/docs/txadmin/recipes).
**License key**: The free key from [portal.cfx.re](https://portal.cfx.re) that every server must set with `sv_licenseKey`. Keys look like `cfxk_...`.
**server.cfg**: The config file FXServer executes on start. It is a list of console commands and convars. See [server.cfg explained](/docs/server-setup/server-cfg).
**Convar**: A console variable, like `sv_hostname` or `sv_maxclients`. You set it with `set`, `sets` (also shows in the server list info) or `setr` (also replicated to clients so client scripts can read it).
**Endpoint**: The IP and port FXServer listens on, set with `endpoint_add_tcp` and `endpoint_add_udp`. The default is `0.0.0.0:30120`.
**Game build**: The GTA V update your server asks clients to run, set with `sv_enforceGameBuild` (for example `3751`). Newer builds unlock newer DLC vehicles, clothes and maps.
**Pure mode**: `sv_pureLevel` blocks modified client game files. Level 1 still allows audio files and known graphics mods, level 2 blocks all modified files.
**OneSync**: FiveM's server side sync system. With `onesync on` the server knows about every entity and player and decides who gets what, which allows more than 32 players and server side entity control. Without a Cfx.re subscription the slot limit is 48. Up to 2048 slots are possible with OneSync and the right tier.
**Routing bucket**: A separate "dimension" on a OneSync server. Players and entities in different buckets cannot see each other. Used for instanced interiors, character selection and races.
**Entity lockdown**: `sv_entityLockdown` stops clients from creating networked entities themselves, which blocks a common cheat. Modes are `inactive`, `relaxed` and `strict`.
## Resources and scripting
**Resource**: A folder with an `fxmanifest.lua` file. It can contain Lua, JavaScript or C# scripts, a web UI, streamed assets and data files. You start it with `ensure name` where `name` is the folder name.
**fxmanifest.lua**: The resource manifest. It declares `fx_version`, `game`, which scripts run on the client or server, which files to send to clients, `data_file` entries and dependencies. Generate one with the [fxmanifest Generator](/tools/fxmanifest-generator).
**Category folder**: A folder in brackets, like `[local]` or `[qb]`. It only groups resources, it is not a resource itself. `ensure [qb]` starts every resource inside it.
**Client script / server script / shared script**: Client scripts run on each player's game. Server scripts run once, in FXServer. Shared scripts run on both. See [Client, server and events](/docs/development/client-server-events).
**Event**: A named message. `TriggerEvent` fires one on the same side, `TriggerServerEvent` sends one from a client to the server, `TriggerClientEvent` sends one from the server to one or all clients. Network events must be registered with `RegisterNetEvent`.
**Callback**: A request that expects an answer, for example "server, how much money does this player have?". FiveM has no built in callback between client and server, so libraries like `ox_lib` (`lib.callback`) and the frameworks provide one on top of events.
**Native**: A function of the GTA V engine or of FiveM itself, like `GetEntityCoords` or `SetPedIntoVehicle`. There are thousands, listed at [docs.fivem.net/natives](https://docs.fivem.net/natives/). See [Natives](/docs/development/natives).
**Hash / joaat**: GTA identifies models, weapons and many other things by a 32 bit hash of their name, computed with Jenkins one-at-a-time (joaat). `GetHashKey('adder')` or `` `adder` `` in FiveM Lua gives you the number. Try the [joaat Hash Calculator](/tools/hash-calculator).
**Export**: A function one resource makes callable from other resources, like `exports.ox_inventory:AddItem(...)`. See [Exports and dependencies](/docs/development/exports-dependencies).
**State bag**: A key/value store attached to the server (`GlobalState`), a player (`Player(src).state`) or an entity (`Entity(ent).state`) that FiveM syncs for you. See [State bags and OneSync](/docs/development/state-bags-onesync).
**NUI**: "New UI", FiveM's embedded Chromium browser. It lets you build HUDs, menus and phones in HTML, CSS and JavaScript (React, Vue, Svelte and so on). See [NUI basics](/docs/development/nui).
**DUI**: Direct-rendered UI. A web page drawn onto a texture in the world, like a TV screen or a billboard.
**KVP**: Key value pairs, a small built in storage (`SetResourceKvp`, `GetResourceKvpString`) on the client or server. Good for settings, not for large data.
**Tick / thread**: A Lua loop created with `CreateThread` that runs every frame or every `Wait(ms)`. Code that runs every frame costs performance. See [Threads and performance](/docs/development/threads-performance).
**resmon**: The resource monitor. Type `resmon` in the F8 console to see how much CPU time and memory each client resource uses.
**Profiler**: The built in FiveM profiler (`profiler record`, `profiler saveJSON`) that records exactly which resource and function uses time. Read its output with the [Profiler Analyzer](/tools/profiler-analyzer).
**Framework**: A shared base for roleplay style servers: player data, characters, jobs, money, items. QBCore, Qbox, ESX Legacy, ox_core and ND_Core are the common ones. See [Frameworks](/docs/frameworks).
**Asset escrow**: Cfx.re's system that encrypts paid resources sold on Tebex so they only run on the buyer's license key. See [Publishing a resource](/docs/development/publishing).
## Permissions
**ACE**: Access Control Entry. A rule like `add_ace group.admin command allow` that allows or denies an **object** (for example `command.ban`) for a **principal**.
**Principal**: Who a rule applies to: a group (`group.admin`), an identifier (`identifier.fivem:123456`, `identifier.license:abc...`, `identifier.discord:...`) or a resource (`resource.myresource`). `add_principal child parent` makes one principal inherit another.
**Identifier**: A player ID that FXServer receives on connect: `license:` (Rockstar license), `fivem:` (Cfx.re account), `discord:`, `steam:` (needs a Steam Web API key), `xbl:`, `live:` and `ip:`.
## GTA V file formats
**RPF**: Rockstar's archive format. Singleplayer mods ship as `dlc.rpf`. FiveM does not load RPFs from resources, you extract their contents into a `stream` folder and meta files instead.
**Streaming**: Loading assets into the game as they are needed. In FiveM, any supported file in a resource's `stream` folder is sent to clients and registered with the game automatically.
**YDR**: A single drawable model (props, simple objects).
**YDD**: A drawable dictionary, several drawables in one file. Used for clothing and ped parts.
**YFT**: A fragment model, a model that can break or has moving parts. Vehicles are `.yft` files (plus a `_hi.yft` high detail version).
**YTD**: A texture dictionary. Holds the textures for a model. Oversized YTDs are the most common cause of texture loss on busy servers. Shrink them with the [YTD Optimizer](/tools/ytd-optimizer).
**YBN**: Static collision (bounds). Without it players fall through your map.
**YMAP**: A map placement file. It lists which objects (entities) are placed where, with rotation and LOD distance. Build one with the [YMAP Builder](/tools/ymap-builder) or in CodeWalker.
**YTYP**: An archetype definition file. It tells the game about new model names, their bounding boxes and LOD distances, and defines MLO interiors. Create one with the [YTYP Creator](/tools/ytyp-creator).
**MLO**: "Map Loaded Object", an interior with rooms and portals, defined in a `.ytyp` and placed by a `.ymap`. Custom shops, police stations and houses are usually MLOs.
**YMT**: A binary metadata file. For clothing, the ped variation `.ymt` lists how many drawables and textures each component has. Generate one with the [YMT Creator](/tools/ymt-creator).
**YNV / YND**: Navmesh and path nodes. They tell peds and traffic where they can walk and drive.
**.meta files**: XML data files the game reads, like `vehicles.meta`, `handling.meta`, `carcols.meta`, `carvariations.meta` and `weapons.meta`. You register them in the manifest with `data_file`.
**AWC / dat54.rel**: Audio: `.awc` holds the sound data, `dat54.rel` (and friends) define how the game plays it. The [Native Audio Builder](/tools/native-audio-builder) turns WAV, MP3 or OGG files into this format.
**CodeWalker**: The free community tool for browsing the GTA V world and editing YMAPs, YTYPs and many other formats. Get it from [github.com/dexyfex/CodeWalker](https://github.com/dexyfex/CodeWalker).
**Sollumz**: The free Blender add-on for importing and exporting GTA V models (YDR, YDD, YFT, YBN) as CodeWalker XML. Get it from [github.com/Sollumz/Sollumz](https://github.com/Sollumz/Sollumz).
**LOD**: Level of detail. Models have simpler versions for far away views, and the game switches between them by distance.
_Last updated: 2026-09-22_
---
## Requirements: hardware, OS and the rules
URL: https://fivemad.com/docs/getting-started/requirements
What you need to run a FiveM server: realistic hardware sizing, Windows or Linux, network, and the legal basics of the Cfx.re license, Rockstar content and Tebex.
Before you rent a machine or promise a community a launch date, check three things: the hardware you need for the kind of server you want, the operating system you are comfortable with, and the rules you agree to when you run a FiveM server.
## What you need no matter what
- **A legal copy of GTA V** on the PC you play from. The server itself does not need GTA V installed.
- **A Cfx.re account** and a free **server license key** from [portal.cfx.re](https://portal.cfx.re). One key per server.
- **A machine that stays online**: your own PC for testing, or a VPS or dedicated server for a public server.
- **Open ports**: `30120` TCP and UDP for players, and `40120` TCP for the txAdmin web panel (keep that one private if you can). See [Ports and networking](/docs/server-setup/ports-and-networking).
- **MariaDB** if you plan to run a framework like QBCore, Qbox or ESX. A plain server with vMenu does not need a database. See [Database setup](/docs/server-setup/database).
## Hardware sizing
Cfx.re does not publish official hardware requirements, and the real load depends far more on your resources than on your player count. A server with 40 well written scripts behaves very differently from one with 300 leaked ones. Use the table below as a starting point, then measure with txAdmin's performance chart and the [profiler](/docs/development/threads-performance).
| Server type | CPU | RAM | Storage | Notes |
| --- | --- | --- | --- | --- |
| Local test server on your PC | Any modern 4 core | 4 GB free | 10 GB | Fine for development. Run the game and the server on the same machine. |
| Small public server, up to ~48 players, light scripts | 2 to 4 fast cores | 4 to 8 GB | 30 to 60 GB SSD | vMenu or a light framework, a few car packs. |
| Roleplay server, 48 to 128 players, full framework | 4+ cores with high single core speed | 8 to 16 GB | 60 to 120 GB NVMe | MariaDB on the same machine is common at this size. |
| Large server, 128+ players, heavy streaming | 6 to 8+ high clock cores | 16 to 32 GB | NVMe, plus a CDN or separate file server for assets | Needs a paid Cfx.re tier for the slots, and careful script work. |
A few things matter more than raw numbers:
- **Single core speed.** The main server thread runs on one core. A high clock CPU beats a many core, low clock one.
- **Upload bandwidth.** Every joining player downloads all your streamed assets. A 2 GB car pack times 50 players joining after a restart is 100 GB of upload. Keep packs lean, shrink textures with the [YTD Optimizer](/tools/ytd-optimizer), and consider a file server or CDN for big servers.
- **Disk speed.** MariaDB and txAdmin logs like fast disks. Avoid spinning disks.
- **Clean IP.** Some hosting IP ranges are blocked on the Cfx.re platform. Check a VPS IP with the [Cfx Blacklist Checker](/tools/cfx-blacklist-checker) before you pay for a year.
> [!IMPORTANT]
> The free slot limit is **48 players**. Going above 48 needs a Cfx.re Element Club tier (Argentum or higher), bought on the Cfx.re Portal. Setting `sv_maxclients 64` without it does not work.
## Windows or Linux
Both are fully supported by FXServer and txAdmin.
| | Windows | Linux |
| --- | --- | --- |
| Setup | Download `server.7z`, extract, double click `FXServer.exe`. | Download `fx.tar.xz`, extract, run `bash run.sh`. Needs basic shell skills. |
| Cost | Windows Server licenses make VPS plans pricier. | Usually cheaper for the same hardware. |
| Tools | HeidiSQL, CodeWalker and Windows only tools run on the same box. | Everything is done over SSH. Run the game tools on your own PC. |
| Running as a service | Scheduled task or a service wrapper. | `systemd`, `screen` or `tmux`. |
| C# resources | Supported. | Supported. |
If you have never used a Linux shell, start on Windows (even your own PC) and move to Linux later. Your resources and `server.cfg` work the same on both, just watch out for **case sensitive file names** on Linux: `ensure MyResource` will not find a folder called `myresource`.
> [!TIP]
> Develop on a local Windows server, deploy to a Linux VPS. Keep the whole server folder in git so moving between them is a `git pull`. See [Security basics](/docs/server-setup/security) for what never to commit.
## Game server providers vs your own VPS
Game server providers (GSPs) give you a panel with FXServer and txAdmin preinstalled. That is the fastest way to get online, and many of them can host MariaDB for you. A VPS or dedicated server gives you full control and usually more hardware for the money, but you handle updates, backups and security yourself. These docs work for both: txAdmin looks the same everywhere.
## The rules you agree to
Running a FiveM server means agreeing to the **Cfx.re Platform License Agreement** (the "terms", at [fivem.net/terms](https://fivem.net/terms)). It has been updated several times, including a new Creator Platform License Agreement that took effect on 12 January 2026, so read the current version yourself. This section is a plain summary, not legal advice.
### What the platform allows
- Running a server with your own game mode, scripts, maps and vehicles.
- Making and sharing resources, free or paid.
- Accepting money from players, but only through **Tebex**, Cfx.re's authorised commerce partner, and only for things the terms allow.
### What gets servers and creators in trouble
Commonly cited points from the current agreement and Cfx.re's guidance:
- **Selling Rockstar's content.** You cannot sell access to GTA V assets, vehicles, clothing or maps that Rockstar made, or charge for things that are just the base game.
- **Loot boxes and gambling.** Chance based purchases and real money gambling mechanics are not allowed.
- **Selling in-game currency** or anything that can be converted back into real money.
- **Using other people's IP.** Real world brands, logos, copyrighted cars and characters. "Everyone else does it" is not a defence when a takedown arrives.
- **Leaked resources.** Running or sharing leaked paid scripts is a licence violation, can get your server delisted, and leaked code is a common place to hide backdoors.
- **Hosting other people's servers commercially** without authorisation. Only authorised game server providers may do that.
### Tebex and asset escrow
- **Tebex** is the store you connect on the Cfx.re Portal. Players buy packages, and Tebex can run commands on your server to deliver them.
- **Asset escrow** is how paid resources are protected. When a creator sells a resource on Tebex with escrow, the files are encrypted and only run for the buyer's Cfx.re account. As a buyer you download them from the assets section of the Cfx.re Portal, logged in with the account that bought them. Escrowed resources usually leave a `config.lua` and a few "open" files readable so you can configure them.
- If you sell your own work, see [Publishing a resource](/docs/development/publishing).
> [!CAUTION]
> If a "free" copy of a paid script shows up on a random Discord, it is leaked. Beyond the licence issue, leaked resources are one of the most common ways servers get backdoored (remote code that gives someone else admin, or drains your Tebex). Don't run them.
## Checklist before you start
- [ ] GTA V installed and FiveM working on your PC.
- [ ] Cfx.re account created, license key generated on the Portal.
- [ ] Machine chosen (local PC, VPS or GSP) and its IP checked with the [Cfx Blacklist Checker](/tools/cfx-blacklist-checker).
- [ ] Ports `30120` TCP/UDP reachable, `40120` reachable at least from your own IP.
- [ ] MariaDB installed if you want a framework.
- [ ] A text editor (VS Code) and git.
Next: [Server setup overview](/docs/server-setup).
_Last updated: 2026-09-22_
---
# Server setup
## Server setup overview
URL: https://fivemad.com/docs/server-setup
The ways to set up a FiveM server (txAdmin, vanilla, hosting provider), what you download, the folder layout, and the difference between Legacy and Enhanced.
Setting up a FiveM server comes down to four steps: get a license key, download a server build (an **artifact**), run it, and give it a `server.cfg` with resources to start. txAdmin, which ships inside every build, does most of this for you.
## Pick a setup method
The official docs list four ways. They all end up with the same FXServer running the same resources.
| Method | Best for | Guide |
| --- | --- | --- |
| **txAdmin on Windows** | First server, local development, Windows VPS | [Windows setup](/docs/server-setup/windows) |
| **txAdmin on Linux** | VPS and dedicated servers, cheaper hosting | [Linux setup](/docs/server-setup/linux) |
| **Vanilla (no txAdmin)** | Minimal dev servers, containers, people who want full control | Covered at the end of both guides |
| **Game server provider** | People who don't want to manage a machine | Your provider's panel, then the [txAdmin](/docs/txadmin) pages |
We recommend txAdmin for almost everyone. It is maintained by Cfx.re, restarts the server when it crashes, schedules restarts, and its deployer can install QBCore, Qbox or ESX from a recipe in a few minutes.
## Before you start
1. **Create a license key.** Log in at [portal.cfx.re](https://portal.cfx.re), open the server registration keys page (the dashboard has a "Create a Key" quick link), click **Generate Key**, give it a display name and copy the key. It starts with `cfxk_`. Store it somewhere safe, you will paste it into txAdmin or `server.cfg`.
2. **Pick an artifact.** Download the **recommended** build from the official [server download page](https://docs.fivem.net/docs/server-download/) or `runtime.fivem.net/artifacts`. Our [Artifacts page](/artifacts) shows the recommended build and flags builds known to be broken.
3. **Decide where the server lives.** Your PC is fine for testing. For a public server read [Requirements](/docs/getting-started/requirements) first.
4. **Install MariaDB** if you will run a framework. See [Database setup](/docs/server-setup/database).
## What you download
| Platform | File | What is inside |
| --- | --- | --- |
| Windows | `server.7z` | `FXServer.exe`, `citizen/` (scripting runtimes, txAdmin, system resources) and DLLs |
| Linux | `fx.tar.xz` | `run.sh` and an `alpine/` folder with the server and its own libraries |
The artifact is the program. Your **server data** (the `server.cfg` and the `resources` folder) lives somewhere else. Keeping them apart is what makes updating easy: you swap the artifact folder and your data stays untouched.
```text title="Recommended layout"
C:\FXServer\
├─ server\ artifact, replace this folder when you update
└─ txData\ created by txAdmin on first start
├─ admins.json
├─ default\ txAdmin's own data (config, player database, logs)
└─ QBCore_A1B2C3.base\ your server data folder: server.cfg + resources\
(the deployer suggests a name like this, you can pick any)
```
On Linux the same idea applies, usually under `/home/fivem/` or `/opt/fivem/`.
## How txAdmin and FXServer start
- Run FXServer **without** `+exec server.cfg` and it starts **txAdmin** on port `40120`. txAdmin then starts FXServer for you with your config. This is the normal way.
- Run FXServer **with** `+exec server.cfg` from inside your server data folder and it starts directly, with no txAdmin. This is the "vanilla" way.
Both guides cover both ways.
## FiveM Legacy and FiveM for GTA V Enhanced
In March 2026 Cfx.re announced FiveM for the Enhanced edition of GTA V, and early access for server owners opened on **21 July 2026**. What you need to know as a server owner:
- It is a **separate platform**. The client is separate, and the server is a separate program called **Cfx Server** with its own download on the [server download page](https://docs.fivem.net/docs/server-download/) (files are named `cfx-server.exe` on Windows). Legacy and Enhanced players cannot join each other's servers, so moving is a decision for your whole community.
- Legacy is **not going away**. Upgrading is optional and Legacy support continues.
- Cfx.re's [What's changed](https://docs.fivem.net/docs/developers/legacy-vs-enhanced/) page lists the breaking changes. The big ones: Mono is replaced by .NET 10 for C# resources, pure mode is always on, OneSync is always the full mode (no "legacy" or P2P mode), only the latest game build is supported, KVP files must be migrated, asset escrow was not yet available at launch, and dev tools need `sv_devMode true`.
- Existing streamed assets may need converting with Cfx.re's **Alchemist** tool.
- txAdmin has a separate "FiveM Basic Server (Enhanced)" recipe.
The rest of these docs describe **Legacy FXServer**, which is what almost all resources, frameworks and tutorials target today. Where Enhanced differs in a way that bites, the page says so.
[FiveM Enhanced: Everything That Changed For Server Owners (TraseDev)](https://www.youtube.com/watch?v=WOgYKmAqptg) (YouTube video)
## The pages in this section
1. [Windows setup](/docs/server-setup/windows): step by step with txAdmin, plus vanilla.
2. [Linux setup](/docs/server-setup/linux): Ubuntu or Debian, systemd service, firewall.
3. [server.cfg explained](/docs/server-setup/server-cfg): every common line and what it does.
4. [Updating artifacts safely](/docs/server-setup/updating-artifacts): how to update without breaking things.
5. [Ports and networking](/docs/server-setup/ports-and-networking): port forwarding, server list, proxies.
6. [Database setup](/docs/server-setup/database): MariaDB, HeidiSQL and oxmysql.
7. [Common errors and fixes](/docs/server-setup/common-errors): the errors everyone hits, and the fix.
8. [Security basics](/docs/server-setup/security): ACE, txAdmin accounts, the database, secrets.
> [!TIP]
> Want a ready config instead of writing one? The [server.cfg Generator](/tools/server-cfg-generator) builds a full `server.cfg` with hostname, slots, OneSync, endpoints, tags, resources and ACE permissions.
_Last updated: 2026-09-22_
---
## Set up a FiveM server on Windows
URL: https://fivemad.com/docs/server-setup/windows
Step by step: download the FXServer artifact, extract it, run txAdmin, link your Cfx.re account, deploy a recipe with your license key, and connect. Plus the vanilla way.
This guide sets up a FiveM server on Windows 10, 11 or Windows Server with txAdmin. It works the same on your own PC (for development) and on a Windows VPS. Plan about 15 minutes.
[How to Make a FiveM Server in 2026! (HighwayTrooper)](https://www.youtube.com/watch?v=NjVwsBinE10) (YouTube video)
## What you need
- A Cfx.re account and a **license key** from [portal.cfx.re](https://portal.cfx.re) (see [Server setup overview](/docs/server-setup#before-you-start)).
- [7-Zip](https://www.7-zip.org/) or WinRAR to open `.7z` files.
- **Git for Windows** is optional but useful later.
- **MariaDB** only if you want a framework (QBCore, Qbox, ESX). Install it first, see [Database setup](/docs/server-setup/database).
## 1. Create the folders
Make a folder with a short path and no spaces, for example:
```text
C:\FXServer\server
```
Short paths avoid problems with long resource paths and some tools. Don't put the server in `Program Files`, `Downloads` or a OneDrive synced folder.
## 2. Download the artifact
1. Open the official [server download page](https://docs.fivem.net/docs/server-download/) (or `https://runtime.fivem.net/artifacts/fivem/build_server_windows/master/`).
2. Pick **FiveM / RedM**, **Windows**, **Recommended** and download `server.7z`.
3. Check the build number against our [Artifacts page](/artifacts), which flags builds with known problems.
> [!NOTE]
> The Enhanced platform (Cfx Server) is a different download on the same page. Pick the FiveM / RedM (Legacy) build unless you know you want Enhanced. See [Legacy and Enhanced](/docs/server-setup#fivem-legacy-and-fivem-for-gta-v-enhanced).
## 3. Extract it
Open `server.7z` with 7-Zip and extract everything into `C:\FXServer\server`. You should now have `C:\FXServer\server\FXServer.exe` and a `citizen` folder next to it.
> [!TIP]
> Windows Defender scanning every file makes FXServer start slowly. The official FAQ suggests excluding the folder: open PowerShell as administrator and run `Add-MpPreference -ExclusionPath 'C:\FXServer\'`.
## 4. Start txAdmin
Double click `FXServer.exe`. A console window opens and, because you did not pass `+exec server.cfg`, FXServer starts **txAdmin**. It creates `C:\FXServer\txData` and opens `http://localhost:40120` in your browser. The console also prints a 4 digit **PIN**.
If the browser does not open, go to `http://localhost:40120` yourself. On a VPS, use `http://YOUR_VPS_IP:40120` from your own PC (and open TCP 40120 in the Windows firewall, ideally only for your IP).
## 5. Link your account
1. Check that the PIN is filled in and click **Link Account**.
2. Log in with your Cfx.re (forum) account and click **Yes, Allow**.
3. Create a **backup password**. You will use it if Cfx.re login is ever down, so save it in a password manager.
This makes you the **master admin** of this txAdmin.
## 6. Run the setup and deployer
1. Enter a **server name** and click **Next**.
2. Choose **Popular Recipes**.
3. Pick a recipe:
- **FiveM Basic Server (Legacy)**, sometimes shown as CFX Default: a clean, framework free server. Best for learning and for vMenu servers.
- **QBCore**, **Qbox** or **ESX Legacy**: full roleplay frameworks. These need MariaDB running. See [Popular recipes](/docs/txadmin/popular-recipes).
4. Confirm the **data location** (the default `txData\.base` is fine) and click **Save**.
5. The **Recipe Deployer** shows the recipe YAML. Click **Next**.
6. Paste your **license key**. For framework recipes, fill in the **database** host (`localhost`), port (`3306`), user (`root`) and password. Leave the database name empty and txAdmin generates one.
7. Click **Run Recipe**. txAdmin downloads the resources and, for frameworks, imports the SQL. This takes a minute or two.
8. Review the generated `server.cfg` and click **Save & Run Server**.
The live console in txAdmin now shows the server starting. When you see resources starting and no red errors, it is up.
> [!IMPORTANT]
> QBCore and some other recipes install NPM packages with yarn on first start. Let that finish before you restart. The QBCore docs say this explicitly.
## 7. Connect
1. Start FiveM.
2. Press F8 to open the client console.
3. Type `connect localhost:30120` (same PC) or `connect YOUR_PUBLIC_IP:30120` and press Enter.
You can also use the direct connect box in the FiveM main menu with the same address. To let friends connect, see [Ports and networking](/docs/server-setup/ports-and-networking).
## 8. Make it start on its own
txAdmin restarts FXServer on crashes, but not the whole machine. On a VPS, start FXServer when Windows boots:
1. Create `C:\FXServer\start.bat`:
```bat title="C:\FXServer\start.bat"
@echo off
cd /d C:\FXServer\server
FXServer.exe
```
2. Open **Task Scheduler**, create a task that runs `start.bat` **At startup**, "Run whether user is logged on or not", with the account that owns the folder.
3. In txAdmin, **Settings > FXServer**, turn on starting the server automatically when txAdmin starts.
## Folder layout after setup
```text
C:\FXServer\
├─ server\ FXServer.exe + citizen\ (replace to update)
├─ start.bat
└─ txData\
├─ admins.json txAdmin accounts
├─ default\ txAdmin config, logs, player database
└─ MyServer.base\
├─ server.cfg
└─ resources\
```
Your own resources go in `resources\[local]\` and get an `ensure` line in `server.cfg`. See [Installing resources](/docs/resources).
## The vanilla way (no txAdmin)
Useful for a throwaway dev server or when you want to see exactly what runs. From the official vanilla guide:
```bat
cd /d C:\FXServer
git clone https://github.com/citizenfx/cfx-server-data.git server-data
```
Create `C:\FXServer\server-data\server.cfg`:
```cfg title="server-data/server.cfg"
endpoint_add_tcp "0.0.0.0:30120"
endpoint_add_udp "0.0.0.0:30120"
ensure mapmanager
ensure chat
ensure spawnmanager
ensure sessionmanager
ensure basic-gamemode
ensure hardcap
sv_hostname "My dev server"
sv_maxclients 8
sv_licenseKey "cfxk_your_key_here"
sv_enforceGameBuild 3751
set onesync on
```
Then start it from inside the data folder:
```bat
cd /d C:\FXServer\server-data
C:\FXServer\server\FXServer.exe +exec server.cfg
```
> [!WARNING]
> Always start FXServer from inside the server data folder (or tell txAdmin where it is). If you start it from somewhere else, it cannot find `resources` and you get "no resources found" or "couldn't find resource" errors.
## Next steps
- Read [server.cfg explained](/docs/server-setup/server-cfg) so you know what every line does.
- Set up [txAdmin admins, bans and scheduled restarts](/docs/txadmin/everyday-admin).
- Add [vMenu or other resources](/docs/resources/recommended).
- Write [your first resource](/docs/development/first-resource).
_Last updated: 2026-09-22_
---
## Set up a FiveM server on Linux
URL: https://fivemad.com/docs/server-setup/linux
Run FXServer and txAdmin on Ubuntu or Debian: dependencies, a dedicated user, the Linux artifact, a systemd service or tmux, the ufw firewall and MariaDB.
This guide sets up FXServer with txAdmin on a fresh **Ubuntu 22.04 / 24.04** or **Debian 12** VPS. Other distributions work too, since the Linux artifact ships its own libraries in an `alpine` folder, but the package commands below are for Debian based systems. You need SSH access with a user that can run `sudo`.
[Linux-Ubuntu FiveM Server Install Guide (Enix Hosting)](https://www.youtube.com/watch?v=kz1TozHDa5Q) (YouTube video)
## 1. Update the system and install tools
```bash
sudo apt update && sudo apt upgrade -y
sudo apt install -y xz-utils git curl wget tmux ufw
```
`xz-utils` is required to extract the artifact. `git` is for cloning resources, `tmux` for running the server in a detachable session, `ufw` for the firewall.
## 2. Create a user for the server
Never run a game server as `root`. Create a dedicated user and switch to it:
```bash
sudo adduser --disabled-password --gecos "" fivem
sudo -iu fivem
mkdir -p ~/server
cd ~/server
```
Everything below runs as `fivem` unless it starts with `sudo`.
## 3. Download the Linux artifact
1. Open `https://runtime.fivem.net/artifacts/fivem/build_proot_linux/master/` in your browser.
2. Pick the **recommended** build (check it on our [Artifacts page](/artifacts)) and copy the link to its `fx.tar.xz`.
3. Download and extract it on the server:
```bash
cd ~/server
wget https://runtime.fivem.net/artifacts/fivem/build_proot_linux/master/XXXXX-/fx.tar.xz
tar xf fx.tar.xz
rm fx.tar.xz
ls
# alpine run.sh
```
Replace the URL with the one you copied. The build folder name changes with every release, so don't reuse an old link from a tutorial.
## 4. Open the firewall
Allow SSH first so you don't lock yourself out, then the game ports:
```bash
sudo ufw allow OpenSSH
sudo ufw allow 30120/tcp
sudo ufw allow 30120/udp
# txAdmin web panel: better to allow only your own IP
sudo ufw allow from YOUR_HOME_IP to any port 40120 proto tcp
sudo ufw enable
sudo ufw status
```
If your home IP changes often, you can open 40120 to everyone (`sudo ufw allow 40120/tcp`), but then use a strong password and 2FA on every txAdmin account. See [Security basics](/docs/server-setup/security). Many VPS providers also have a firewall in their web panel: open the same ports there.
## 5. First start with txAdmin
```bash
cd ~/server
bash run.sh
```
FXServer starts txAdmin and prints something like:
```text
[txAdmin] Use the PIN below to register:
[txAdmin] 1234
[txAdmin] http://YOUR_VPS_IP:40120/
```
Open that address in your browser on your own PC and follow the same steps as on Windows: **Link Account** with your Cfx.re login, create a backup password, pick a recipe, paste your license key, run the recipe, then **Save & Run Server**. The full walkthrough is in [First setup and the deployer](/docs/txadmin/first-setup).
On Linux, txAdmin creates `txData` next to `run.sh` by default (`~/server/txData`). You can change it with the `TXHOST_DATA_PATH` environment variable.
Press Ctrl+C to stop it once setup is done. Next we make it run in the background.
## 6. Keep it running
### Option A: tmux (simple)
```bash
tmux new -s fivem
cd ~/server && bash run.sh
```
Detach with Ctrl+B then D. Reattach later with `tmux attach -t fivem`. The server keeps running after you log out, but not after a reboot. `screen` works the same way (`screen -S fivem`, detach with Ctrl+A then D, reattach with `screen -r fivem`).
### Option B: systemd service (starts on boot)
Create the unit file as root:
```ini title="/etc/systemd/system/fivem.service"
[Unit]
Description=FiveM server (txAdmin)
After=network-online.target mariadb.service
Wants=network-online.target
[Service]
Type=simple
User=fivem
Group=fivem
WorkingDirectory=/home/fivem/server
ExecStart=/bin/bash /home/fivem/server/run.sh
Restart=on-failure
RestartSec=10
# Optional txAdmin settings, see the txAdmin env-config docs
# Environment=TXHOST_TXA_PORT=40120
[Install]
WantedBy=multi-user.target
```
Enable and start it:
```bash
sudo systemctl daemon-reload
sudo systemctl enable --now fivem
sudo systemctl status fivem
journalctl -u fivem -f # follow the console output
```
txAdmin still restarts FXServer itself when it crashes. systemd restarts txAdmin if the whole process dies, and starts everything on boot. In txAdmin **Settings > FXServer**, enable starting the server when txAdmin starts, so a reboot brings the game server back without you logging in.
> [!NOTE]
> With systemd you do not have an interactive console. Use txAdmin's **Live Console** page to type server commands.
## 7. MariaDB (for frameworks)
```bash
sudo apt install -y mariadb-server
sudo mariadb-secure-installation
```
Then open the MariaDB shell with `sudo mariadb` and create a database user for FiveM instead of using `root`:
```sql
CREATE USER 'fivem'@'localhost' IDENTIFIED BY 'a-long-random-password';
GRANT ALL PRIVILEGES ON *.* TO 'fivem'@'localhost';
FLUSH PRIVILEGES;
EXIT;
```
`GRANT ALL ON *.*` lets the txAdmin deployer create the database for you. After deploying you can tighten it to the one database (`GRANT ALL ON yourdb.* ...`). Keep MariaDB bound to `127.0.0.1` (the default on Debian and Ubuntu) and never open port 3306 in the firewall. More in [Database setup](/docs/server-setup/database).
## Linux gotchas
- **File names are case sensitive.** `ensure qb-Core` will not find `qb-core`. Stream files referenced in metas must match their exact case too.
- **Line endings.** Scripts edited on Windows work fine, but shell scripts (`.sh`) with Windows line endings fail with `bad interpreter`. Convert with `sed -i 's/\r$//' script.sh`.
- **Permissions.** If you upload files as `root` (for example with SFTP as root), the `fivem` user cannot read them. Fix with `sudo chown -R fivem:fivem /home/fivem/server`.
- **Paths with spaces or brackets.** Quote them in the shell: `cd "resources/[local]"`.
## The vanilla way (no txAdmin)
From the official guide:
```bash
git clone https://github.com/citizenfx/cfx-server-data.git ~/server-data
cd ~/server-data
nano server.cfg # same content as the Windows vanilla example
bash ~/server/run.sh +exec server.cfg
```
You must start it from inside the data folder, with `+exec server.cfg`. See the [Windows guide](/docs/server-setup/windows#the-vanilla-way-no-txadmin) for a minimal `server.cfg`.
## Updating later
Stop the server, move the old `alpine` folder and `run.sh` aside, extract the new `fx.tar.xz` in the same place, start again. Your `txData` is untouched. The full routine, including rollback, is in [Updating artifacts safely](/docs/server-setup/updating-artifacts).
_Last updated: 2026-09-22_
---
## server.cfg explained line by line
URL: https://fivemad.com/docs/server-setup/server-cfg
What every common server.cfg line does: endpoints, hostname, tags, license key, slots, game build, OneSync, ensure order, convars, ACE permissions and splitting configs.
`server.cfg` is not a special format. It is a list of **server console commands** that FXServer runs from top to bottom when it starts, exactly as if you typed them into the console. That explains most of its behaviour: order matters, a typo is an "unknown command", and anything you can type in the console you can put in the file.
> [!TIP]
> Don't want to write it by hand? The [server.cfg Generator](/tools/server-cfg-generator) builds a complete file with hostname, slots, OneSync, endpoints, tags, resources and ACE permissions.
## A complete example
This is a sensible config for a small public server without a framework. The sections below explain each part.
```cfg title="server.cfg"
## Network
endpoint_add_tcp "0.0.0.0:30120"
endpoint_add_udp "0.0.0.0:30120"
## Server list info
sv_hostname "^2My Server ^7| Custom cars | Discord in desc"
sets sv_projectName "My Server"
sets sv_projectDesc "A small freeroam server with custom cars and friendly admins."
sets tags "freeroam, drift, cars"
sets locale "en-US"
load_server_icon myLogo.png
sets banner_detail "https://example.com/banner_detail.png"
sets banner_connecting "https://example.com/banner_connecting.png"
## Core settings
sv_licenseKey "cfxk_xxxxxxxxxxxxxxxxxxxx_xxxxxx"
sv_maxclients 32
sv_enforceGameBuild 3751
set onesync on
sv_endpointPrivacy true
sv_scriptHookAllowed 0
set steam_webApiKey "none"
set resources_useSystemChat true
## Resources (order matters)
ensure mapmanager
ensure chat
ensure spawnmanager
ensure basic-gamemode
ensure hardcap
ensure [local]
## Permissions
add_ace group.admin command allow
add_ace group.admin command.quit deny
add_principal identifier.fivem:123456 group.admin
```
## Network: endpoints
```cfg
endpoint_add_tcp "0.0.0.0:30120"
endpoint_add_udp "0.0.0.0:30120"
```
These bind the server to port `30120` on every network interface, TCP for HTTP (connection info, downloads) and UDP for game traffic. Both lines are needed. Change `30120` to run a second server on the same machine (for example `30121`).
When txAdmin deploys a server, it writes these lines for you (the `{{serverEndpoints}}` placeholder in recipes), and the `TXHOST_FXS_PORT` variable can force a port. See [Ports and networking](/docs/server-setup/ports-and-networking).
## Server list info
| Line | What it does |
| --- | --- |
| `sv_hostname "..."` | The name in the server browser. Supports colour codes like `^1` red, `^2` green, `^7` white. Preview them with [Draw Text Colors](/tools/text-colors). |
| `sets sv_projectName "..."` | Your community's name. Shown in the server browser details. Required for proper listing. |
| `sets sv_projectDesc "..."` | One sentence describing the server. Also required for proper listing. |
| `sets tags "a, b, c"` | Comma separated tags for server browser search. |
| `sets locale "en-US"` | The server's main language. The default recipes use `root-AQ`, which means "not set", so change it. |
| `load_server_icon file.png` | Server icon, a **96x96 PNG** in the server data folder. |
| `sets banner_detail` / `sets banner_connecting` | Image URLs for the server detail page and the connecting screen. |
`set` stores a convar, `sets` also publishes it in the server info (so the server browser can show it), and `setr` replicates it to clients so client scripts can read it with `GetConvar`. Use `setr` for things like `voice_useNativeAudio` that client code needs.
## Core settings
### `sv_licenseKey`
Your key from [portal.cfx.re](https://portal.cfx.re). Without a valid key the server will not start. Never paste it in screenshots or public repos. If it leaks, regenerate it on the Portal.
### `sv_maxclients`
Maximum players, 1 to 2048. Up to **48** is free. Anything above 48 needs a Cfx.re Element Club tier (Argentum or higher) on the account that owns the key.
### `sv_enforceGameBuild`
Forces clients to run a specific GTA V update, which unlocks that update's vehicles, clothing, weapons and map changes. It can only be set at startup. Valid builds for FiveM include:
| Build | DLC |
| --- | --- |
| 2699 | The Criminal Enterprises |
| 2802 | Los Santos Drug Wars |
| 2944 | San Andreas Mercenaries |
| 3095 | The Chop Shop |
| 3258 | Bottom Dollar Bounties |
| 3407 | Agents of Sabotage |
| 3570 | Money Fronts |
| 3751 | A Safehouse in the Hills |
| 3889 | The Kortz Center Heist |
Every build includes everything before it. The txAdmin default recipes currently set `3751`. Pick the build your resources support: some older scripts and MLOs break on the newest build, and players have to download the matching game data the first time they join. You can check a build's content in the [Model & Hash Browser](/tools/model-hash-browser) (vehicles, peds and weapons).
> [!NOTE]
> FiveM for GTA V Enhanced only supports the latest game build, so this setting works differently there.
### `onesync`
```cfg
set onesync on
```
Turns on OneSync, the server side sync. Values are `on`, `legacy` (compatibility mode, not recommended) and `off`. Every current framework needs `on`, and you need it for more than 32 players, routing buckets, server side entity creation and state bags on entities. Use `set onesync on` in the cfg (or `+set onesync on` on the command line). txAdmin also exposes it in its settings.
### Privacy and client mods
| Line | Meaning |
| --- | --- |
| `sv_endpointPrivacy true` | Hides player IP addresses in the public player list output. Turn it on. |
| `sv_scriptHookAllowed 0` | Blocks clients with ScriptHookV (singleplayer mod menus). Default is off, keep it off. |
| `sv_pureLevel 1` | Blocks modified game files except audio and known graphics mods. `2` blocks all modified files. Leave it out to allow anything. |
| `sv_entityLockdown strict` | Clients cannot create networked entities, only the server can. Great against cheaters, but many older scripts spawn things client side and will break. Test first. |
### Steam and chat
- `set steam_webApiKey "none"` disables Steam identifiers. If your scripts need `steam:` identifiers, put a key from [steamcommunity.com/dev/apikey](https://steamcommunity.com/dev/apikey).
- `set resources_useSystemChat true` makes `ensure chat` use the chat resource built into the artifact instead of an old copy in your resources folder. The default txAdmin recipe sets this.
## Resources: `ensure`, `start` and order
```cfg
ensure mapmanager
ensure chat
ensure spawnmanager
ensure [local]
```
- `ensure name` starts a resource, or restarts it if it is already running. It is the one you want in `server.cfg`.
- `start name` starts it only if it is stopped. `stop name` stops it. `restart name` restarts a running one.
- `ensure [folder]` starts every resource inside a bracketed category folder.
- `name` is the **folder name**, not what the manifest says.
**Order matters.** Resources start in the order of the lines. Libraries and databases first, then the framework, then everything that depends on it:
```cfg
ensure oxmysql
ensure ox_lib
ensure qbx_core # or qb-core, es_extended
ensure ox_target
ensure ox_inventory
ensure [qbx]
ensure [standalone]
ensure [local] # your own stuff last
```
If a resource lists `dependencies` in its manifest, FXServer starts those first anyway, but explicit order saves you confusing errors. More in [Installing resources](/docs/resources).
## Splitting the config with `exec`
Big servers split their config. `exec` runs another file:
```cfg
exec permissions.cfg
exec resources.cfg
exec @vMenu/config/permissions.cfg
```
Paths are relative to the server data folder, and `@resource/path` points into a resource. The Qbox recipe, for example, splits settings into `permissions.cfg`, `ox.cfg`, `voice.cfg` and `misc.cfg`.
A common trick is a `secrets.cfg` that holds the license key and database password and is **not** in git:
```cfg title="secrets.cfg"
sv_licenseKey "cfxk_..."
set mysql_connection_string "mysql://fivem:password@localhost/fivem?charset=utf8mb4"
```
```cfg title="server.cfg"
exec secrets.cfg
```
## Database connection
Frameworks use `oxmysql`, which reads one convar:
```cfg
set mysql_connection_string "mysql://user:password@localhost:3306/database?charset=utf8mb4"
```
The key value form `"user=root;password=12345;host=localhost;port=3306;database=fivem"` also works. Avoid special characters like `@ : / ? # & =` in the password. See [Database setup](/docs/server-setup/database).
## Permissions (ACE)
```cfg
add_ace group.admin command allow # admins can run any command
add_ace group.admin command.quit deny # except quit
add_principal identifier.fivem:123456 group.admin
add_principal identifier.discord:111111111111111111 group.admin
```
- `add_ace