Build a Basic CRUD App with PostgreSQL, Express and React
In this beginner project, we will create a simple users application using PostgreSQL, Express.js, Node.js and React.js.
We will divide the application into small steps so that the complete flow is easy to understand.
| Action | Method | API |
|---|---|---|
| Show users | GET | /api/users |
| Add user | POST | /api/users |
| Edit user | PUT | /api/users/:id |
| Delete user | DELETE | /api/users/:id |
Run the following SQL query:
CREATE TABLE users ( id INT GENERATED ALWAYS AS IDENTITY PRIMARY KEY, name VARCHAR(100) NOT NULL, email VARCHAR(150) NOT NULL UNIQUE );
The ID will be generated automatically. The name and email fields are required, and duplicate emails are not allowed.
INSERT INTO users (name, email)
VALUES
('Akshay', 'akshay@example.com'),
('Rahul', 'rahul@example.com');
Check the inserted users:
SELECT * FROM users ORDER BY id;
Open a terminal and run:
mkdir users-crud-app cd users-crud-app
mkdir backend cd backend
npm init -y
This command creates the package.json file.
npm install express
npm install cors
CORS allows the React frontend to communicate with the Express backend.
npm install pg
The pg package allows Node.js to communicate with PostgreSQL.
npm install --save-dev nodemon
Nodemon automatically restarts the backend whenever we save server.js.
Open package.json and update the scripts section:
"scripts": {
"start": "node server.js",
"dev": "nodemon server.js"
}
Create a file named db.js inside the backend folder:
const { Pool } = require("pg");
const pool = new Pool({
user: "postgres",
host: "localhost",
database: "users_crud_db",
password: "your_password",
port: 5432
});
module.exports = pool;
your_password with your actual PostgreSQL password.
Create a file named server.js inside the backend folder:
const express = require("express");
const cors = require("cors");
const pool = require("./db");
const app = express();
app.use(cors());
app.use(express.json());
Add this below the middleware code:
app.get("/api/users", async (req, res) => {
const result = await pool.query(
"SELECT * FROM users ORDER BY id"
);
res.json(result.rows);
});
This route reads all users from PostgreSQL.
app.post("/api/users", async (req, res) => {
const { name, email } = req.body;
const result = await pool.query(
`INSERT INTO users (name, email)
VALUES ($1, $2)
RETURNING *`,
[name, email]
);
res.json(result.rows[0]);
});
This route creates a new user.
app.put("/api/users/:id", async (req, res) => {
const { id } = req.params;
const { name, email } = req.body;
const result = await pool.query(
`UPDATE users
SET name = $1, email = $2
WHERE id = $3
RETURNING *`,
[name, email, id]
);
res.json(result.rows[0]);
});
This route updates a user using the user ID.
app.delete("/api/users/:id", async (req, res) => {
const { id } = req.params;
await pool.query(
"DELETE FROM users WHERE id = $1",
[id]
);
res.json({
message: "User deleted"
});
});
This route deletes a user using the user ID.
Add this code at the bottom of server.js:
app.listen(5000, () => {
console.log("Server running on port 5000");
});
Your complete server.js file should now look like this:
const express = require("express");
const cors = require("cors");
const pool = require("./db");
const app = express();
app.use(cors());
app.use(express.json());
app.get("/api/users", async (req, res) => {
const result = await pool.query(
"SELECT * FROM users ORDER BY id"
);
res.json(result.rows);
});
app.post("/api/users", async (req, res) => {
const { name, email } = req.body;
const result = await pool.query(
`INSERT INTO users (name, email)
VALUES ($1, $2)
RETURNING *`,
[name, email]
);
res.json(result.rows[0]);
});
app.put("/api/users/:id", async (req, res) => {
const { id } = req.params;
const { name, email } = req.body;
const result = await pool.query(
`UPDATE users
SET name = $1, email = $2
WHERE id = $3
RETURNING *`,
[name, email, id]
);
res.json(result.rows[0]);
});
app.delete("/api/users/:id", async (req, res) => {
const { id } = req.params;
await pool.query(
"DELETE FROM users WHERE id = $1",
[id]
);
res.json({
message: "User deleted"
});
});
app.listen(5000, () => {
console.log("Server running on port 5000");
});
npm run dev
Open the following address in the browser:
http://localhost:5000/api/users
You should see the users as JSON.
Keep the backend running. Open another terminal from the users-crud-app folder.
npm create vite@latest frontend -- --template react
cd frontend npm install
npm run dev
The frontend normally opens at:
http://localhost:5173
Open frontend/src/App.jsx and start with:
import { useEffect, useState } from "react";
function App() {
const [users, setUsers] = useState([]);
const [name, setName] = useState("");
const [email, setEmail] = useState("");
const [editingId, setEditingId] = useState(null);
The state variables store:
users → User records name → Name input email → Email input editingId → ID of the user being edited
useEffect(() => {
getUsers();
}, []);
async function getUsers() {
const response = await fetch(
"http://localhost:5000/api/users"
);
const data = await response.json();
setUsers(data);
}
useEffect calls getUsers when the React component opens.
async function saveUser(event) {
event.preventDefault();
const url = editingId
? `http://localhost:5000/api/users/${editingId}`
: "http://localhost:5000/api/users";
await fetch(url, {
method: editingId ? "PUT" : "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
name,
email
})
});
setName("");
setEmail("");
setEditingId(null);
getUsers();
}
If editingId contains a user ID, the function sends a PUT request. Otherwise, it sends a POST request.
function editUser(user) {
setEditingId(user.id);
setName(user.name);
setEmail(user.email);
}
This function copies the selected user's information into the form.
async function deleteUser(id) {
await fetch(
`http://localhost:5000/api/users/${id}`,
{
method: "DELETE"
}
);
getUsers();
}
After deleting the user, getUsers loads the latest user list.
return (
<div className="container">
<h1>User Management</h1>
<form onSubmit={saveUser}>
<input
value={name}
onChange={(event) =>
setName(event.target.value)
}
placeholder="Name"
/>
<input
value={email}
onChange={(event) =>
setEmail(event.target.value)
}
placeholder="Email"
/>
<button>
{editingId
? "Update User"
: "Add User"}
</button>
</form>
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{users.map((user) => (
<tr key={user.id}>
<td>{user.id}</td>
<td>{user.name}</td>
<td>{user.email}</td>
<td>
<button
onClick={() =>
editUser(user)
}
>
Edit
</button>
<button
onClick={() =>
deleteUser(user.id)
}
>
Delete
</button>
</td>
</tr>
))}
</tbody>
</table>
</div>
);
}
export default App;
Your complete App.jsx file should look like this:
import { useEffect, useState } from "react";
function App() {
const [users, setUsers] = useState([]);
const [name, setName] = useState("");
const [email, setEmail] = useState("");
const [editingId, setEditingId] = useState(null);
useEffect(() => {
getUsers();
}, []);
async function getUsers() {
const response = await fetch(
"http://localhost:5000/api/users"
);
const data = await response.json();
setUsers(data);
}
async function saveUser(event) {
event.preventDefault();
const url = editingId
? `http://localhost:5000/api/users/${editingId}`
: "http://localhost:5000/api/users";
await fetch(url, {
method: editingId ? "PUT" : "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
name,
email
})
});
setName("");
setEmail("");
setEditingId(null);
getUsers();
}
function editUser(user) {
setEditingId(user.id);
setName(user.name);
setEmail(user.email);
}
async function deleteUser(id) {
await fetch(
`http://localhost:5000/api/users/${id}`,
{
method: "DELETE"
}
);
getUsers();
}
return (
<div className="container">
<h1>User Management</h1>
<form onSubmit={saveUser}>
<input
value={name}
onChange={(event) =>
setName(event.target.value)
}
placeholder="Name"
/>
<input
value={email}
onChange={(event) =>
setEmail(event.target.value)
}
placeholder="Email"
/>
<button>
{editingId
? "Update User"
: "Add User"}
</button>
</form>
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{users.map((user) => (
<tr key={user.id}>
<td>{user.id}</td>
<td>{user.name}</td>
<td>{user.email}</td>
<td>
<button
onClick={() =>
editUser(user)
}
>
Edit
</button>
<button
onClick={() =>
deleteUser(user.id)
}
>
Delete
</button>
</td>
</tr>
))}
</tbody>
</table>
</div>
);
}
export default App;
Replace frontend/src/index.css with:
body {
font-family: Arial, sans-serif;
background: #f4f4f4;
padding: 20px;
}
.container {
max-width: 700px;
margin: auto;
}
input,
button {
padding: 10px;
margin: 5px;
}
table {
width: 100%;
margin-top: 20px;
border-collapse: collapse;
background: white;
}
th,
td {
border: 1px solid #dddddd;
padding: 10px;
text-align: left;
}
users-crud-app
├── backend
│ ├── db.js
│ ├── package.json
│ └── server.js
│
└── frontend
├── src
│ ├── App.jsx
│ ├── index.css
│ └── main.jsx
├── package.json
└── vite.config.js
Open the backend terminal:
cd users-crud-app/backend npm run dev
Open another terminal:
cd users-crud-app/frontend npm run dev
Open the React application in the browser.
Enter a name and email and click Add User.
Click Edit to load a user's information into the form.
Change the information and click Update User.
Click Delete to remove a user.
Final Application Flow
React form or button → fetch request → Express route → PostgreSQL query → JSON response → React refreshes the users list
Quick Revision
GET /api/users → Read all users POST /api/users → Add a user PUT /api/users/:id → Update a user DELETE /api/users/:id → Delete a user useState → Store React data useEffect → Load users when the page opens fetch → Send requests to Express pool.query → Send SQL queries to PostgreSQL
Final Notes
This project is intentionally simple. We kept each step small and removed extra validation and advanced error handling so beginners can first understand the basic CRUD flow.
After understanding this version, the next improvements can include form validation, try/catch error handling, environment variables, separate route files and confirmation before deleting a user.
Happy Coding!
Comments
Post a Comment