Build a Todo app with Next.js 13 and Prisma
Using Hanko Auth for a Todo app with Next.js 13 and Prisma
In this tutorial, you’ll learn how to build a Todo app with the Next.js 13 popular “App Router” structure and understand some of the most important changes that come with it. We will build a fully functional todo app, handling the creation, updating when completed and the option to delete the todos.
Let’s set it up
At Hanko, we understand that finding the right stack for the project is a big step. In this guide, we will bring Next.js as the main character of the project, we will test the Client vs Server Components. For the style, we will use Tailwind CSS. We will use Hanko for the login and registration, user management and logout. Prisma will handle the storage.
Initialize the Next.js app
To create a new Next.js app, we can use the create-next-app
or create-next-app@latest
command-line tool followed by the name of your choice for the app. Open your terminal in Visual Studio Code and run the following command:
Then you’ll be asked some prompts on what you will use for the app. The project configuration options should look something like this:
The above choices will create a new Next.js app with the chosen name, all the required dependencies for this project will also be installed.
Understanding the project structure
When using the version 13 of Next.js, we have the option to work with the App Router directory instead of the Pages Router, for a quick summary we could say that:
- The new directory named “app” is replacing “pages”
- “page.tsx|page.jsx” is the new “index.tsx|index.jsx”
- “layout.tsx” is the new “_app.tsx”
- Everything is a Server Component unless you make it a Client Component using the “use client” directive at the top of the file.
- API Routes are now Server Components or Route Handlers (… More info on how this is very important)
Remove unnecessary files, such as logos, icons, etc. If you are going to use Tailwind CSS make sure to bring your desired configuration to the tailwind.config.ts
file, defining your color palette, fonts, breakpoints, etc.
For more information about the App Router of Next.js click here.
Setting up Prisma
Install the Prisma CLI as a development dependency in the project:
Set up Prisma with the init command of the Prisma CLI:
This creates a new prisma
directory with your Prisma schema file and configures SQLite as your database. Once we also create the “Todo” model, the Prisma schema file should look like this:
At this point, you have a Prisma schema but no database yet. Run the following command in your terminal to create the SQLite database and the Todo table:
This command did two things:
- It creates a new SQL migration file for this migration in the
prisma/migrations
directory. - It runs the SQL migration file against the database.
Because the SQLite database file didn’t exist before, the command also created it inside the prisma
directory with the name dev.db
as defined via the environment variable in the .env
file.
To prevent problems when instantiating PrismaClient, on the Prisma Docs there’s a section dedicated to the best practice to do it. Let’s try it by creating a db.ts
file in the root of the app and add the following code inside:
For more information about Prisma integration click here.
Building the user interface
The goal is to build a simple “todo app” with a nice login to protect the todos, for this we will only need two pages:
- The login page where the Hanko-auth component will play its part in handling authentication.
- The todo page where all the todos will be displayed.
App structure
In the App Router directory, the page.tsx
is like the new index.tsx
, which means that this name will play an important role when creating a new route. You can define a page by exporting a component from a page.tsx
file.
Now you can update the page.tsx
file to display “Hello World” as done below.
We will get back to it later to add a nice login with Hanko.
The Todo page
We will style this page using Tailwind CSS classes to create a centered container to display the todos. We need a form with an input to create the new todos, and every todo element will have a checkbox and a delete button. Inside the app
directory, create a new todo
folder with a page.tsx
file inside of it. Use the code below as the todo/page.tsx
contents:
For a better understanding of the Tailwind CSS classes click here.
Todos in the making
To make our app functional, we need to be able to create a new todo, then check the todo once it’s completed and finally be able to remove a single todo from the list.
API Routes in Next.js 13
What we know as API Routes are replaced by Route Handlers and they are defined in a route.ts|js
file inside the app
directory. Read more about the Route Handlers in the Next.js Docs.
Inside the app
directory create an api
folder. We will group our Route Handlers as follows: one directory todo
with a route.tsx
which will contain the POST
HTTP method handler for creating a new todo, and in that same directory we will use a dynamic route to GET
and DELETE
todos. Should look like the following example:
New Todo
This is a good moment to start breaking it down into components, let’s first create a components
folder at the root directory, then create a components/todos/NewTodo.tsx
file and use the following as its contents:
This is a good example of where to use the “use client” directive since we are using useState()
and subscribing to interactive events.
This is how we call Prisma to create the todo inside the api/todo/route.ts
Route Handler:
By default, Next.js uses Server Components, thanks to that we can now call Prisma from the todo/page.tsx
file to get all our todos, then we pass them to our components/todos/TodoItem.tsx
file to be displayed. This is how the todo/page.tsx
should look after our changes:
Client Components themselves cannot be async functions (official FAQ). Prisma will break the app if you try to call it inside a Client Component.
Update and Delete todo by ID
In the next step, we need a way to handle marking a todo as completed and to handle the deletion of a todo. Accordingly, we create update
and delete
functions that fetch our dynamic route. This would be the components/todos/TodoItem.tsx
file:
Add the following code inside the api/todo/[id]/route.tsx
Route Handler:
For more information on the Prisma Client Api click here.
Authentication with Hanko
Now is time to start working on the security.
Hanko Cloud setup
Visit Hanko Cloud and create an account. Then create an organization to manage your Hanko project.
Then create a new project and set the App URL to your development URL (example: http://localhost:3000):
And that’s all! Now you can always return to your Hanko Cloud dashboard to see your API URL and other insights about your project, you can also change the app URL in the settings, so that once you want to move from “development” to “production”, you can change it to a proper domain/URL. Take the time to discover all the features.
Adding Hanko to the Next.js app
Let’s bring Hanko to the game by installing the @teamhanko/hanko-elements
package running the code below:
First, let’s update our “Home” page and rename the function to “Login”. Import the register function from @teamhanko/hanko-elements
, and call the function with the Hanko API URL as an argument to register the <hanko-auth>
. Now include it in your JSX:
The code snippet above should display the Hanko authentication component:
The <hanko-profile>
component offers a page for managing email addresses and passkeys. Let’s create a profile button component by creating a file components/Profile.tsx
and use the following code as its content:
It should look like this:
Now let’s use @teamhanko/hanko-elements
to manage user logouts by creating a logout button component. Create a file components/Logout.tsx
and use the following as its content:
When a user logs out, a specific event is triggered that you can subscribe to, like redirecting to a specific page after logout:
Verifying JWT with jose library
Hanko issues a cookie after a successful login. The value of this cookie is a JWT and to secure our app we still need to verify the JWT.
What are JWTs? > A JSON Web Token (JWT) is a compact and self-contained way for transmitting information between parties as a JSON object in a secure way. The purpose of a JWT is to ensure the authenticity of the data. Hanko handles the authentication and signing of the JWT. On successful authentication with Hanko a cookie, which contains said JWT as its value, is set. We don’t really need to know a lot about JWTs, but it’s worth getting familiar with the parts of a JWT (header, payload and signature), and with what a JWKS is. For more information you can visit JWT.io. To verify the JWT we need to install the
jose
package:
jose
is a JavaScript module that supports JWT and provides functionality for signing and verifying tokens.
For more information about jose
click here.
Middleware
Create a new file middleware.tsx
in the root of your project and use the following code:
To verify the JWT we need the token and the JWKS. We get the token from the “hanko” cookie, and then we obtain the JSON Web Key Set (JWKS) calling the createRemoteJWKSet
function from jose. Then we call await jose.jwtVerify(token, JWKS)
. If the token can be verified, then the promise returned from the function resolves to a decoded token. If it cannot be verified, then the promise rejects and we can catch the error and handle it appropriately, e.g. by redirecting the user to the login/home page. If you console.log the const verifiedJWT
you should see the decoded token showing the payload, the protectedHeader and the key. Inside the key, you should be able to see a “true” if it’s verified.
For more information about Next.js Middleware click here.
Securing the application and redirecting
To prevent unauthorized users from getting access to private user data, we can add the paths to be protected in the Middleware configuration. Following the example on the Next.js Docs about the middleware, copy the following code to the bottom of your middleware.tsx
file:
Update the Login
page to subscribe to the events of the Hanko client and redirect to the Todo
page after a successful login:
Time to display the right Todos
Lastly, we should only display the todos for the user that is logged in. To do so, we need to link the todos to the correct “user ID”. The first step is to update the Todo model in the prisma schema
:
Then run the following command to create a migration:
Or the following to push the schema changes directly to the database:
The next step is to update the api/todo/route.tsx
file to get the user ID from the token, then create a new todo if there is a user ID:
The final step is to update the Prisma call to fetch all the todos from the todo/page.tsx
:
That’s all, you’ve successfully created a Todo app with Next.js, Hanko, Prisma and Tailwind CSS!
Try it yourself
Todo app using Hanko Auth, Next.js 13 and Prisma
Full source code available on our GitHub
Was this page helpful?