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
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)
}
}