In this post, I'll show you how to add a view counter to your Next.js blog using Upstash Redis. We'll focus on two main goals: (1) displaying the number of views for each blog post, and (2) incrementing the view count each time someone visits a page. This builds on my previous post. Let's dive in and enhance your blog with this interactive feature!
In the REST API section, click the .env button to copy your environment variables.
Configuring Upstash
Install the Upstash Redis package in your Next.js app:
Implementing the View Counter
Create an API route to handle saving user visits in the Redis database:
/app/api/increment/route.ts
This API route does the following:
Extracts the slug from the request body.
Hashes the visitor's IP address for privacy.
Uses Redis to deduplicate views based on the hashed IP and slug.
Increments the view count only for new views *not seen in the last 24 hours.
Redis provides two key commands that make this process efficient:
SET with the NX option: Sets a key only if it doesn't exist, perfect for deduplication.
INCR: Atomically increments a counter, ideal for tracking views.
Redis provides two key commands that make this process efficient:
Reporting Views
Create a client-side component to call the API when a user visits a blog post:
/app/blog/[...slug]/report-view.tsx
Displaying View Count
Create another component to fetch and display the view count for each blog post:
/app/blog/[...slug]/show-view.tsx
Import and use these components in your blog post page:
/app/blog/[...slug]/page.tsx
Folder Structure
route.ts
page.tsx
report-view.tsx
show-view.tsx
page.tsx
That's it! You've successfully implemented a view counter in your Next.js application. The view count will increment once every 24 hours per unique visitor for each blog post, and the updated count will be displayed on the page.