In this tutorial we will write a single page application which uses Redis as state store in a Next.js application.
The example is a basic roadmap voting application where users enter and vote for feature requests. You can check the complete application in Upstash Roadmap page
We will use Next.js as web framework. So let's create a next.js app and install the redis client first.
npx create-next-app nextjs-with-redis
npm install ioredis
Our application will be a single page. We will list the features with their order of votes. There will be 3 actions available for the page user:
- The user will suggest a new feature.
- The user will vote up an existing feature.
- The user will enter their email to be notified of a release of any feature.
The below are the parts that handles all those. If you want to check the full page see here
With Next.js, you can write server-side APIs within your project. We will have 4 apis:
- list features
- vote a feature
- add a new feature
- add email
Now let's examine these API implementations:
The list API connects to the Redis and fetches feature requests ordered by their scores (votes) from the Sorted Set
This API connects to the Redis server and add a new element to the sorted set (roadmap) . We use "NX" flag together with ZADD, so a user will not be able to overwrite an existing feature request with the same title.
This API updates (increments) the score of the selected feature request. It also keeps the IP addresses of the user to prevent multiple votes on the same feature request.
This API simply adds the user's email to the Redis Set. As the Set already ensures the uniqueness, we only need to check if the input is a valid email.
- If you deploy this application with Vercel; Vercel runs AWS Lambda functions to back the API implementations. For best performance choose the the same region for both Vercel functions and Upstash cluster.
- You can access your database details via Upstash Console