Back to blog
Blog

Build a ToDo app powered by Cosmic and React Server Actions

Tony Spiro's avatar

Tony Spiro

May 20, 2024

cover image

In this article, we're going to build the quintessential application for demonstrating CRUD (Create, Read, Update, Delete) capabilities, a ToDo app using React Server Actions and the Cosmic CMS API.

By using the Cosmic CMS API to store our ToDo tasks and React Server Actions to update the tasks we will be able do all client-side interactions without exposing any endpoints or API keys. And our tasks will be saved in Cosmic which we could then use in any website or application using the Cosmic API. Let's get into it.

TL;DR

View the ToDo app live demo

Check out the ToDo app code on GitHub

Getting started

First, install a fresh Next.js project.


Select the following options:

project-options.png

Install the Cosmic JavaScript SDK.


Create a new file located at with the following code:


Create Project in Cosmic

Log in to the Cosmic dashboard and create a new empty Project.

Create Project

Create an Object type with slug :

Create Object Type

Add the switch Metafield with key .

Add completed Metafield

Create a new file. And add your API keys found in the Cosmic dashboard at Project / API keys.


Code the ToDo logic

Create a new file in with the following code.


There is a bit going on in this file, but the main thing to understand is that this file has the directive at the top of the page which tells Next.js to render this code to the client.

All of the hook actions for , , and interacts with the React Server Actions located in the folder.

React Server Actions

To make our ToDo list data interactive with React Server Actions, create a new file located at with the following:


Notice the directive at the top of the page which tells Next.js to only render this code on the server. Even though these functions are being called in the client component, the code from the Server Action is kept securely private on the server.

The magic happening here is "When calling a Server Action on the client, it will make a network request to the server that includes a serialized copy of any arguments passed." as noted in the React docs.

Next, create the form component in with the following code:


Put it all together in the file.


Notice that we set so that our data is the most up to date on page load. And we fetch the initial ToDos using the action.

Now run the app:


Open up your browser to and see the ToDo app. Add / update / delete ToDo tasks and see them available in the Cosmic dashboard.

Next steps

I hope you enjoyed this example of using React Server Actions and the Cosmic CMS to create a ToDo application that keeps your API access secure. For more information on Cosmic capabilities, go to the Cosmic documentation and react out to us on X (fka Twitter).