JavaScript Snippets
Common JavaScript patterns for FiveM resources. Treat these snippets as focused building blocks. Rename events and callbacks, handle rejected promises, validate messages crossing the NUI boundary, and move authoritative gameplay decisions to server-side handlers before production use. Log failures with enough context to reproduce them without exposing secrets.
NUI to Client
fetch(`https://${GetParentResourceName()}/callback`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
type: 'action',
data: data,
}),
})Client to NUI
// In NUI
window.addEventListener('message', (event) => {
const data = event.data
if (data.type === 'showMenu') {
// Show menu
}
})Async Function
Where fetch is available depends on the context. Client scripts have no
browser or Node.js APIs (JavaScript runtime
manual ).
Server scripts default to Node.js 16, which has no global fetch; add
node_version '22' to fxmanifest.lua or use PerformHttpRequest. NUI pages
run in Chromium and have the browser fetch.
// Server script with node_version '22', or an NUI page
async function fetchData() {
try {
const response = await fetch('https://api.example.com/data')
const data = await response.json()
return data
} catch (error) {
console.error('Error:', error)
}
}