Hi there 👋, welcome to my blog, where I share my learnings and tools that might be helpful to you. I wanted to track the reach of my content to help me create even better content!
The idea was simple: I needed to store page-view counts. I could have implemented this using Vercel or Google Analytics, but I decided to go in a different direction for this implementation.
I'll have a website URL-to-count mapping in the database.
So when you visit my blog, I'll store the view count associated with the URL. Simple, right?
It's a Postgres database with a free tier of 512MB storage, which is perfect for my use case. I wanted to try out Postgres, so I gave it a shot. Here are some free Postgres database providers you can try:
Instead of writing raw database queries, using an ORM provides predefined methods to interact with the database. Drizzle generates the Postgres queries needed for table creation and migrations. Here are some popular JavaScript ORMs:
The process is quite simple, we need to build a counter app. I'm using Next.js, a full-stack framework based on React, which lets you write both frontend and backend code in one place. Let's start coding!
Install these dependencies
Let's create drizzle.config.ts file in our root directory, where we can specify path of schema file
Let's define schema for our database👇
Create a method to interact with the database, so we can use it in our API.
Add these script to package.json file for generating database migration files
Now we can push the generated database migration files to NeonDB using this command:
Create the POST method to increment the count in the database. Create an api/views/route.ts file:
The APIs I wrote are public and can be spammed, which can mess up the analytics. I need to rate-limit the API requests 🤔! Since these APIs are public and we don't have an authentication layer, using a secret-key method won’t work. I asked my mentor, and he suggested IP whitelisting.
What is IP Whitelisting?
It's the process of storing the IP address from a user's request, so we can validate it for future requests. I had two options to tackle this:
Store the data in my database, but there’s no automatic way to clear the database entries after some time.
Use something that can store data and automatically delete it after a period of time.
Redis
Redis is an in-memory data store often used for caching, providing high-speed data access with the ability to automatically expire data after a specified duration. Here are few providers who're providing free tier Redis
I choosed upstash, it has 10,000 commands free daily, now storing data in redis is simple it's like storing data with JSON pair. Similar like react-query setQueryData & getQueryData. Here is the example for rate-limiting
Let's create a method to interact with the redis database
Now let's rate limit our POST method
So yeah everything came out well, so what's next i need to add comments to blog😅.