Developer Preview

State & storage

Share live data with state bags and save it with KVP and the database.

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.

Many resources need to share small pieces of data – is the café open, which job does a player have, who rang this doorbell last. Neighborly gives you three tools for that:

ToolLivesSeen byUse it for
State bagsIn memory until restartServer and every clientLive data everyone should see: jobs, duty status, lot settings
KVPOn diskOnly the side that wrote itSmall settings: a player's UI preferences, a server toggle
DatabaseOn disk, in backupsServer onlyReal data: bank accounts, inventories, business records

State bags

A state bag is a table attached to something. Set a value on the server and it is synced to every client automatically, including players who join later.

This is the short version. The State bags guide walks through every rule with diagrams – who can write, who receives what, what late joiners get and when handlers fire.

BagAttached toBag name
GlobalStateThe whole serverglobal
Player(source).stateA player (server)player:12
LocalPlayer.stateThe local player (client)player:12
Lot(zoneId).stateA lotlot:4821
Entity(sim).stateA Sim or an objectentity:90031
server.luaLUA
GlobalState.cafeOpen = true

Player(source).state:set('job', 'barista', true)
Player(source).state:set('onDuty', true, true)

Lot(zoneId).state:set('doorbellSound', 'chime', true)

Entity(GetPlayerCharacter(source)).state:set('ordersToday', 14, true)
client.luaLUA
if GlobalState.cafeOpen then
    print('The café is open')
end

if LocalPlayer.state.job == 'barista' then
    print('You work at the café')
end

local sound = Lot(GetCurrentLot()).state.doorbellSound or 'ding'
print('This lot\'s doorbell plays', sound)

The third argument of :set(key, value, replicated) decides whether the value is synced to clients. Use false for data only the server needs. Writing GlobalState.key = value is a shortcut for a replicated set.

Clients can only write their own player bag: LocalPlayer.state:set(key, value, true). The server checks it and passes it on; writes to any other bag are refused. Without true the value stays on that PC. Read the State bags guide for the full picture.

Reacting to changes

AddStateBagChangeHandler(key, bagFilter, handler) calls your handler whenever a key changes. Pass nil as the filter to watch every bag, or a bag name like 'global'. It returns a cookie for RemoveStateBagChangeHandler.

int AddStateBagChangeHandler(string? key, string? bagFilter, function handler)
client.luaLUA
AddStateBagChangeHandler('onDuty', nil, function(bagName, key, value, reserved, replicated)
    local player = GetPlayerFromStateBagName(bagName)
    if player ~= PlayerId() then
        return
    end
    exports.neighborly:notify({
        text = value and 'You are now on duty.' or 'You are off duty. Enjoy your evening!',
        type = value and 'success' or 'info'
    })
end)

AddStateBagChangeHandler('cafeOpen', 'global', function(bagName, key, value)
    exports.neighborly:notify({
        text = value and 'Bluejay Café just opened!' or 'Bluejay Café has closed for today.',
        icon = 'coffee'
    })
end)

Helpers to turn a bag name back into a thing: GetPlayerFromStateBagName, GetLotFromStateBagName and GetEntityFromStateBagName. They return nil if the bag belongs to something else.

KVP storage

Resource KVP is a tiny key/value store scoped to your resource. On a client it is saved on the player's PC (separately for each server); on the server it is saved in the server's data folder. Values can be strings, numbers, booleans or tables.

FunctionDescription
SetResourceKvp(key, value)Saves a value. Tables are stored as JSON.
GetResourceKvp(key)Returns the value or nil.
DeleteResourceKvp(key)Removes a key.
GetResourceKvpKeys(prefix)Returns a list of keys starting with prefix.
client.luaLUA
local settings = GetResourceKvp('settings') or { volume = 0.6, theme = 'light' }

RegisterNUICallback('saveSettings', function(data, cb)
    settings.volume = tonumber(data.volume) or settings.volume
    settings.theme = data.theme == 'dark' and 'dark' or 'light'
    SetResourceKvp('settings', settings)
    cb({ ok = true })
end)

Database

For real, persistent data the neighborly resource gives every server script a simple document database. Each resource gets its own space, saved in the server's data folder and included in the automatic backups. Keys are strings, values are anything JSON can hold. Calls are fast and synchronous – no callbacks needed.

Database exports.neighborly:db() Server
MethodReturnsDescription
db:get(key)anyThe stored value or nil.
db:set(key, value)–Stores a value, replacing the old one. nil deletes.
db:delete(key)booleanRemoves a key, true if it existed.
db:exists(key)booleanWhether a key exists.
db:update(key, fn)anyCalls fn(oldValue) and stores what it returns, safely even when two events change the same key at once.
db:increment(key, amount)numberAdds amount to a number (starting from 0) and returns the new value.
db:keys(prefix)tableAll keys starting with prefix.
db:find(prefix, filter)tableList of { key, value } under prefix for which filter(value) returns true.
server.luaLUA
local db = exports.neighborly:db()

local function accountKey(player)
    return 'account:' .. GetPlayerAccountId(player)
end

RegisterNetEvent('rtx_cafe:clockIn', function()
    local src = source
    local key = accountKey(src)
    local record = db:get(key) or { shifts = 0, earned = 0 }
    record.shifts = record.shifts + 1
    record.lastShift = os.time()
    db:set(key, record)
    Player(src).state:set('onDuty', true, true)
end)

local function addEarnings(player, amount)
    return db:update(accountKey(player), function(record)
        record = record or { shifts = 0, earned = 0 }
        record.earned = record.earned + amount
        return record
    end)
end

RegisterCommand('topbaristas', function(source)
    local rows = db:find('account:', function(record)
        return record.earned > 1000
    end)
    table.sort(rows, function(a, b)
        return a.value.earned > b.value.earned
    end)
    for i = 1, math.min(5, #rows) do
        print(i, rows[i].key, rows[i].value.earned)
    end
end, true)

Key your data by GetPlayerAccountId(player), not by the player's server id or name. Server ids change every time someone joins, names can change – the account id never does.