Todo App with Neon Postgres
This tutorial demonstrates how to build Todo app
using Drizzle ORM with Neon database and Next.js.
- You should have an existing Next.js project or create a new one using the following command:
npx create-next-app@latest --typescript
- You should have installed Drizzle ORM and Drizzle kit. You can do this by running the following command:
npm i drizzle-orm
npm i -D drizzle-kit
yarn add drizzle-orm
yarn add -D drizzle-kit
pnpm add drizzle-orm
pnpm add -D drizzle-kit
bun add drizzle-orm
bun add -D drizzle-kit
- You should have installed the Neon serverless driver.
npm i @neondatabase/serverless
yarn add @neondatabase/serverless
pnpm add @neondatabase/serverless
bun add @neondatabase/serverless
- You should have installed the
dotenv
package for managing environment variables.
npm i dotenv
yarn add dotenv
pnpm add dotenv
bun add dotenv
In case you face the issue with resolving dependencies during installation:
If you’re not using React Native, forcing the installation with --force
or --legacy-peer-deps
should resolve the issue. If you are using React Native, then you need to use the exact version of React which is compatible with your React Native version.
Setup Neon and Drizzle ORM
Create a new Neon project
Log in to the Neon Console and navigate to the Projects section. Select a project or click the New Project
button to create a new one.
Your Neon projects come with a ready-to-use Postgres database named neondb
. We’ll use it in this tutorial.
Setup connection string variable
Navigate to the Connection Details section in the project console to find your database connection string. It should look similar to this:
postgres://username:password@ep-cool-darkness-123456.us-east-2.aws.neon.tech/neondb
Add the DATABASE_URL
environment variable to your .env
or .env.local
file, which you’ll use to connect to the Neon database.
DATABASE_URL=NEON_DATABASE_CONNECTION_STRING
Connect Drizzle ORM to your database
Create a drizzle.ts
file in your src/db
folder and set up your database configuration:
import { config } from "dotenv";
import { neon } from '@neondatabase/serverless';
import { drizzle } from 'drizzle-orm/neon-http';
config({ path: ".env" }); // or .env.local
const sql = neon(process.env.DATABASE_URL!);
export const db = drizzle(sql);
Declare todo schema
import { integer, text, boolean, pgTable } from "drizzle-orm/pg-core";
export const todo = pgTable("todo", {
id: integer("id").primaryKey(),
text: text("text").notNull(),
done: boolean("done").default(false).notNull(),
});
Here we define the todo
table with fields id
, text
, and done
, using data types from Drizzle ORM.
Setup Drizzle config file
Drizzle config - a configuration file that is used by Drizzle Kit and contains all the information about your database connection, migration folder and schema files.
Create a drizzle.config.ts
file in the root of your project and add the following content:
import { config } from 'dotenv';
import { defineConfig } from "drizzle-kit";
config({ path: '.env' });
export default defineConfig({
schema: "./src/db/schema.ts",
out: "./migrations",
dialect: "postgresql",
dbCredentials: {
url: process.env.DATABASE_URL!,
},
});
Applying changes to the database
You can generate migrations using drizzle-kit generate
command and then run them using the drizzle-kit migrate
command.
Generate migrations:
npx drizzle-kit generate
These migrations are stored in the drizzle/migrations
directory, as specified in your drizzle.config.ts
. This directory will contain the SQL files necessary to update your database schema and a meta
folder for storing snapshots of the schema at different migration stages.
Example of a generated migration:
CREATE TABLE IF NOT EXISTS "todo" (
"id" integer PRIMARY KEY NOT NULL,
"text" text NOT NULL,
"done" boolean DEFAULT false NOT NULL
);
Run migrations:
npx drizzle-kit migrate
Alternatively, you can push changes directly to the database using Drizzle kit push command:
npx drizzle-kit push
Establish server-side functions
In this step, we establish server-side functions in the src/actions/todoAction.ts file to handle crucial operations on todo items:
getData
:- Fetches all existing todo items from the database.
addTodo
:- Adds a new todo item to the database with the provided text.
- Initiates revalidation of the home page using
revalidatePath("/")
.
deleteTodo
:- Removes a todo item from the database based on its unique ID.
- Triggers a revalidation of the home page.
toggleTodo
:- Toggles the completion status of a todo item, updating the database accordingly.
- Revalidates the home page after the operation.
editTodo
:- Modifies the text of a todo item identified by its ID in the database.
- Initiates a revalidation of the home page.
"use server";
import { eq, not } from "drizzle-orm";
import { revalidatePath } from "next/cache";
import { db } from "@/db/drizzle";
import { todo } from "@/db/schema";
export const getData = async () => {
const data = await db.select().from(todo);
return data;
};
export const addTodo = async (id: number, text: string) => {
await db.insert(todo).values({
id: id,
text: text,
});
};
export const deleteTodo = async (id: number) => {
await db.delete(todo).where(eq(todo.id, id));
revalidatePath("/");
};
export const toggleTodo = async (id: number) => {
await db
.update(todo)
.set({
done: not(todo.done),
})
.where(eq(todo.id, id));
revalidatePath("/");
};
export const editTodo = async (id: number, text: string) => {
await db
.update(todo)
.set({
text: text,
})
.where(eq(todo.id, id));
revalidatePath("/");
};
Setup home page with Next.js
Define a TypeScript type
Define a TypeScript type for a todo item in src/types/todoType.ts
with three properties: id
of type number
, text
of type string
, and done
of type boolean
. This type, named todoType
, represents the structure of a typical todo item within your application.
export type todoType = {
id: number;
text: string;
done: boolean;
};
Create a home page for a to-do application
src/components/todo.tsx
: Create aTodo
component that represents a single todo item. It includes features for displaying and editing the todo text, marking it as done with a checkbox, and providing actions for editing, saving, canceling, and deleting the todo.src/components/addTodo.tsx
: TheAddTodo
component provides a simple form for adding new todo items to the Todo app. It includes an input field for entering the todo text and a button for triggering the addition of the new todo.src/components/todos.tsx
: Create Todos components that represents the main interface of a Todo app. It manages the state of todo items, provides functions for creating, editing, toggling, and deleting todos, and renders the individual todo items using theTodo
component.
"use client";
import { ChangeEvent, FC, useState } from "react";
import { todoType } from "@/types/todoType";
interface Props {
todo: todoType;
changeTodoText: (id: number, text: string) => void;
toggleIsTodoDone: (id: number, done: boolean) => void;
deleteTodoItem: (id: number) => void;
}
const Todo: FC<Props> = ({
todo,
changeTodoText,
toggleIsTodoDone,
deleteTodoItem,
}) => {
// State for handling editing mode
const [editing, setEditing] = useState(false);
// State for handling text input
const [text, setText] = useState(todo.text);
// State for handling "done" status
const [isDone, setIsDone] = useState(todo.done);
// Event handler for text input change
const handleTextChange = (e: ChangeEvent<HTMLInputElement>) => {
setText(e.target.value);
};
// Event handler for toggling "done" status
const handleIsDone = async () => {
toggleIsTodoDone(todo.id, !isDone);
setIsDone((prev) => !prev);
};
// Event handler for initiating the edit mode
const handleEdit = () => {
setEditing(true);
};
// Event handler for saving the edited text
const handleSave = async () => {
changeTodoText(todo.id, text);
setEditing(false);
};
// Event handler for canceling the edit mode
const handleCancel = () => {
setEditing(false);
setText(todo.text);
};
// Event handler for deleting a todo item
const handleDelete = () => {
if (confirm("Are you sure you want to delete this todo?")) {
deleteTodoItem(todo.id);
}
};
// Rendering the Todo component
return (
<div className="flex items-center gap-2 p-4 border-gray-200 border-solid border rounded-lg">
{/* Checkbox for marking the todo as done */}
<input
type="checkbox"
className="text-blue-200 rounded-sm h-4 w-4"
checked={isDone}
onChange={handleIsDone}
/>
{/* Input field for todo text */}
<input
type="text"
value={text}
onChange={handleTextChange}
readOnly={!editing}
className={`${
todo.done ? "line-through" : ""
} outline-none read-only:border-transparent focus:border border-gray-200 rounded px-2 py-1 w-full`}
/>
{/* Action buttons for editing, saving, canceling, and deleting */}
<div className="flex gap-1 ml-auto">
{editing ? (
<button
onClick={handleSave}
className="bg-green-600 text-green-50 rounded px-2 w-14 py-1"
>
Save
</button>
) : (
<button
onClick={handleEdit}
className="bg-blue-400 text-blue-50 rounded w-14 px-2 py-1"
>
Edit
</button>
)}
{editing ? (
<button
onClick={handleCancel}
className="bg-red-400 w-16 text-red-50 rounded px-2 py-1"
>
Close
</button>
) : (
<button
onClick={handleDelete}
className="bg-red-400 w-16 text-red-50 rounded px-2 py-1"
>
Delete
</button>
)}
</div>
</div>
);
};
export default Todo;
"use client";
import { ChangeEvent, FC, useState } from "react";
interface Props {
createTodo: (value: string) => void;
}
const AddTodo: FC<Props> = ({ createTodo }) => {
// State for handling input value
const [input, setInput] = useState("");
// Event handler for input change
const handleInput = (e: ChangeEvent<HTMLInputElement>) => {
setInput(e.target.value);
};
// Event handler for adding a new todo
const handleAdd = async () => {
createTodo(input);
setInput("");
};
// Rendering the AddTodo component
return (
<div className="w-full flex gap-1 mt-2">
{/* Input field for entering new todo text */}
<input
type="text"
className="w-full px-2 py-1 border border-gray-200 rounded outline-none"
onChange={handleInput}
value={input}
/>
{/* Button for adding a new todo */}
<button
className="flex items-center justify-center bg-green-600 text-green-50 rounded px-2 h-9 w-14 py-1"
onClick={handleAdd}
>
Add
</button>
</div>
);
};
export default AddTodo;
"use client";
import { FC, useState } from "react";
import { todoType } from "@/types/todoType";
import Todo from "./todo";
import AddTodo from "./addTodo";
import { addTodo, deleteTodo, editTodo, toggleTodo } from "@/actions/todoAction";
interface Props {
todos: todoType[];
}
const Todos: FC<Props> = ({ todos }) => {
// State to manage the list of todo items
const [todoItems, setTodoItems] = useState<todoType[]>(todos);
// Function to create a new todo item
const createTodo = (text: string) => {
const id = (todoItems.at(-1)?.id || 0) + 1;
addTodo(id, text);
setTodoItems((prev) => [...prev, { id: id, text, done: false }]);
};
// Function to change the text of a todo item
const changeTodoText = (id: number, text: string) => {
setTodoItems((prev) =>
prev.map((todo) => (todo.id === id ? { ...todo, text } : todo))
);
editTodo(id, text);
};
// Function to toggle the "done" status of a todo item
const toggleIsTodoDone = (id: number) => {
setTodoItems((prev) =>
prev.map((todo) => (todo.id === id ? { ...todo, done: !todo.done } : todo))
);
toggleTodo(id);
};
// Function to delete a todo item
const deleteTodoItem = (id: number) => {
setTodoItems((prev) => prev.filter((todo) => todo.id !== id));
deleteTodo(id);
};
// Rendering the Todo List component
return (
<main className="flex mx-auto max-w-xl w-full min-h-screen flex-col items-center p-16">
<div className="text-5xl font-medium">To-do app</div>
<div className="w-full flex flex-col mt-8 gap-2">
{/* Mapping through todoItems and rendering Todo component for each */}
{todoItems.map((todo) => (
<Todo
key={todo.id}
todo={todo}
changeTodoText={changeTodoText}
toggleIsTodoDone={toggleIsTodoDone}
deleteTodoItem={deleteTodoItem}
/>
))}
</div>
{/* Adding Todo component for creating new todos */}
<AddTodo createTodo={createTodo} />
</main>
);
};
export default Todos;
Update the page.tsx
file in the src/app
folder to fetch the todo items from the database and render the Todos
component:
import { getData } from "@/actions/todoAction";
import Todos from "@/components/todos";
export default async function Home() {
const data = await getData();
return <Todos todos={data} />;
}
Basic file structure
This guide uses the following file structure:
📦 <project root>
├ 📂 migrations
│ ├ 📂 meta
│ └ 📜 0000_heavy_doctor_doom.sql
├ 📂 public
├ 📂 src
│ ├ 📂 actions
│ │ └ 📜 todoActions.ts
│ ├ 📂 app
│ │ ├ 📜 favicon.ico
│ │ ├ 📜 globals.css
│ │ ├ 📜 layout.tsx
│ │ └ 📜 page.tsx
│ ├ 📂 components
│ │ ├ 📜 addTodo.tsx
│ │ ├ 📜 todo.tsx
│ │ └ 📜 todos.tsx
│ └ 📂 db
│ │ ├ 📜 drizzle.ts
│ │ └ 📜 schema.ts
│ └ 📂 types
│ └ 📜 todoType.ts
├ 📜 .env
├ 📜 .eslintrc.json
├ 📜 .gitignore
├ 📜 drizzle.config.ts
├ 📜 next-env.d.ts
├ 📜 next.config.mjs
├ 📜 package-lock.json
├ 📜 package.json
├ 📜 postcss.config.mjs
├ 📜 README.md
├ 📜 tailwind.config.ts
└ 📜 tsconfig.json