How can I make my DataStore script more secure?

I have a basic script (please don’t judge me I used the wiki to make this)

local ds = game:GetService("DataStoreService")
local plrs = game:GetService("Players")

local goldDataStore = ds:GetDataStore("goldDataStore")

plrs.PlayerAdded:Connect(function(plr)
	local key = plr.UserId.."-gold"
	
	local leaderstats = Instance.new("Folder")
	leaderstats.Name = "leaderstats"
	leaderstats.Parent = plr
	
	local gold = Instance.new("IntValue")
	gold.Name = "Gold"
	gold.Parent = leaderstats
	
	local goldNewValue
	
	local success,data = pcall(function()
		goldNewValue = goldDataStore:GetAsync(key)
	end)
	
	if success then
		gold.Value = goldNewValue
	else
		print(data)
	end
end)

plrs.PlayerRemoving:Connect(function(plr)
	local key = plr.UserId.."-gold"
	
	local leaderstats = plr.leaderstats
	local gold = leaderstats.Gold
	
	local success,data = pcall(function()
		goldDataStore:UpdateAsync(key,function(oldValue)
			return gold.Value
		end)
	end)
	
	if data ~= nil then
		print(data)
	end
end)

I tested it out and it works. I was just wondering on how to make it better. If you see mistakes, please point it out. Thanks

The first thing I noticed in your code is that you’re trying to save player’s data when the player leaves by using the data saved in leaderstats which is not a great way to do it because there is a chance that player object can get garbage collected before the script can save the data in leaderstats to datastore which would cause a data loss.

You should save player’s data in separate valuebase objects that are located in either serverscriptservice or server storage so when player leaves you can just let the script do it’s job and not worry about potential data loss.

Do you mean like making a leaderstats script and a datastore script?

I mean creating a dedicated player data folder in serverstorage along with leaderstats when player joins and get the data from server storage when player leaves so player object getting garbage collected wouldn’t cause data loss.

Like this:
image

2 Likes

So it would be like creating 2 copies of data, one in the players service and the other in the ServerStorange Service, to save the ServerStorange data, and to make sure the PlayersService data is a “Display” of the ServerStorange data and that the values ​​are modified there?.

(One thing aside) sorry if I say some things wrong, the truth is I don’t speak English but I had that doubt