Client ↔ server data
Get data from the server to players and back: events, callbacks and state bags – and when to use which.
Developer Preview. Scripting is live on Neighborly servers – everything on these pages works today. The API is young, so tell us what you need next on Discord.
Neighborly keeps the game world in sync for you: where Sims are and what they do, what's built on a lot and the time of day look the same for every player. Your own data is different – a savings account, a job, a player's status, whether the café is open. Moving that data between the server and players is your job, and Neighborly gives you three tools for it:
TriggerServerEventTriggerClientEventTriggerServerCallbackTriggerClientCallbackGlobalStatePlayer(id).stateWhich one should I use?
Start from what you want to happen. If more than one row fits, the rule of thumb is: moments are events, questions are callbacks, facts are state.
| You want to… | Use | Direction | Late joiners | Example |
|---|---|---|---|---|
| Tell players that something happened right now – a sound, a toast, a cutscene | TriggerClientEvent | Server → client | No | Doorbell ringing |
| Send a player's action to the server | TriggerServerEvent | Client → server | – | Brew a drink |
| Ask the server and use the answer – a balance, a price, “did it work?” | Server callback | Client → server → client | – | Bank deposit |
| Ask one player and wait for their answer – accept a trade, confirm a payment | Client callback | Server → client → server | – | Money request |
| Share a server-wide fact everyone needs | GlobalState | Server → every client | Yes | Café open, player list |
| Share a fact about one player | Player(id).state | Server → every client | Yes | Job, on duty, team |
| Share a fact about a lot | Lot(zoneId).state | Server → every client | Yes | Lights, doorbell sound |
| Attach data to an object or Sim | Entity(id).state | Server → players on its lot | Yes | Notes, cups brewed |
| Remember a small setting on one machine | KVP | Stays where it was written | – | UI theme, last amount |
| Keep real data forever | Database | Server only | – | Bank accounts, notes |
| Update your HTML page | SendNUIMessage | Client Lua → page | – | Phone, scoreboard |

