3 min read
QBCore Scripting Guide
Create a QBCore resource with explicit client/server boundaries. The daily reward below checks eligibility on the server and reserves each claim in the database before changing money. Client callbacks are never authorization.
These examples are source-reviewed against QBCore Player APIs and oxmysql. Lua contract tests use mocks; a real FiveM server and database acceptance test is still required.
Table of Contents
- Getting Started
- Basic Script Structure
- QBCore API Integration
- Creating Your First Script
- Advanced Concepts
- Best Practices
- Deployment and Testing
Getting Started
Prerequisites
Before you start scripting for QBCore, ensure you have:
- QBCore Framework: Latest version installed
- Development Environment: VS Code or similar editor
- Basic Lua Knowledge: Understanding of Lua programming language
- FiveM Server: Development server for testing
- Database Access: For data persistence
Development Environment Setup
-
Install VS Code Extensions:
- Lua Language Server
- FiveM Development Tools
- GitLens (for version control)
-
Create Development Workspace:
mkdir qbcore-scripts cd qbcore-scripts -
Set up Version Control:
git init # Create a .gitignore before staging files; never include server credentials.
Basic Script Structure
Standard QBCore Resource Structure
resource-name/
├── fxmanifest.lua # Resource manifest
├── config.lua # Configuration file
├── server/
│ ├── main.lua # Server-side logic
│ └── callbacks.lua # Server callbacks
├── client/
│ ├── main.lua # Client-side logic
│ └── events.lua # Client events
├── shared/
│ └── config.lua # Shared configuration
└── html/ # NUI files (if needed)
├── index.html
├── style.css
└── script.jsEssential Files
fxmanifest.lua
fx_version 'cerulean'
game 'gta5'
description 'QBCore Custom Script'
version '1.0.0'
author 'YourName'
shared_scripts {
'shared/config.lua',
'config.lua'
}
client_scripts {
'client/main.lua',
'client/events.lua'
}
server_scripts {
'@oxmysql/lib/MySQL.lua', -- If using database
'server/main.lua',
'server/callbacks.lua'
}
-- NUI (if using HTML interface)
ui_page 'html/index.html'
files {
'html/index.html',
'html/style.css',
'html/script.js'
}
dependencies {
'qb-core'
}
QBCore API Integration
Getting QBCore Object
Always get the QBCore object at the beginning of your scripts:
local QBCore = exports['qb-core']:GetCoreObject()Player Data Access
Client-Side Player Data
-- Get local player data
local PlayerData = QBCore.Functions.GetPlayerData()
-- Listen for player data updates
RegisterNetEvent('QBCore:Client:OnPlayerLoaded', function()
PlayerData = QBCore.Functions.GetPlayerData()
-- Initialize your script here
end)
RegisterNetEvent('QBCore:Client:OnPlayerUnload', function()
PlayerData = {}
-- Clean up when player logs out
end)
RegisterNetEvent('QBCore:Player:SetPlayerData', function(val)
PlayerData = val
-- Handle player data updates
end)Server-Side Player Data
-- Get player by source
local Player = QBCore.Functions.GetPlayer(source)
if not Player then return end
-- Get player by citizen ID
local Player = QBCore.Functions.GetPlayerByCitizenId(citizenId)
-- Get player by phone number
local Player = QBCore.Functions.GetPlayerByPhone(phone)Creating Your First Script
Build a cash-only, per-character daily reward. Use an isolated development server with qb-core,
oxmysql, and an InnoDB database. The reward and cooldown are server configuration, not event arguments.
Read Cfx event security before adding rewards.
Step 1: Create the Resource Structure
Create qb-dailybonus inside your server's resources directory:
mkdir -p qb-dailybonus/client qb-dailybonus/server
cd qb-dailybonusStep 2: Create fxmanifest.lua
fx_version 'cerulean'
game 'gta5'
description 'QBCore Daily Bonus Example'
version '1.0.0'
client_script 'client/main.lua'
server_scripts {
'@oxmysql/lib/MySQL.lua',
'config.lua',
'server/main.lua'
}
dependencies { 'qb-core', 'oxmysql' }Step 3: Create Configuration
-- config.lua (server-only)
Config = {}
Config.Reward = 1000
Config.CooldownSeconds = 24 * 60 * 60Import this SQL into the same database as your server before starting the resource:
CREATE TABLE IF NOT EXISTS docs_dailybonus_claims (
citizenid VARCHAR(50) NOT NULL PRIMARY KEY,
last_claim BIGINT UNSIGNED NOT NULL DEFAULT 0
) ENGINE=InnoDB;This new table stores Unix seconds, not a SQL TIMESTAMP or milliseconds. If you previously used
player_dailybonus, stop that resource and reconcile its historical claims before enabling this
example; otherwise existing players will receive a fresh first claim. Do not blindly convert or
remove your production table.
Step 4: Server-Side Logic
-- server/main.lua
local QBCore = exports['qb-core']:GetCoreObject()
local inFlight = {}
RegisterNetEvent('qb-dailybonus:server:claimBonus', function()
local src = source
local Player = QBCore.Functions.GetPlayer(src)
if not Player then return end
local citizenId = Player.PlayerData.citizenid
if inFlight[citizenId] then return end
inFlight[citizenId] = true
local ok, err = xpcall(function()
MySQL.query.await([[
INSERT IGNORE INTO docs_dailybonus_claims (citizenid, last_claim)
VALUES (?, 0)
]], { citizenId })
-- The conditional UPDATE is the authorization decision. Only one concurrent
-- request can change this character's row during the cooldown.
local changed = MySQL.update.await([[
UPDATE docs_dailybonus_claims
SET last_claim = UNIX_TIMESTAMP()
WHERE citizenid = ?
AND last_claim <= UNIX_TIMESTAMP() - ?
]], { citizenId, Config.CooldownSeconds })
-- Database awaits can outlive logout or a switch to another character.
Player = QBCore.Functions.GetPlayer(src)
if not Player or Player.PlayerData.citizenid ~= citizenId then return end
if changed ~= 1 then
TriggerClientEvent('QBCore:Notify', src, 'Daily bonus is not available yet.', 'error')
return
end
if not Player.Functions.AddMoney('cash', Config.Reward, 'daily-bonus') then
error('Cash reward failed after claim reservation')
end
Player.Functions.Save()
TriggerClientEvent('QBCore:Notify', src, 'Daily bonus claimed.', 'success')
end, debug.traceback)
inFlight[citizenId] = nil
if not ok then
print(('[qb-dailybonus] Claim failed for %s: %s'):format(citizenId, err))
end
end)The event accepts no reward, citizen ID, or eligibility value from the client. The in-flight guard reduces overlapping queries; the conditional database update also protects replay after a resource restart. A database error grants no money and releases the local guard.
Failure boundary: reservation and QBCore money persistence are separate operations. Disconnects, a crash, or a failed save after reservation can consume the cooldown without a durable reward. This example favors preventing duplicate payouts; it does not promise exactly-once delivery. Reconcile failed claims administratively after checking logs and balances. Do not automatically clear a reservation after a possible payout. A production economy may need a durable reward ledger.
Step 5: Client-Side Logic
-- client/main.lua
RegisterCommand('dailybonus', function()
TriggerServerEvent('qb-dailybonus:server:claimBonus')
end, false)
TriggerEvent('chat:addSuggestion', '/dailybonus', 'Claim your daily bonus')Expected result: the first eligible /dailybonus adds the configured cash once. Repeating the
command or sending the event directly cannot bypass the cooldown. Test simultaneous claims,
logout during database work, database failure, resource restart, and eligibility at the next
24-hour boundary on your staging server. See money APIs and
configuration validation before adapting this example.
Advanced Concepts
Database Integration
Using oxmysql
-- Insert data
MySQL.insert('INSERT INTO table_name (column1, column2) VALUES (?, ?)', {
value1, value2
}, function(insertId)
print('Inserted with ID: ' .. insertId)
end)
-- Select single row
MySQL.single('SELECT * FROM table_name WHERE id = ?', {id}, function(result)
if result then
print('Found: ' .. result.name)
end
end)
-- Select multiple rows
MySQL.query('SELECT * FROM table_name WHERE active = ?', {true}, function(results)
for i = 1, #results do
print('Row: ' .. results[i].name)
end
end)
-- Update data
MySQL.update('UPDATE table_name SET column1 = ? WHERE id = ?', {
newValue, id
}, function(affectedRows)
print('Updated ' .. affectedRows .. ' rows')
end)Event Handling
Custom Events
-- Server to Client
TriggerClientEvent('custom:event', source, data)
-- Client to Server
TriggerServerEvent('custom:event', data)
-- Register event handler
RegisterNetEvent('custom:event', function(data)
-- Handle the event
print('Received data: ' .. json.encode(data))
end)QBCore Specific Events
-- Player loaded
RegisterNetEvent('QBCore:Client:OnPlayerLoaded', function()
-- Player finished loading
end)
-- Job change
RegisterNetEvent('QBCore:Client:OnJobUpdate', function(JobInfo)
-- Player job changed
end)
-- Gang change
RegisterNetEvent('QBCore:Client:OnGangUpdate', function(GangInfo)
-- Player gang changed
end)Creating Callbacks
-- Server callback
QBCore.Functions.CreateCallback('script:getData', function(source, cb, ...)
local args = {...}
local Player = QBCore.Functions.GetPlayer(source)
-- Process data
cb(responseData)
end)
-- Client trigger callback
QBCore.Functions.TriggerCallback('script:getData', function(data)
-- Handle response
print(json.encode(data))
end, arg1, arg2)NUI Integration
HTML Interface
<!-- html/index.html -->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Custom Interface</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="container" hidden>
<h1>Custom Script Interface</h1>
<button id="closeBtn">Close</button>
</div>
<script src="script.js"></script>
</body>
</html>JavaScript Communication
// html/script.js (no jQuery dependency)
const container = document.getElementById('container');
window.addEventListener('message', (event) => {
if (event.data?.action === 'open') container.hidden = false;
if (event.data?.action === 'close') container.hidden = true;
});
document.getElementById('closeBtn').addEventListener('click', async () => {
try {
await fetch(`https://${GetParentResourceName()}/close`, {
method: 'POST',
headers: { 'Content-Type': 'application/json; charset=UTF-8' },
body: JSON.stringify({})
});
} catch (error) {
console.error('Could not close NUI:', error);
}
});Lua NUI Integration
-- Client-side NUI control
RegisterCommand('openui', function()
SetNuiFocus(true, true)
SendNUIMessage({
action = 'open'
})
end)
RegisterNUICallback('close', function(data, cb)
SetNuiFocus(false, false)
SendNUIMessage({
action = 'close'
})
cb('ok')
end)Best Practices
Code Organization
- Separate Concerns: Keep client and server logic separate
- Use Config Files: Make your scripts configurable
- Error Handling: Always check for nil values and edge cases
- Consistent Naming: Use clear, descriptive variable names
Performance Optimization
-- Cache frequently used values
local PlayerData = QBCore.Functions.GetPlayerData()
-- Use proper thread management
CreateThread(function()
while true do
if PlayerData then
-- Do work
end
Wait(1000) -- Don't run every frame
end
end)
-- Clean up resources
AddEventHandler('onResourceStop', function(resource)
if resource == GetCurrentResourceName() then
-- Cleanup code here
end
end)Security Considerations
-- Server-side validation
RegisterNetEvent('script:doSomething', function(data)
local src = source
local Player = QBCore.Functions.GetPlayer(src)
-- Always validate player exists
if not Player then return end
-- Validate input data
if not data or type(data) ~= 'table' then
return
end
-- Additional security checks
if not Player.Functions.GetItemByName('required_item') then
TriggerClientEvent('QBCore:Notify', src, 'You need the required item', 'error')
return
end
-- Process request
end)Deployment and Testing
Local Testing
Before starting the resource, you can check fxmanifest.lua with the free
fxmanifest Generator & Validator and run
Lua, QBCore API and event preflight checks with the
FiveM Script Tester. The script tester uses
a browser sandbox, not your real FXServer; neither tool verifies game natives, database operations
or complete gameplay flows. RPScripts and qbcore.net are operated by the same owner.
-
Add to server.cfg:
ensure oxmysql ensure qb-core ensure qb-dailybonus -
Monitor for errors: Inspect your actual FXServer/txAdmin console and database logs; the log file location depends on your deployment.
-
Test all functions:
- Join server as different players
- Test edge cases
- Verify database operations
Production Deployment
- Code Review: Review all code for security issues
- Database Backup: Backup database before deployment
- Staged Rollout: Test on staging environment first
- Monitoring: Monitor server performance after deployment
Current FiveM Lua uses Lua 5.4; the old lua54 manifest flag is deprecated. Consult the resource manifest reference and NUI callback reference for platform behavior.
For more advanced topics, check out our API documentation or join our community discussions.
Found an issue in this guide?
Send the page URL, the affected example, and a source or reproduction to the site maintainer. For a server or resource problem, use the support guide.
Become admin
Grant QBCore admin access correctly with ACE principals, server.cfg, /addpermission and qb-adminmenu. Includes custom permission groups and troubleshooting.
How to Set Job on QBCore: /setjob Command & SetJob Code
Set or change a QBCore player's job using /setjob and server-side SetJob methods. Check grades, ACE permissions, duty state and database persistence.
