In this article, we will build a Serverless Next.js based TODO application. We will try our best to make it minimalist. It will not have any database connection. It will not have any extra dependency other than Next.js. It will not have any buttons. Besides,
minimalism is cool and clean, I love it because I am a lazy developer :)
Next.js is a modern framework which enables the front-end developers to develop full stack applications. Serverless functions have an important role in simplifying backend development for Next.js developers. As you probably know, serverless functions do not like database connections due to their stateless nature. See here and here as examples of problems of database connections inside serverless functions.
REST allows client and server to communicate with no session information. This statelessness and its simple nature makes REST a perfect communication protocol for serverless environments. We will access Upstash Redis with REST.
See the demo: https://nextjs-todo-zeta.vercel.app/
Create a Next.js app:
Create an Upstash Redis database in AWS-US-EAST-1 region and copy the REST URL and token.
The project will be a single page application with 3 API endpoints:
- pages/api/list.js: Lists the TODO items.
- pages/api/add.js: Adds a TODO item.
- pages/api/remove.js: Removes a TODO item.
Add pages/api/list.js as below:
Add pages/api/add.js as below:
Add pages/api/remove.js as below:
Update pages/index.js as below:
As you see, it is a basic React application which uses hooks. We have 3 methods which interact with APIs: addTodo, removeTodo and loadTodos.
And finally update the styles/Home.module.css file as here.
Run your project locally with
npm run dev. If everything looks good, you can deploy your project by running
vercel in the project folder. Vercel will create serverless functions for your API functions. The default region for Vercel functions is US-EAST-1, that’s why we created our database in the same region.
- It is safer to keep the database token in a Vercel environment variable.
- It is best for performance to keep the serverless function and Redis database in the same region.
- We could use Redis clients instead of REST API. But as I mentioned before, the database connections can cause issues inside serverless functions. Also note that we did not see a major performance difference between Upstash REST API and native API.