Mar 3, 2024
Adding analytics to your website.
Adding analytics using NextJS and Redis.
#Step-by-Step Tutorial: Adding Website Analytics using Redis and TypeScript in Next.js
In this tutorial, we'll walk through the process of integrating website analytics into a Next.js portfolio blog using Redis and TypeScript. Website analytics help track page views, visitor locations, and timestamps, providing valuable insights into user engagement.
#Prerequisites
Before we begin, ensure you have the following:
- Node.js and npm: Make sure you have Node.js and npm installed on your machine.
- Next.js Project: Set up a Next.js project with TypeScript.
- Redis: Redis should be installed and running locally or accessible via a Redis service.
#Step 1: Setting Up Redis Configuration
Redis is a powerful in-memory data store that we'll use to store our website analytics data. We'll start by configuring Redis for our Next.js project.
In this code:
- We import the
Redis
class from the@upstash/redis
package. - We create a new instance of
Redis
, passing in the Redis URL and authentication key obtained from your Redis provider.
#Step 2: Implementing Analytics Tracking
Now, let's implement the functionality to track page views and retrieve analytics data.
Here:
- We define functions to track page views (
trackPageView
) and retrieve page view data (getPageViews
) from Redis. - When tracking a page view, we store the page URL, country (if available), and timestamp in a JSON format in a Redis list.
- When retrieving page views, we fetch the data from the Redis list and parse each page view event.
#Step 3: Adding Middleware for Tracking
Next, let's add a middleware to track page views on each request to our Next.js application.
Here:
- We define a middleware that intercepts incoming requests and tracks the page view using the
trackPageView
function we defined earlier. - We use
req.geo?.country
to get the country of the visitor, if available, and pass it to thetrackPageView
function along with the page URL.
#Step 4: Displaying Analytics Data
Finally, let's create a page to display the analytics data retrieved from Redis.
In this code:
- We fetch page view data from the server using the
getPageViews
server action and set it in the component's state. - We use React's
useEffect
hook to fetch page views when the component mounts. - We render the page view data in a list format, displaying the page URL, country, and timestamp for each page view event.
#Conclusion
Congratulations! You've successfully integrated website analytics using Redis and TypeScript into your Next.js project. This implementation allows you to track page views, visitor locations, and timestamps, providing valuable insights into user engagement. Feel free to customize and expand upon this implementation to suit your specific requirements and analytics needs.