FaunaDB Counter
In this tutorial I will explain how you can create a counter with FaunaDB and Netlify. This can be used, for example, to count downloads, page visits or likes.
For this tutorial you need to have published your finished website on Netlify.
Set up FaunaDB
- Create your FaunaDB account
- Click on 'NEW DATABASE' to create a new database.
- Enter a name for the database (e.g., the name of your website), select the region classic and click on 'CREATE'.
- Click on 'NEW COLLECTION' and enter the name 'counter'. Leave the other fields on the default value. (You can use a different name, but you must also change it in the code.)
- Click on 'NEW DOCUMENT' and paste the following code into the input field.
{name: "NAME", count: 0}
Replace 'NAME' with the name of your counter and save the document.
- Click on the button 'Security' in the sidebar on the left and click on 'NEW KEY'.
- Select the name of your database, if not already selected, and click on 'SAVE'.
- Copy your Secret Key. Attention: It will only be displayed once.
Set up Netlify
- Go to your website's settings on Netlify.
- Select 'Build & Deploy' from the sidebar and click on 'Environment'.
- Under the 'Environment variables' click on 'Edit variables'

- Enter
FAUNADB_SERVER_SECRET
in the 'Key' input field and your Secret Key from step 8. in the 'Value' input field and save.

Create JavaScript
Do counting in a save environment (Netlify Functions)
Do counting in normal JavaScript
-
Go to the root directory of your website, create a new .json file called
package.json
and paste the following code:
{
"name": "netlify-fauna",
"version": "0.1.0",
"private": true,
"dependencies": {
"faunadb": "^2.13.1"
}
}
- Again, in the root directory of your website: Create a folder called
netlify
and in it subfolder called functions
.
-
Create a new .js file called
read.js
in the newly created subfolder and paste the following code into it:
var faunadb = require('faunadb');
var q = faunadb.query;
exports.handler = (event, context) => {
// get FaunaDB secret key
var client = new faunadb.Client({
secret: process.env.FAUNADB_SERVER_SECRET
})
// get document id and collection name from url
var id = event.path.match(/([^\/]*)\/*$/)[0];
var collection = event.path.replace("/" + id, "").match(/([^\/]*)\/*$/)[0];
// get data from db
return client.query(q.Get(q.Ref(`classes/${collection}/${id}`)))
.then((response) => {
return {
statusCode: 200,
body: JSON.stringify(response)
}
}).catch((error) => {
return {
statusCode: 400,
body: JSON.stringify(error)
}
})
}
This file will be used to retrieve the counter data from the Fauna database.
-
Create a new .js file called
update.js
in the same directory and paste the following code in it:
var faunadb = require('faunadb')
var q = faunadb.query
exports.handler = (event, context) => {
// get FaunaDB secret key
var client = new faunadb.Client({
secret: process.env.FAUNADB_SERVER_SECRET
});
// get document id and collection name from url
var id = event.path.match(/([^\/]*)\/*$/)[0];
var collection = event.path.replace("/" + id, "").match(/([^\/]*)\/*$/)[0];
// get data from db
return client.query(q.Get(q.Ref(`classes/${collection}/${id}`))).then((current) => {
// update counter
var data = {
count: JSON.parse(JSON.stringify(current)).data.count + 1,
date: new Date()
}
data = JSON.parse(JSON.stringify(data));
// update data in db
return client.query(q.Update(q.Ref(`classes/${collection}/${id}`), {data}))
.then((response) => {
return {
statusCode: 200,
body: JSON.stringify(response)
}
}).catch((error) => {
return {
statusCode: 400,
body: JSON.stringify(error)
}
})
});
}
This file will be used to count and update the counter data.
-
Create a new .js file in your preferred JavaScript directory and paste the following code in it:
// read db
var read = (id, collection) => {
return fetch(`/.netlify/functions/read/${collection}/${id}`, {
method: 'POST',
}).then(response => {
return response.json();
})
}
// update db
var update = (id, collection) => {
return fetch(`/.netlify/functions/update/${collection}/${id}`, {
method: 'POST',
}).then(response => {
return response.json();
})
}
// ###########################################################
// set id and collection name of counter
var id = "REF_NUMBER";
var collection = "counter";
// show counter in html
Promise.resolve( read(id, collection) ).then( function(value) {
try {
document.getElementById("show_counter").innerHTML = value.data.count;
}
catch (e) {
console.log("Counter isn't shown on page");
}
});
// update counter
function updateCounter() {
update(id, collection)//.then((value) => { console.log(value); });
}
This file will handle all the front-end code.
-
Create a new .js file called
update.js
in the same directory and paste the following code in it:
var faunadb = require('faunadb')
var q = faunadb.query
exports.handler = (event, context) => {
// get FaunaDB secret key
var client = new faunadb.Client({
secret: process.env.FAUNADB_SERVER_SECRET
});
// get document id and collection name from url
var data = JSON.parse(event.body);
var id = event.path.match(/([^\/]*)\/*$/)[0];
var collection = event.path.replace("/" + id, "").match(/([^\/]*)\/*$/)[0];
// update data from db
return client.query(q.Update(q.Ref(`classes/${collection}/${id}`), {data}))
.then((response) => {
return {
statusCode: 200,
body: JSON.stringify(response)
}
}).catch((error) => {
return {
statusCode: 400,
body: JSON.stringify(error)
}
})
}
This file will be used to update the counter data.
-
Create a new .js file in your preferred JavaScript directory and paste the following code in it:
// read db
var read = (id, collection) => {
return fetch(`/.netlify/functions/read/${collection}/${id}`, {
method: 'POST',
}).then(response => {
return response.json()
})
}
// update db
var update = (id, collection, data) => {
return fetch(`/.netlify/functions/update/${collection}/${id}`, {
body: JSON.stringify(data),
method: 'POST'
}).then(response => {
return response.json()
})
}
// ###########################################################
// set id and collection name of counter
var id = "REF_NUMBER";
var collection = "counter";
// get counter from db
var counter
Promise.resolve( read(id, collection) ).then( function(value) {
counter = value.data.count;
// show counter in html
try {
document.getElementById("show_counter").innerHTML = counter;
}
catch (e) {
console.log("Counter isn't shown on page");
}
});
// update counter
function updateCounter() {
update(id, collection, {
count: counter + 1,
date: new Date()
})//.then((value) => { console.log(value); });
}
This file will handle all the front-end code and counting.
- Go back to FaunaDB into your 'Database - Collections - counter' and click on the copy icon on the right side of your document.

- In the JavaScript file from step 17 you need to replace the 'REF_NUMBER' with the copied number from step 18.
Modify HTML
- Link the file from step 17 to the HTML file.
- To update your counter, you only need to execute this function:
updateCounter()
For example, with this button: <button onclick="updateCounter()">Like</button>
- To display your counter on the page, add the following code to the HTML:
<span id="show_counter"></span>
- Deploy your website and your counter should work.