Whatever you pick, the server decides. Clients may ask for things with events and callbacks, but only server code changes money, ownership, needs or replicated state – and it checks every request first. See Best practices.
Events with payloads
Events are the simplest tool: a name plus arguments, sent once. The receiver must register network events with RegisterNetEvent. On the server, source is the player who sent it.
RegisterNetEvent('rtx_garden:harvested', function(plant, amount)
exports.neighborly:notify({
text = ('You harvested %d %s.'):format(amount, plant),
type = 'success',
icon = 'plant'
})
end)
RegisterCommand('harvest', function()
local plant = GetClosestObject(GetSimPosition(GetActiveSim()), nil, 2.0)
if not plant or not GetObjectDefinition(plant):lower():find('garden') then
return exports.neighborly:notify({ text = 'Stand next to a garden plant first.' })
end
TriggerServerEvent('rtx_garden:harvest', GetObjectPosition(plant))
end, false)local harvested = {}
RegisterNetEvent('rtx_garden:harvest', function(coords)
local src = source
local sim = GetPlayerCharacter(src)
local zoneId = GetPlayerLot(src)
if type(coords) ~= 'table' or not sim or not zoneId then
return
end
local spot = ('%s:%d:%d'):format(zoneId, math.floor(coords.x), math.floor(coords.z))
if harvested[spot] and os.time() - harvested[spot] < 3600 then
return TriggerClientEvent('neighborly:notify', src, { text = 'Nothing is ripe here yet.' })
end
if #(GetSimPosition(sim) - coords) > 3.0 then
return
end
harvested[spot] = os.time()
local amount = math.random(2, 5)
GiveMoney(src, amount * 3, 'Sold tomatoes')
TriggerClientEvent('rtx_garden:harvested', src, 'tomatoes', amount)
end)| Rule | Details |
|---|---|
| What you can send | Strings, numbers, booleans, nil, vector3 and tables of those. Functions and handles to Lua objects can't cross the network. |
| How much | Keep events small – send ids, not whole data sets – and well below 64 KB. Batch many small updates into one event. |
| Order | Events from the server to one player arrive in the order they were sent, together with state bag changes. If you set a state bag and then trigger an event, the client already sees the new value in the handler. |
| Who receives | TriggerClientEvent(name, -1, …) reaches everyone connected now. For one lot, loop over GetPlayersOnLot. |
| Late joiners | Miss every event sent before they connected. If they need to know, it belongs in a state bag. |
Server callbacks
Very often the client needs an answer: how much is in my savings account?, did the purchase work?, what's on the menu today? Pairing two events by hand works but gets messy quickly. Server callbacks do the round trip for you: the client calls TriggerServerCallback, its thread pauses, the server handler runs and whatever it returns comes back as return values.
- The client asks
TriggerServerCallback('rtx_shop:buy', 'latte')sends the name and arguments, then pauses the calling thread. - The server checks and answersThe handler registered with
RegisterServerCallbackruns withsourceas its first argument. It validates everything, changes what it has to and returns its answer. - The client continuesThe return values arrive and
TriggerServerCallbackreturns them. The rest of your function runs as if it had been one call.
local db = exports.neighborly:db()
RegisterServerCallback('rtx_shop:getMenu', function(source)
local regular = (db:get('visits:' .. GetPlayerAccountId(source)) or 0) >= 10
local menu = {}
for id, item in pairs(Config.Items) do
menu[#menu + 1] = { id = id, label = item.label, price = regular and math.floor(item.price * 0.9) or item.price }
end
return menu, regular
end)
RegisterServerCallback('rtx_shop:buy', function(source, itemId)
local item = Config.Items[itemId]
if not item then
return false, 'That is not on the menu.'
end
if GetPlayerLot(source) ~= Config.ShopLot then
return false, 'You have to be in the shop.'
end
if not TakeMoney(source, item.price, 'Shop: ' .. item.label) then
return false, "You don't have enough simoleons."
end
db:increment('visits:' .. GetPlayerAccountId(source), 1)
AddSimBuff(GetPlayerCharacter(source), item.buff, 60)
return true, GetBalance(source)
end)RegisterCommand('shop', function()
local menu, regular = TriggerServerCallback('rtx_shop:getMenu')
if not menu then
return exports.neighborly:notify({ text = 'The shop is not answering.', type = 'error' })
end
local items = {}
for _, item in ipairs(menu) do
items[#items + 1] = {
label = item.label,
badge = FormatMoney(item.price),
onSelect = function()
local ok, result = TriggerServerCallback('rtx_shop:buy', item.id)
exports.neighborly:notify({
text = ok and ('Enjoy! You have %s left.'):format(FormatMoney(result)) or result,
type = ok and 'success' or 'error'
})
end
}
end
exports.neighborly:openMenu({
id = 'rtx_shop',
title = 'Corner Shop',
subtitle = regular and 'Regulars get 10% off' or nil,
items = items
})
end, false)- The handler is a thread. It may
Wait, use the database or even ask the player something with a client callback before it returns. - Return several values. The
ok, resultpattern above lets the client show a friendly message for every failure. - Always handle
nil. If no handler has that name, the handler raised an error, or nothing came back within 30 seconds,TriggerServerCallbackreturns nothing and logs a warning to the launcher log. - Call it inside a thread. Commands, event handlers, NUI callbacks, menu
onSelectfunctions andCreateThreadare all threads. Calling it at the top level of a file raises an error. - Validate like an event. A callback is a door into your server just like a net event – check types, ranges, distance and permissions, and rate-limit expensive ones.
From a NUI page all the way to the server
Callbacks chain nicely. The page asks Lua with fetch, the NUI callback asks the server and waits, and only then answers the page – so the UI always shows what the server decided.
async function deposit(amount) {
const res = await fetch(`https://${GetParentResourceName()}/deposit`, {
method: 'POST',
headers: { 'Content-Type': 'application/json; charset=UTF-8' },
body: JSON.stringify({ amount })
}).then((r) => r.json());
document.getElementById('status').textContent = res.ok ? 'Saved!' : res.error;
}RegisterNUICallback('deposit', function(data, cb)
local ok, result = TriggerServerCallback('nb_bank:deposit', tonumber(data.amount))
if ok == nil then
return cb({ ok = false, error = 'The bank is not answering.' })
end
cb({ ok = ok, account = ok and result or nil, error = not ok and result or nil })
end)The complete version is the nb_bank example.
Client callbacks
Sometimes the server needs to ask a player: do you accept this trade?, which outfit should the uniform use?, where is your camera looking? Client callbacks are the mirror image of server callbacks: the server calls TriggerClientCallback for one player and waits for what their handler returns.
RegisterClientCallback('rtx_trade:confirm', function(fromName, item, price)
local answer = exports.neighborly:alertDialog({
header = 'Trade offer',
content = ('%s offers you %s for %s.'):format(fromName, item, FormatMoney(price)),
confirmLabel = 'Accept',
cancelLabel = 'Decline'
})
return answer == 'confirm'
end)local asking = {}
RegisterNetEvent('rtx_trade:offer', function(target, itemId)
local src = source
local item = Config.Items[itemId]
if not item or type(target) ~= 'number' or target == src or not GetPlayerName(target) then
return
end
if GetPlayerLot(target) ~= GetPlayerLot(src) or asking[target] then
return
end
asking[target] = true
local accepted = TriggerClientCallback('rtx_trade:confirm', target, GetPlayerName(src), item.label, item.price)
asking[target] = nil
if accepted == true and TransferMoney(target, src, item.price, 'Trade: ' .. item.label) then
TriggerClientEvent('neighborly:notify', src, { text = 'Sold!', type = 'success' })
else
TriggerClientEvent('neighborly:notify', src, { text = 'No deal this time.' })
end
end)- Never trust the answer. It comes from a PC you don't control. Use client callbacks for choices and local information, never for facts like money, ownership or what an item costs – the server already knows those.
- Expect no answer. After 30 seconds, or as soon as the player leaves,
TriggerClientCallbackreturns nothing. Treat that as “no”. - One question at a time. Keep track of players you are waiting for, like
askingabove, so two requests don't open two dialogs. - Only the calling thread waits. The rest of your resource and the server keep running while the player decides.
State bags
A state bag is a small table attached to the server, a player, a lot or an entity. Set a value on the server and Neighborly sends it to the right clients – now and to everyone who arrives later. State bags are the right tool for facts: things that are true until they change.
| Bag | Name | Who can replicate | Replicates to | Late joiners get it |
|---|---|---|---|---|
GlobalState | global | Server | Every client | Before client scripts start |
Player(id).stateLocalPlayer.state | player:12 | Server, and the player themselves | Every client | Before client scripts start |
Lot(zoneId).state | lot:4821 | Server | Every client | Before client scripts start |
Entity(id).state | entity:90031 | Server | Every client | Before client scripts start |
GlobalState.cafeOpen = true
local state = Player(source).state
state:set('job', 'barista', true)
state:set('onDuty', true, true)
state:set('shiftStarted', os.time(), false)
Lot(zoneId).state:set('sign', 'Bluejay Café – open until 22:00', true)
Entity(GetPlayerCharacter(source)).state:set('cupsToday', 12, true)if GlobalState.cafeOpen then
exports.neighborly:showTextUI('Bluejay Café is open', { icon = 'coffee' })
end
if LocalPlayer.state.onDuty then
print('You are working as', LocalPlayer.state.job)
end
local zoneId = GetCurrentLot()
print('Sign here:', zoneId and Lot(zoneId).state.sign or 'none')Replication rules
- The server replicates.
bag:set(key, value, true)sends the value to clients. Assigningbag.key = valueon the server is the same as a replicated:set. - Server-only values stay on the server. Pass
falseas the third argument for data clients shouldn't see, likeshiftStartedabove. - A client may write only its own player bag.
LocalPlayer.state:set(key, value, true)goes to the server, which checks that the bag belongs to that player and passes it on to everyone. Writes toGlobalState, other players, lots or entities are refused and the client gets the real value back. Withouttruea client write stays on that PC. Server owners can refuse every client write with"stateBagStrictMode": trueinserver.json. - Late joiners get the current values. A connecting player receives every replicated bag – global, players, lots and entities – before their client scripts run, so reading a bag at the top of
client.luaworks. - Change handlers only fire for changes. The values a player receives on joining don't trigger
AddStateBagChangeHandler. Read the current value once, then listen – see below. - Values are copied, not linked. Changing a field of a table you read from a bag changes nothing. Change your table and set the whole key again.
- Unchanged values cost nothing. Setting a key to the value it already has sends nothing.
- Changes arrive in order. State changes and events from the server reach each player in the order you made them.
- Keep values small. A key should stay below about 16 KB; the hard limit is 64 KB. Bags hold state, not logs or histories.
- Bags live in memory. Player bags are cleared when the player leaves; global, lot and entity bags when the server restarts. Save what must survive with KVP or the database and put it back in
onResourceStart.
local list = GlobalState.queue or {}
list[#list + 1] = GetPlayerName(source)
GlobalState.queue = list
The three lines above are the right way to add to a replicated list. Writing table.insert(GlobalState.queue, name) only changes a copy and nobody – not even the server – sees the new entry.
Reading and writing by bag name
Change handlers give you a bag name like 'lot:4821'. GetStateBagValue, SetStateBagValue and GetStateBagKeys work with that name directly, and GetPlayerFromStateBagName, GetLotFromStateBagName and GetEntityFromStateBagName turn it back into an id.
Reacting to changes
The handler receives (bagName, key, value, reserved, replicated) when a value changes – just before it is stored, like on FiveM, so reading the bag inside the handler still gives the old value. Use the value argument. Pass nil as the key to hear every key, and nil as the filter to hear every bag – then use the helpers above to find out whose bag it was. It returns a cookie for RemoveStateBagChangeHandler.
Because handlers don't fire for values a player received on arrival, almost every client that shows state uses the same two-part pattern: read the current value, then listen for changes.
local function showSign(zoneId, text)
if text then
exports.neighborly:showTextUI(text, { icon = 'home' })
else
exports.neighborly:hideTextUI()
end
end
AddEventHandler('lotEntered', function(zoneId)
showSign(zoneId, Lot(zoneId).state.sign)
end)
AddEventHandler('lotLeft', function(zoneId)
showSign(zoneId, nil)
end)
AddStateBagChangeHandler('sign', nil, function(bagName, key, text)
local zoneId = GetLotFromStateBagName(bagName)
if zoneId and zoneId == GetCurrentLot() then
showSign(zoneId, text)
end
end)Handlers work on the server too. They fire when server code changes a value – useful when several resources share a key, like a job other resources set:
AddStateBagChangeHandler('job', nil, function(bagName, key, job)
local player = GetPlayerFromStateBagName(bagName)
if player then
print(('%s is now working as %s'):format(GetPlayerName(player), tostring(job)))
end
end)See it in real resources
nb_scoreboardA live player list in GlobalState.
nb_lotcounterA shared counter in GlobalState.
nb_bankServer and client callbacks with NUI.
And nb_status lets every player publish their own status in their player state bag.
Common problems
My change handler never runs for the value that's already set
Handlers only fire for changes. Read the bag when your script starts or in lotEntered, then listen for changes.
I changed a table in a state bag but nobody sees it
Values are copies. Modify your table, then set the whole key again with :set or an assignment.
Players who join later don't see what happened
You probably used an event. Events only reach players who are online right now – store lasting facts in a state bag.
TriggerServerCallback returns nil
Check the server console: either no handler is registered with exactly that name, the handler raised an error, or it took longer than 30 seconds. Make sure the server resource started without errors.
Can a client set its own job or money in a state bag?
No. Client writes stay on that PC and are overwritten by the server. Send a request to the server and let it decide.
How do I send something to everyone on one lot?
For a moment, loop over GetPlayersOnLot(zoneId) and trigger a client event for each. For a fact, use Lot(zoneId).state.