All snippets
Lua

A small HTTP API inside a FiveM resource

Route GET and POST requests to Lua handlers with SetHttpHandler, with a shared-secret check.

FiveMLuaHTTP

FiveM resources can serve HTTP at http://<server>:30120/<resource-name>/... through SetHttpHandler. The Conflict Roleplay dashboard uses this to act on the live server, for example giving items or kicking players. A route table keeps the handler short, and every request has to send a shared secret, because that port is usually open to the internet.

lua
-- server.lua: set the secret in server.cfg with  set dashboard_token "long-random-value"
local TOKEN = GetConvar("dashboard_token", "")

local function sendJson(res, status, data)
  res.writeHead(status, { ["Content-Type"] = "application/json" })
  res.send(json.encode(data))
end

local routes = {
  GET = {
    ["/health"] = function(_, res)
      sendJson(res, 200, { ok = true, players = #GetPlayers() })
    end,
  },
  POST = {
    ["/players/kick"] = function(body, res)
      local id = tonumber(body.id)
      if not id or not GetPlayerName(id) then
        return sendJson(res, 404, { ok = false, error = "Player not online" })
      end
      DropPlayer(id, body.reason or "Kicked by staff")
      sendJson(res, 200, { ok = true })
    end,
  },
}

SetHttpHandler(function(req, res)
  -- Reject anything without the shared secret before touching a route.
  if TOKEN == "" or req.headers["Authorization"] ~= ("Bearer " .. TOKEN) then
    return sendJson(res, 401, { ok = false, error = "Unauthorized" })
  end

  local handler = routes[req.method] and routes[req.method][req.path]
  if not handler then
    return sendJson(res, 404, { ok = false, error = "Not found" })
  end

  if req.method ~= "POST" then return handler(nil, res) end

  req.setDataHandler(function(raw)
    local ok, body = pcall(json.decode, raw)
    if not ok or type(body) ~= "table" then
      return sendJson(res, 400, { ok = false, error = "Invalid JSON" })
    end
    handler(body, res)
  end)
end)

On the website, call it from server code only, so the token never reaches a browser:

ts
await fetch(`${process.env.FIVEM_SERVER_URL}/jk_dashboard/players/kick`, {
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.FIVEM_AUTH_TOKEN}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({ id: 12, reason: "AFK" }),
});

Leaving TOKEN empty refuses every request, so a missing convar fails safe instead of leaving the API open.

From the projectConflict Roleplay