DEV Community

Lois Aleghe
Lois Aleghe

Posted on

Building a Visitor Counter with Lambda, API Gateway, and DynamoDB

This week's session was long, and I'm looking forward to the Infrastructure as Code step. After clicking through the console for hours, I'm curious how much faster this could have been. I haven't used IaC yet, but now I can see the problem it solves.
Here's the path the counter takes: JavaScript → API Gateway → Lambda → DynamoDB

Step 7: JavaScript

Step 7 of the Cloud Resume Challenge is to add a visitor counter that shows how many people have accessed the site. I started with my local file and focused on localStorage and sessionStorage.
My logic, in simple terms:

  • Check if the counter exists in localStorage. If it returns null, set my variable to 0. Otherwise, use the stored value, converted to a number because localStorage stores everything as strings.

  • Check if the counter exists in sessionStorage. If it doesn't, add 1 to the count and set the sessionStorage value to true.

  • Save the count back to localStorage.

  • Finally, check that the HTML element exists, then show the count in it.
    below is my code:

function updateCount(){
  let visitorCounter = localStorage.getItem("counted");
  let visitorSession = sessionStorage.getItem("counted");
  let currentCount;
  if (visitorCounter !== null) {
    currentCount = Number(visitorCounter);
  } else {
    currentCount = 0;
  }
  if (visitorSession === null) {
    currentCount = currentCount + 1;
  }
  localStorage.setItem("counted", currentCount);
  sessionStorage.setItem("counted", true);
  let contentId = document.getElementById("countId");
  if (contentId) {
    contentId.textContent = currentCount;
  }
}

updateCount()
Enter fullscreen mode Exit fullscreen mode

This worked, but there was a catch. localStorage lives in each visitor's own browser, so every person only sees their own visits. It isn't a real visitor count, and that's why steps 8 to 10 exist.

Step 8: Database

I needed somewhere to store a shared count, so I used DynamoDB, a NoSQL database. I created a table with id (String) as the partition key, and set the capacity mode to on-demand. With on-demand, you pay per request, and since this is a resume site, it should cost very little.
The table only needs one item, because I'm only storing one number, which is the count.

Steps 9 and 10: API and Python

Step 9 says not to communicate with DynamoDB directly from my JavaScript. The reason is that JavaScript runs in the visitor's browser, so any credentials in it would be visible to everyone. Instead, API Gateway and Lambda sit in the middle. API Gateway gives my JavaScript a URL to call, and the Lambda function holds the code that talks to the database.

I created the Lambda function first. Lambda can't access DynamoDB unless you allow it, so I copied the table's ARN and added an inline policy to the function's role. It allows exactly two actions: dynamodb:UpdateItem and dynamodb:GetItem. I learned there are many different actions, and I could have used dynamodb:* to allow all of them, but listing only what I need follows least privilege, which is good practice.

For my Lambda code, it checks the request method. If it's POST, it adds 1 to the count. Otherwise, it's a GET, and it just returns the count. The increment happens inside DynamoDB, not in my code, so if two people open the site at the same moment, neither update overwrites the other. I used #c as a stand-in for count because count is a reserved word in DynamoDB.

import json
import boto3

dynamodb = boto3.resource("dynamodb")
table = dynamodb.Table("visitor-counter")

def lambda_handler(event, context):
    method = event["requestContext"]["http"]["method"]

    if method == "POST":
        response = table.update_item(
            Key={"id":"visitors"},
            UpdateExpression="ADD #c :inc",
            ExpressionAttributeNames={"#c":"count"},
            ExpressionAttributeValues={":inc":1},
            ReturnValues="UPDATED_NEW"
        )
        count = int(response["Attributes"]["count"])
    else:
        response = table.get_item(Key={"id":"visitors"})
        count = int(response["Item"]["count"])

    return {
        'statusCode': 200,
        'headers':{'Content-Type': "application/json"},
        'body': json.dumps({"count": count})
    }
Enter fullscreen mode Exit fullscreen mode

The goal is to count a visit once per session, not on every page load, which is why my JavaScript uses sessionStorage. I tested the function in the Lambda console with two test events, one for GET and one for POST. GET left the count alone, and POST increased it by 1.
In API Gateway, I created an HTTP API with two routes, POST /visitors and GET /visitors, and attached my Lambda integration to both.
Then came CORS. Browsers block a web page from calling an API on a different domain unless that API says it's allowed. Since my site is on lois-aleghe-resume.com and the API is on an amazonaws.com address, I had to set it up:

  • Allow-Origin: both of my domains (with and without www)

  • Allow-Methods: GET and POST

  • Allow-Headers: content-type

I copied the invoke URL, added /visitors to the end, and used it in my JavaScript. The final version only sends a POST the first time in a session. After that, it sends a GET, which reads the count without changing it. Finally, I refactored my code into the version below. I replaced my real URL with a placeholder here.

const API_URL =
  "https://xxxx.ca-central-1.amazonaws.com/visitors";

async function updateCount() {
  const counterVal = document.getElementById("countId");
  if (!counterVal) return;

  const alreadyCounted = sessionStorage.getItem("counted");
  const method = alreadyCounted ? "GET" : "POST";

  try {
    const res = await fetch(API_URL, { method: method });
    const data = await res.json();
    counterVal.textContent = data.count;
    sessionStorage.setItem("counted", true);
  } catch (err) {
    console.log("could not load visitor count:", err);
  }
}

updateCount();
Enter fullscreen mode Exit fullscreen mode

Finally, I uploaded the files to my S3 bucket and created a CloudFront invalidation for /*, so the new files appear right away.
This was a lot of technical information and a lot of steps, but that’s all for today!
This is the link to see my updated resume: Updated Resume

Top comments (0)