Can't detect players leaving the game when the server script is in PlayerGui?

So I have a huge issue, I’m trying to make it so when the player leaves the game, a bool value saves. BUT no matter what I tried, the script won’t detect the player leaving nor events being able to tell it to do something.

What I’ve tried: make another server script send an event to the script in the PlayerGui when a player leaves, letting the server script detect when a player leaves, and detecting when the player leaves by parent. None work

How would I fix this???

game.Players.PlayerRemoving:Connect(function(player)
	print("recieved")
	local userid = player.UserId
	local Data = keep.Value
	local success, errormessage = pcall(function()
		KeepData:SetAsync(userid, Data)
	end)
end)

I don’t wanna change the saving system to be done in ServerScriptService as moving all of it/changing all the systems would take to long so is there another way to do this???

its a very bad idea to put server scripts in startergui so you should probably move it

i also found that you can set the RunContext to Server instead of Legacy and it seems to work
its also going to run again every time the player respawns so it could cause some massive lag and issues

Never ever ever put a script for storing player data in a place like StarterGui or just in general only local scripts should go in there. Move it to server script service and that will save you a ton of future headaches