Skip to content
Tutorials

FiveM NUI in Lua: Messages, Callbacks and Focus Done Right

ATY Development
·
·Updated ·
19 views
StandaloneQBCoreESXQbox
FiveM NUI in Lua: Messages, Callbacks and Focus Done Right

Most broken FiveM UIs fail in the same handful of ways. A file is missing from the manifest, a callback never answers, focus gets stuck, or the server trusts whatever the page sends it. This article walks through the NUI pipeline end to end, with a minimal pattern you can reuse in every resource.

The four moving parts

Every NUI resource is built from the same pieces, whatever framework you run:

  • The manifest declares which HTML page the resource loads and which files the page is allowed to request.
  • Lua to JavaScript: the client script calls SendNUIMessage, and the page receives it as a standard browser message event.
  • JavaScript to Lua: the page sends a fetch POST to https://<resource-name>/<callback>, and Lua handles it with RegisterNUICallback.
  • Focus: SetNuiFocus decides whether the page receives the mouse and keyboard.

If you keep these four separate in your head, debugging becomes a matter of finding which link in the chain broke.

The manifest

fx_version 'cerulean'
game 'gta5'
lua54 'yes'

client_script 'client.lua'
server_script 'server.lua'

ui_page 'html/index.html'

files {
  'html/index.html',
  'html/style.css',
  'html/app.js'
}

Every file the page loads, including fonts, images and sounds, must be covered by files. If it is not, the request fails and you usually get a blank or unstyled UI with no Lua error at all. Glob patterns such as 'html/**/*' work, but be careful not to ship source folders, maps or node_modules by accident. If you build with Vite or similar, point the manifest at the build output only.

Lua to JavaScript: one message shape

Pick a single message format and stick with it. An action field plus a data payload keeps the JavaScript side a simple router.

-- client.lua
local isOpen = false

local function setOpen(state, payload)
  isOpen = state
  SetNuiFocus(state, state)
  SendNUIMessage({
    action = state and 'open' or 'close',
    data = payload
  })
end

RegisterCommand('shopui', function()
  if isOpen then return end
  setOpen(true, { title = 'General Store' })
end, false)
// app.js
const app = document.getElementById('app');

window.addEventListener('message', (event) => {
  const { action, data } = event.data;

  if (action === 'open') {
    app.classList.remove('hidden');
    render(data);
  } else if (action === 'close') {
    app.classList.add('hidden');
  }
});

Everything you pass to SendNUIMessage is serialized to JSON, so stick to plain tables, strings, numbers and booleans. Functions and vectors will not arrive the way you expect; convert coordinates to { x = ..., y = ... } tables first.

JavaScript to Lua: callbacks that always answer

On the page side, wrap the request in a tiny helper. GetParentResourceName() is injected into the NUI page and returns the resource name, so you never hardcode it.

// app.js
async function post(name, body = {}) {
  const res = await fetch(`https://${GetParentResourceName()}/${name}`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json; charset=UTF-8' },
    body: JSON.stringify(body)
  });
  return res.json();
}

document.getElementById('buy').addEventListener('click', () => {
  post('buy', { item: 'water', amount: 2 });
});
-- client.lua
RegisterNUICallback('close', function(_, cb)
  setOpen(false)
  cb({})
end)

RegisterNUICallback('buy', function(data, cb)
  TriggerServerEvent('myshop:buy', data.item, data.amount)
  cb({ ok = true })
end)

Two rules matter here:

  • Always call cb, on every code path, including early returns. If you forget, the fetch promise hangs and any UI logic waiting on it freezes.
  • Answer with a table, even an empty one. If the page calls res.json() and you replied with a bare string like 'ok', parsing throws and the error is easy to miss.

Focus: open cleanly, close every time

A stuck cursor is the bug players report most, and it is almost always a missing close path. Give the player several ways out and make all of them go through the same function.

// app.js
document.addEventListener('keyup', (e) => {
  if (e.key === 'Escape') post('close');
});
-- client.lua
AddEventHandler('onResourceStop', function(resource)
  if resource == GetCurrentResourceName() and isOpen then
    SetNuiFocus(false, false)
  end
end)

The resource stop handler matters during development: restart a resource while its UI is open and, without it, you may be left with no mouse control until you reconnect. Also close the UI when the player dies, enters a vehicle or gets cuffed, if that suits your design. A single setOpen(false) keeps state and focus consistent.

If players should keep walking while the UI is open, look at SetNuiFocusKeepInput. Be aware that game controls then fire while the player types, so you will need to disable the relevant controls in a loop that only runs while the UI is open.

The page is client code, so treat it that way

Anything running in NUI is under the player's control. A cheater can call your callbacks with any payload they like, skip your client-side checks entirely and fire your server event directly. The page decides what to show; the server decides what happens.

-- server.lua
local ITEMS = { water = 5, bread = 8 }

RegisterNetEvent('myshop:buy', function(item, amount)
  local src = source
  local price = ITEMS[item]
  amount = math.floor(tonumber(amount) or 0)

  if not price or amount < 1 or amount > 10 then return end

  -- check distance to the shop, check money through your
  -- framework, remove money, then give the item
end)
  • Never send prices, rewards or permissions from the page. Look them up on the server.
  • Clamp and type-check every number. tonumber and math.floor stop strings, decimals and negatives.
  • Check that the player is actually where the action makes sense, using server-side ped coordinates.
  • Rate-limit expensive or valuable actions per source.

Keeping NUI cheap

resmon shows Lua time, not browser time, so a heavy UI can drag client FPS while your resource looks clean. Watch for these:

  • Do not stream data every frame. Calling SendNUIMessage inside a Wait(0) loop is a common HUD mistake. Send on change, or throttle to a few times per second.
  • Stop work when hidden. Clear setInterval timers and pause CSS animations when the UI closes. A hidden element with a running animation still costs.
  • Compress assets. Large PNGs and unoptimized fonts slow first open and every client download.
  • Ship a build, not a dev setup. Minified bundles load faster and leak less of your source.

Debugging checklist

FiveM includes Chromium DevTools for NUI, which you can open from the F8 console with nui_devtools. The Console and Network tabs answer most questions. When something does not work, go down this list:

  1. Blank page or missing styles: check the Network tab for failed requests and confirm the file is listed in files.
  2. Message never arrives: log event.data in the listener and confirm the action string matches exactly.
  3. Callback hangs: find the code path in Lua that returns without calling cb.
  4. Callback 404s: the name in fetch and in RegisterNUICallback differ, or the resource folder was renamed and something is hardcoded.
  5. Old version still showing: restart the resource; if it persists, clear the client NUI cache.
  6. Cursor stuck: some close path skips SetNuiFocus(false, false).

For native signatures, the FiveM natives reference is the source of truth.

Takeaway

  • One message shape (action + data) and one post() helper per resource.
  • Every callback calls cb with a table, on every path.
  • All close paths go through one function that releases focus, plus an onResourceStop safety net.
  • The page shows; the server decides. Validate type, range, distance and price server-side.
  • Send NUI messages on change, stop timers when hidden and check DevTools before blaming Lua.