FiveM State Bags in Lua: Syncing Data Without Event Spam


Many FiveM scripts still sync shared data the old way: the server fires TriggerClientEvent to everyone whenever something changes, and every client keeps its own copy in a table that slowly drifts out of date. State bags solve most of that. This article covers how they work in Lua, when to use each type, how to react to changes, and the mistakes that cause desync and exploits.
What a state bag actually is
A state bag is a key-value store attached to something the server knows about: a networked entity, a player, or the server as a whole. When a value is set with replication enabled, the new value is sent to clients automatically, including clients that join or stream the entity in later. You stop managing "who needs to know" yourself.
There are three entry points you will use in practice:
- Entity state:
Entity(entity).state, attached to a networked entity such as a vehicle, ped or object. - Player state:
Player(source).stateon the server,LocalPlayer.stateon the client for the local player. - Global state:
GlobalState, one bag shared by the whole server.
The official reference lives in the FiveM state bags documentation. Read it once; the rest of this article focuses on how to use them well.
Choosing the right bag
Picking the wrong bag type is the most common design mistake. A quick rule set:
- Data that belongs to a physical thing in the world (a vehicle is locked, a crate has been looted, a door object is broken) goes in entity state. It lives and dies with the entity.
- Data about a person for the current session (on duty, current job grade shown on a HUD, a temporary status) goes in player state. It is cleared when the player drops.
- Server-wide values everyone needs (a heist cooldown flag, the current event phase, whether a store is open) go in global state.
None of these are persistent. A restart wipes them. If something must survive a restart, the database is the source of truth and the state bag is only a live mirror of it.
Setting values from the server
The safest pattern is: the client asks, the server validates, the server writes the state. Here is a vehicle lock toggle that follows it.
-- server.lua
RegisterNetEvent('myres:toggleLock', function(netId)
local src = source
local veh = NetworkGetEntityFromNetworkId(netId)
if veh == 0 or not DoesEntityExist(veh) then return end
local ped = GetPlayerPed(src)
if #(GetEntityCoords(ped) - GetEntityCoords(veh)) > 10.0 then return end
-- add your own ownership / key check here
local state = Entity(veh).state
state:set('locked', not state.locked, true)
end)The third argument to set is the replicate flag. With true, clients receive the value. With false, it stays on the server, which is useful for internal bookkeeping you do not want players to read, such as who spawned the entity or an anti-abuse counter.
Player and global state work the same way:
-- server.lua
Player(src).state:set('onDuty', true, true)
GlobalState.bankCooldown = trueAssigning directly to a key, as in the GlobalState line, replicates by default. Using set makes the intent explicit, which is easier to review later.
Reading and reacting on the client
Reading is a plain table lookup: Entity(veh).state.locked or LocalPlayer.state.onDuty. That is fine for one-off checks, for example when the player presses a key.
For anything that should apply the moment a value changes, register a change handler instead of polling in a loop:
-- client.lua
AddStateBagChangeHandler('locked', nil, function(bagName, key, value)
local veh = GetEntityFromStateBagName(bagName)
if veh == 0 then return end
SetVehicleDoorsLocked(veh, value and 2 or 1)
end)The first argument filters by key, the second by bag name. Passing nil for the bag means "any bag", so this one handler covers every vehicle on the server. That is far cheaper than a thread that loops through nearby vehicles every frame checking a table.
Two details that bite people
- Use the
valueargument. Inside the handler, the bag may still hold the old value. ReadingEntity(veh).state.lockedthere can give you the previous state. Always trust the parameter. - The entity may not exist locally. If the vehicle is out of scope for this client,
GetEntityFromStateBagNamereturns0. When that vehicle streams in later, the handler will not necessarily fire again for a value that did not change. Apply the current state wherever you first interact with the entity too, for example when a player enters the vehicle or targets it.
Never let the client be the authority
Clients can write to some state bags themselves, such as their own player bag and entities they control. That is convenient for purely cosmetic data, but it means any value a client can write, a cheater can write too.
Treat it this way:
- Anything that grants money, items, access or job permissions must be set by the server only, and the server must decide based on its own data, never on a value it read back from a client-writable bag.
- If you allow client writes for something harmless (a selected walk style, a UI preference), keep it isolated under clearly named keys and never use those keys in server-side logic that matters.
- On the server, a change handler receives a
replicatedflag indicating the change came from a client. You can use it to log or revert writes to keys that only the server should touch.
A quick server-side guard looks like this:
-- server.lua
local protectedKeys = { onDuty = true, jobGrade = true }
AddStateBagChangeHandler(nil, nil, function(bagName, key, value, _, replicated)
if replicated and protectedKeys[key] then
print(('[myres] client tried to set %s on %s'):format(key, bagName))
end
end)Logging is a starting point. The real protection is that your server code never reads these keys as proof of anything; it reads its own records.
Keep payloads small
Every replicated change sends the whole value for that key, not a diff. If you store a 200-entry table in one key and change one field, the full table goes over the network to every client that should receive it.
- Split large structures into several keys so a change only resends what moved.
- Store ids and short flags, not full item lists or descriptions. Clients can look up static data from a shared config file.
- Do not update a replicated key every frame or every few hundred milliseconds. If a value changes that often, it is probably something each client should compute locally.
- Use non-replicated keys for server-only data instead of keeping a separate Lua table that can fall out of sync with the entity.
Cleanup and lifecycle
Entity state disappears when the entity is deleted. Player state disappears when the player drops. That is usually what you want, but it has consequences:
- If your script tracks something important on an entity, also save it to the database when it matters, or it is gone with the entity.
- Global state persists until the server restarts or you clear it. Reset keys to
nilwhen an event ends so stale flags do not confuse other resources. - Restarting your resource does not clear state that was set on entities or globally. On resource start, either re-read existing state or reset your keys deliberately.
Debugging state bags
When something does not sync, check in this order:
- Was the value set with replication enabled? A
falseflag is the usual culprit. - Is the entity actually networked? Local-only entities have no network id, and their state will not reach other clients.
- Is the client in scope? Test with two players standing next to each other before testing across the map.
- Is the handler key spelled the same as the key you set? A key filter is an exact match.
- Add a temporary handler with
nil, nilfilters that prints every change, then remove it once you find the problem. It is noisy but shows exactly what is replicating.
Practical takeaway
- Use entity state for things in the world, player state for session data, global state for server-wide flags, and the database for anything that must persist.
- Let the server write anything that matters; clients request, the server validates and sets.
- React with
AddStateBagChangeHandlerinstead of polling loops, and use the handler'svalueargument. - Handle entities that are not yet streamed in by also applying state when you first interact with them.
- Keep each key small and change it rarely. If you would not send it in an event every second, do not put it in a replicated key that changes every second.