If you are looking for an easy and efficient way to add simple real-time page views to your Next.js website then you’re reading the perfect how-to article on this subject. Now, I’ll teach you how to add real-time page views to your Next.js website using Turso and Drizzle ORM.
# What is Turso?
Introducing Turso, the SQLite edge database that will revolutionize your website. Built on the powerful libSQL framework, Turso offers a mind-blowing free-forever plan, providing a whopping 8 GB of total storage and the ability to have up to 3 databases in 3 different locations. Prepare to have your expectations shattered!
# What is Drizzle ORM?
Drizzle ORM, a cutting-edge object-relational mapping library designed specifically for Node.js and TypeScript applications. This powerhouse brings support for multiple databases, migrations, and query building. It’s like having a supercharged engine under the hood of your website!
# Setup Turso database
- Install the Turso CLI (For more options Click here):
- Sign up to Turso:
- Create a new database
- Get the URL of your database (Starts with
- Access your database shell:
- Create a new table for
- Create an
- Now inside
.envfile, add the following:
# Connect Next.js to Turso
In order to connect our site to the database, we need to use Drizzle ORM. All we have to do is install couple of packages and set them up.
- Install Drizzle ORM and libSQL client:
- Create a file
lib/turso.tsto initialize your Turso client
- Now we create
app/api/views/[slug]/route.tsand use it to increment and fetch page views
- Finally, we create
ViewCounter.tsxcomponent to display the page views which we can use in our blog posts
Now we have a working page views counter that is connected to our Turso database. You can use this method to add page views to any website that is built with Next.js.