Skip to main content

Fullstack User CRUD

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

Step 1: Create the Database
Open pgAdmin. Right-click Databases, select Create → Database, enter users_crud_db, and save it.

Step 2: Open the Query Tool
Select users_crud_db and open Tools → Query Tool.

Step 3: Create the Users Table

Run the following SQL query:

users.sql
SQL
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.


Step 4: Add Test Users
users.sql
SQL
INSERT INTO users (name, email)
VALUES
 ('Akshay', 'akshay@example.com'),
 ('Rahul', 'rahul@example.com');

Check the inserted users:

users.sql
SQL
SELECT *
FROM users
ORDER BY id;

Step 5: Create the Main Project Folder

Open a terminal and run:

Terminal
Bash
mkdir users-crud-app
cd users-crud-app

Step 6: Create the Backend Folder
Terminal
Bash
mkdir backend
cd backend

Step 7: Initialize Node.js
Terminal
Bash
npm init -y

This command creates the package.json file.


Step 8: Install Express
Terminal
Bash
npm install express

Step 9: Install CORS
Terminal
Bash
npm install cors

CORS allows the React frontend to communicate with the Express backend.


Step 10: Install the PostgreSQL Package
Terminal
Bash
npm install pg

The pg package allows Node.js to communicate with PostgreSQL.


Step 11: Install Nodemon
Terminal
Bash
npm install --save-dev nodemon

Nodemon automatically restarts the backend whenever we save server.js.


Step 12: Add the Development Script

Open package.json and update the scripts section:

package.json
JSON
"scripts": {
 "start": "node server.js",
 "dev": "nodemon server.js"
}

Step 13: Create the PostgreSQL Connection

Create a file named db.js inside the backend folder:

db.js
JavaScript
const { Pool } = require("pg");

const pool = new Pool({
 user: "postgres",
 host: "localhost",
 database: "users_crud_db",
 password: "your_password",
 port: 5432
});

module.exports = pool;
Replace your_password with your actual PostgreSQL password.

Step 14: Create the Express Server

Create a file named server.js inside the backend folder:

server.js
JavaScript
const express = require("express");
const cors = require("cors");
const pool = require("./db");

const app = express();

app.use(cors());
app.use(express.json());

Step 15: Create the GET Route

Add this below the middleware code:

server.js
JavaScript
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.


Step 16: Create the POST Route
server.js
JavaScript
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.


Step 17: Create the PUT Route
server.js
JavaScript
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.


Step 18: Create the DELETE Route
server.js
JavaScript
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.


Step 19: Start the Express Server

Add this code at the bottom of server.js:

server.js
JavaScript
app.listen(5000, () => {
 console.log("Server running on port 5000");
});

Step 20: Complete server.js

Your complete server.js file should now look like this:

server.js
JavaScript
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");
});

Step 21: Run the Backend
Backend Terminal
Bash
npm run dev

Open the following address in the browser:

Backend URL
URL
http://localhost:5000/api/users

You should see the users as JSON.


Step 22: Create the React Application

Keep the backend running. Open another terminal from the users-crud-app folder.

Frontend Terminal
Bash
npm create vite@latest frontend -- --template react

Step 23: Install the Frontend Packages
Frontend Terminal
Bash
cd frontend
npm install

Step 24: Start the React Application
Frontend Terminal
Bash
npm run dev

The frontend normally opens at:

Frontend URL
URL
http://localhost:5173

Step 25: Add React State

Open frontend/src/App.jsx and start with:

src/App.jsx
React JSX
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:

React State
Text
users → User records
name → Name input
email → Email input
editingId → ID of the user being edited

Step 26: Load Users from the API
src/App.jsx
React JSX
 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.


Step 27: Add or Update a User
src/App.jsx
React JSX
 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.


Step 28: Select a User for Editing
src/App.jsx
React JSX
 function editUser(user) {
  setEditingId(user.id);
  setName(user.name);
  setEmail(user.email);
 }

