Skip to Content
ScriptingFirst Resources by LanguageYour First FiveM JavaScript Resource and Vehicle Demo
Report an error
Open in ChatGPTOpen in Claude

Build a JavaScript resource

FiveM client JavaScript is a game scripting runtime, not a browser and not unrestricted Node.js. The official JavaScript starter  introduces manifests, commands, native calls and a vehicle spawner. Use a private development server where you can already connect and spawn.

Files and execution sides

Create resources/[local]/doc_js_first/fxmanifest.lua:

fx_version 'cerulean' game 'gta5' client_script 'client.js' server_script 'server.js'

Create server.js:

console.log('[doc_js_first] server started'); RegisterCommand('docservercheck', (source) => { if (source !== 0) return; console.log('[doc_js_first] server-console command received'); }, true);

Client files are downloaded to players, so keep secrets and privileged state out of them. Browser APIs belong in a declared NUI page; Node filesystem/network APIs belong only in the supported server runtime. Use manifest entries to declare dependencies and files deliberately.

A client command with bounded model loading

Create client.js with the following complete example. It owns at most one non-networked demo vehicle; this is not a production purchase command or a server-authorized entity creation API.

// example: first-js-vehicle const delay = (milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds)); let vehicle = 0; let loading = false; let generation = 0; function removeDemo() { if (vehicle !== 0 && DoesEntityExist(vehicle)) DeleteEntity(vehicle); vehicle = 0; } RegisterCommand('docremove', removeDemo, false); RegisterCommand('docvehicle', async (_source, args) => { if (loading) return; const name = args[0] ?? 'adder'; if (typeof name !== 'string' || name.length > 64) return; const model = GetHashKey(name); if (!IsModelInCdimage(model) || !IsModelAVehicle(model)) { console.log('Choose a vehicle model available in this build.'); return; } loading = true; const requestGeneration = generation; const startedAt = GetGameTimer(); try { RequestModel(model); while (!HasModelLoaded(model)) { if (generation !== requestGeneration || ((GetGameTimer() - startedAt) >>> 0) >= 10000) { console.log('Model loading was cancelled or timed out.'); return; } await delay(50); } if (generation !== requestGeneration) return; const ped = PlayerPedId(); if (ped === 0 || !DoesEntityExist(ped)) return; const [x, y, z] = GetEntityCoords(ped); const [dx, dy, dz] = GetEntityForwardVector(ped); removeDemo(); vehicle = CreateVehicle(model, x + dx * 5, y + dy * 5, z + dz * 5, GetEntityHeading(ped), false, false); if (vehicle === 0 || !DoesEntityExist(vehicle)) { vehicle = 0; console.log('Vehicle creation failed.'); return; } SetPedIntoVehicle(ped, vehicle, -1); console.log('Local demo created. Use docremove to delete it.'); } catch (error) { removeDemo(); console.error('Vehicle demo failed:', error instanceof Error ? error.message : 'unknown error'); } finally { SetModelAsNoLongerNeeded(model); loading = false; } }, false); on('onResourceStop', (resource) => { if (resource !== GetCurrentResourceName()) return; generation += 1; removeDemo(); });

The example validates first, waits cooperatively with a deadline, reads the current position, creates the vehicle, seats the player and releases the requested hash in finally. JavaScript vectors returned by these natives are unpacked arrays here, not Lua vector userdata. The delay helper is a local constant; do not create an accidental global such as Delay = ....

The final two vehicle flags are false for this local-only exercise. Other clients do not receive an authorized server vehicle. A networked server feature needs permission checks, server-owned records, entity/owner validation and restart behavior; see secure events.

Run and diagnose the resource

In the server console, run refresh and ensure doc_js_first. Observe the server log and connect a client. In F8, run docvehicle adder, then docremove. An invalid model must exit without starting a load request. A valid but unavailable model must stop at the deadline. Repeating the command during loading must not start parallel requests.

After editing, run restart doc_js_first or ensure doc_js_first. Test resource stop both with a visible vehicle and while loading. An unrelated resource stopping must not delete the demo. Choose an open test area; the position five units ahead does not guarantee a safe spawn surface.

A timeout abandons the scripting operation; it is not a guarantee about the exact frame or external transport cancellation. The finally block releases the model reference, while removeDemo deletes only the tracked entity. Do not delete arbitrary nearby vehicles during cleanup.

Gametypes, chat and server events

The upstream gametype example uses onClientGameTypeStart, automatic spawning and a chat message. These require the actual mapmanager, spawnmanager and chat providers. Declare dependencies and follow stock resource setup; do not install an additional spawn owner over a framework’s character selector.

Use on/emit for local events and onNet/emitNet across the network. Server emitNet needs a recipient; client emitNet does not. Save global.source before asynchronous server work and revalidate the session before replying. The JavaScript event reference supplies a bounded client/server example, and async interoperability covers server I/O scheduling.

What the tests establish

The published client block is executed with deterministic mocked natives to check invalid models, success, duplicate requests, deadlines, cleanup and resource-stop handling. Those tests do not run GTA streaming, physics or networking. Complete the client checks above before adapting the example into a game feature. Stop the resource and remove its development startup entry after the exercise.