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

  1. Create your FaunaDB account
  2. Click on 'NEW DATABASE' to create a new database.
  3. Enter a name for the database (e.g., the name of your website), select the region classic and click on 'CREATE'.
  4. 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.)
  5. 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.
  6. Click on the button 'Security' in the sidebar on the left and click on 'NEW KEY'.
  7. Select the name of your database, if not already selected, and click on 'SAVE'.
  8. Copy your Secret Key. Attention: It will only be displayed once.

Set up Netlify

  1. Go to your website's settings on Netlify.
  2. Select 'Build & Deploy' from the sidebar and click on 'Environment'.
  3. Under the 'Environment variables' click on 'Edit variables'
  4. 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

Modify HTML

  1. Link the file from step 17 to the HTML file.
  2. To update your counter, you only need to execute this function: updateCounter()
    For example, with this button: <button onclick="updateCounter()">Like</button>
  3. To display your counter on the page, add the following code to the HTML:
    <span id="show_counter"></span>
  4. Deploy your website and your counter should work.