This function copies the selected user's information into the form.


Step 29: Delete a User
src/App.jsx
React JSX
 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.


Step 30: Create the React Interface
src/App.jsx
React JSX
 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;

Step 31: Complete App.jsx

Your complete App.jsx file should look like this:

src/App.jsx
React JSX
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;

Step 32: Add Simple CSS

Replace frontend/src/index.css with:

src/index.css
CSS
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;
}

Step 33: Final Project Structure
Project Structure
Text
users-crud-app
├── backend
│   ├── db.js
│   ├── package.json
│   └── server.js
│
└── frontend
    ├── src
    │   ├── App.jsx
    │   ├── index.css
    │   └── main.jsx
    ├── package.json
    └── vite.config.js

Step 34: Run the Backend

Open the backend terminal:

Backend Terminal
Bash
cd users-crud-app/backend
npm run dev

Step 35: Run the Frontend

Open another terminal:

Frontend Terminal
Bash
cd users-crud-app/frontend
npm run dev

Step 36: Test the Application

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

Application Flow
Text
React form or button
→ fetch request
→ Express route
→ PostgreSQL query
→ JSON response
→ React refreshes the users list

Quick Revision

CRUD Revision
Text
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

Popular posts from this blog

Prompt Engineering for Web Developers: Work Smarter with AI 🚀

   AI is changing the way web applications are built. From generating components and writing tests to planning projects and reviewing code, developers can now use natural language prompts to accelerate development. This approach, often called Vibe Coding, allows developers to describe what they want and let AI generate the solution. The secret to getting quality results is Prompt Engineering : the practice of writing better prompts. 📌 The RTCF Framework A simple framework for creating effective prompts is RTCF : Role → Who should AI act as? Task → What needs to be done? Context → Why is it needed? Format → How should the output look? ❌ Weak Prompt Make me a learning app. ✅ Strong Prompt Role: Senior React Developer Task: Build a React Learning Planner Context: Users need to track learning resources through stages Format: React, Tailwind CSS, drag-and-drop, modern UI, no TypeScript Providing clear instructions dramatically improves AI o...

💰 Managing Finances

Most people focus on earning more, but real wealth is built through smart investing, risk management, and disciplined financial habits. Here's a simple framework to help secure your financial future. 🎯 1. Set Financial Goals First Invest with a purpose: Emergency Fund Home Purchase Child Education Retirement Financial Independence ⚠️ 2. Control Lifestyle Inflation ✅ Good Debt Home Loan Business Loan Education Loan ❌ Bad Debt Credit Card Loan Personal Loan Consumer EMIs Rule: Keep total EMIs below 40% of monthly income . 🛡️ 3. Create an Emergency Fund Maintain 6 months of household expenses in: Fixed Deposits (FD) or Sweep-In Account Arbitrage Mutual Fund (tax-efficient for higher tax brackets) Post Office Deposits This should be your first financial priority. ❤️ 4. Protect Before You Invest Term Insurance Coverage: 10-15× Annual Income/CTC Health Insurance Keep a personal family floater policy. Do not rely only on employer...

Prompt Engineering with OpenAI ChatGPT

Prompt Engineering: A Simple Guide to Better Results Many people use AI with vague prompts and hope for the best. Something like: "Write a postmortem update about yesterday's outage." often produces inconsistent results. Instead of playing Prompt Roulette , use a structured approach. A Better Workflow 1. Contract – Define what success looks like. Ask: What must be included? 2. Scaffold – Use a reusable template. For example: Summary Impact Timeline Known Facts 3. Levers – Change only one thing at a time: Add more detail Shorten the response Change the tone Adjust the audience 4. Loop – Review and improve: Generate → Review → Find one issue → Improve the prompt → Run again. Think of a Prompt as a Contract A strong prompt usually contains five parts: Instructions – What should AI do? Context – Facts and background information. Constraints – Rules and limitations. Examples – Optional style or format sa...