How to make an external database using a Replit Database [OUTDATED]

I’ll be explaining how to get and set data using an express server that uses replit databases.

don’t flame my nodejs code i’m new to js


Why should I do this?

  • Perhaps you want to modify and get data using discord bots
  • Or you just want more control over your data

In order to do this you need:

  • Replit Account
  • Basic knowledge of roblox scripting

Note that roblox ONLY allows up to 500 HTTP Requests per minute.


Repl:

First of all start by making a new repl

image

Then select Node.js

Once you done that simply press on Create Repl

Then a page should open with a file called index.js, simply paste this.

const Database = require("@replit/database")
const db = new Database()

const express = require('express');

const app = express();
const bodyParser = require('body-parser');

app.use(bodyParser.json());

app.get('/', (req, res) => {
  res.send('hello')
});

app.post('/getData', (req, res) => {
  if (req.headers && req.headers["authorization"] && req.headers["authorization"] === process.env.authorization) {
    if (req.body["key"]) {
      db.get(req.body["key"]).then(data => {
        if (data === null) {
          res.send({success: true, data: "{}"}) 
        } else {
          res.send({success: true, data: data})
        }
      })   
    } else {
      res.send({success: false, data: "Body did not contain a key"})
    }
  } else {
    res.send({success: false, data: "Forbidden 403"})
  }
})

app.post('/setData', (req, res) => {
  if (req.headers && req.headers["authorization"] && req.headers["authorization"] === process.env.authorization) {
    if (req.body["key"] && req.body["data"]) {
      db.set(req.body["key"], req.body["data"]).then(() => {})

      res.send({success: true})
    } else {
      res.send({success: false, data: "Body did not contain a key or a data value"})
    }
  } else {
    res.send({success: false, data: "Forbidden 403"})
  }
})

app.listen(3000, () => {
  console.log('server started');
});

After that, go on the right and find the + and click on it.

image

And now press on Secrets after you find it

image

Press on Create Secret

After that just press Add Secret after you put a key that you actually remember.

Hopefully you are keeping track, after that just press “Run”

image

If there is un-installed packages, wait for replit to install them and wait for a “Webview” tab to open up.
And once you do that copy the URL over here.

image

Roblox Studio:

Start by opening up a published place that has HTTP Requests enabled (you can find this in the game settings)

Make a script in ServerScriptService and call it whatever you want, after doing that paste this into the code and configure it.

-- written by @notaisar on discord

local HttpService = game:GetService("HttpService")

local dataServerURL = "put here the URL that you copied"; -- IF THERE IS A / AT THE END, REMOVE IT.

local dataHeaders = {
	["authorization"] = "put the SECRET that you made in replit here"
}

function CheckTableEquality(t1,t2)
	for i,v in next, t1 do if t2[i]~=v then return false end end
	for i,v in next, t2 do if t1[i]~=v then return false end end

	return true
end

local startingData = {}

game:GetService("Players").PlayerAdded:Connect(function(player)
	local httpConnection = HttpService:PostAsync(dataServerURL.. "/getData", HttpService:JSONEncode({key = "Player_" .. player.UserId}), Enum.HttpContentType.ApplicationJson, nil, dataHeaders)

	local request;
	local requestSuccess;

	if httpConnection then
		requestSuccess, request = pcall(HttpService.JSONDecode, HttpService, httpConnection)
	end

	if requestSuccess then
		local parsed, data = pcall(HttpService.JSONDecode, HttpService, request.data)

		if parsed then
			if request.success and data then
				if CheckTableEquality(data, {}) then
					-- DATA IS EMPTY

					data = {
						Coins = 0;
					}

					-- RECONCILED DATA
				end

				startingData[player] = data;

				local leaderstats = Instance.new("Folder")
				leaderstats.Name = "leaderstats"
				leaderstats.Parent = player

				for dataName, dataValue in pairs(data) do
					local value = "StringValue"

					if typeof(dataValue) == "number" then
						value = "NumberValue"
					elseif typeof(dataValue) == "boolean" then
						value = "BoolValue"
					end

					local dataInstance = Instance.new(value)
					dataInstance.Name = dataName
					dataInstance.Value = dataValue
					dataInstance.Parent = leaderstats
				end
			else
				warn("DataManager: COULD NOT LOAD ".. player.Name .." (" .. player.UserId ..") RETURNING INFO WAS " .. (request.data and request.data or "null") .. ".")

				player:Kick("Met with an error while retrieving your data.")
			end
		else
			player:Kick("Could not correctly parse your JSON data.")
		end
	else
		player:Kick("Could not retrieve your data.")
	end
end)

game:GetService("Players").PlayerRemoving:Connect(function(player)
	local endingData = {}

	for _, v in pairs(player:WaitForChild("leaderstats"):GetChildren()) do
		endingData[v.Name] = v.Value;
	end

	if CheckTableEquality(startingData[player], endingData) then
		warn("not saving data due to it not changing")

		return
	end

	endingData = HttpService:JSONEncode(endingData)

	local httpConnection = HttpService:PostAsync(dataServerURL.. "/setData", HttpService:JSONEncode({key = "Player_" .. player.UserId, data = endingData}), Enum.HttpContentType.ApplicationJson, nil, dataHeaders)

	local request;
	local requestSuccess;

	if httpConnection then
		requestSuccess, request = pcall(HttpService.JSONDecode, HttpService, httpConnection)
	end

	if requestSuccess and not request.success then
		warn("DataManager: had an error while saving ".. player.Name .. " (" .. player.UserId ..")'s data message was ".. (request.data and request.data or "null"))
	elseif not requestSuccess then
		warn("DataManager: had an error while saving ".. player.Name .. " (" .. player.UserId ..")'s data message was " .. (request and request or "null"))
	end
end)

And like that, you should have a working replit database system.

If you couldn’t understand or the code errors, reply to this topic with your issue.

Hopefully this helps anyone.

5 Likes

This shouldn’t be used for big games by the way, Replit has some small storage of 50MB.

1 Like

I’m not new to JavaScript yet I’m not very familiar with node(.js) and its modules.

Just wondering what the express module does.

Express is basically a way to host an API or a web server, it’s used for many big API’s and stuff.

2 Likes

A better alternative is Supabase and possibly finding elsewhere to host your express server :happy3:

Just to let ya know, Replit has a bandwidth limit so don’t use replit for big games

also It reminds me of when someone uses GitHub Gist for database

also why would you theme your avatar after a steam emote?

image

yeah i already said that it shouldn’t be used for big games

the answer to your question is, steam happy is adorable.

2 Likes

Thank you, I’ll try it out in a bit.

1 Like

Hi i am trying to figure out how i can get ‘hello’ in index.js with the database

elaborate on what you mean? please

I just need some way to get the variable. So like that i can print(console.log) and do other stuff

What did I wrong?

This tutorial is outdated since replit changed their web-hosting services.

1 Like