4 Min

CRUD Operations Tutorial for Beginners: Building a Full-Stack App with JavaScript

If you’re new to web development, you’ve probably come across the term CRUD. It stands for Create, Read, Update, and Delete — the four basic operations of any persistent storage system which I explained elsewhere on this site allready. CRUD is the foundation of most web applications, sooner or later you’ll need it.

In this tutorial, we’ll walk through how to implement CRUD operations using JavaScript both on the Front-End and Back-End. By the end, you’ll have a solid understanding of how CRUD works and be well on your way to building more sophisticated apps. Let’s dive in!

What is CRUD?

Before we get into the practical part, let’s quickly define each part of CRUD:

  • Create: Adding new data (like creating a new user, post, or product)
  • Read: Retrieving data from a database (like fetching a user profile or displaying a list of products)
  • Update: Modifying existing data (like editing a user’s profile information)
  • Delete: Removing data (like deleting a user account or post)

Now, let’s apply these operations in a full-stack app using JavaScript for both the front-end and back-end.


Setting Up Your Project

Front-End: HTML and JavaScript

We will use a simple HTML page to create a form that allows users to input data (like a new item or post). We will also use JavaScript to handle the interactions.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>CRUD App</title>
</head>
<body>
  <h1>CRUD App Example</h1>

  <!-- Create Form -->
  <form id="itemForm">
    <input type="text" id="itemName" placeholder="Enter Item Name" required>
    <button type="submit">Add Item</button>
  </form>

  <!-- Read List -->
  <ul id="itemList"></ul>

  <!-- JavaScript -->
  <script src="app.js"></script>
</body>
</html>

Back-End: Node.js with Express

On the back-end, we’ll use Node.js with Express.js to create a REST API that handles CRUD operations. The Express framework is perfect for setting up routes to perform each CRUD operation.

First, initialize your project and install the necessary dependencies:

npm init -y
npm install express body-parser cors

Now, let’s build a basic Express server that can handle CRUD operations:

const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');

const app = express();
const PORT = 5000;

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

let items = [];

// CREATE
app.post('/api/items', (req, res) => {
  const newItem = req.body;
  items.push(newItem);
  res.json(newItem);
});

// READ
app.get('/api/items', (req, res) => {
  res.json(items);
});

// UPDATE
app.put('/api/items/:id', (req, res) => {
  const id = req.params.id;
  const updatedItem = req.body;
  items[id] = updatedItem;
  res.json(updatedItem);
});

// DELETE
app.delete('/api/items/:id', (req, res) => {
  const id = req.params.id;
  items.splice(id, 1);
  res.json({ message: 'Item deleted' });
});

app.listen(PORT, () => {
  console.log(`Server running on http://localhost:${PORT}`);
});

Integrating CRUD Operations on the Front-End

Let’s now add the logic in the front-end JavaScript file (app.js) to call our backend API and interact with the data.

1. Create Operation

We’ll allow users to add items using the form, and send the data to the server to store it.

document.getElementById('itemForm').addEventListener('submit', async (e) => {
  e.preventDefault();
  
  const itemName = document.getElementById('itemName').value;
  
  const response = await fetch('http://localhost:5000/api/items', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ name: itemName })
  });
  
  const newItem = await response.json();
  displayItem(newItem);
  
  document.getElementById('itemName').value = '';
});

function displayItem(item) {
  const itemList = document.getElementById('itemList');
  const listItem = document.createElement('li');
  listItem.textContent = item.name;
  itemList.appendChild(listItem);
}

2. Read Operation

Next, we’ll fetch all the items from the server and display them when the page loads.

window.onload = async () => {
  const response = await fetch('http://localhost:5000/api/items');
  const items = await response.json();
  
  items.forEach(item => displayItem(item));
};

3. Update Operation

We’ll add functionality to allow users to update items by sending a PUT request to the server.

// This part can be triggered when a user clicks an edit button next to an item
async function updateItem(id, updatedName) {
  await fetch(`http://localhost:5000/api/items/${id}`, {
    method: 'PUT',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ name: updatedName })
  });
  
  // Update the displayed item
  document.querySelector(`#item-${id}`).textContent = updatedName;
}

4. Delete Operation

Finally, we’ll allow users to delete an item by sending a DELETE request.

async function deleteItem(id) {
  await fetch(`http://localhost:5000/api/items/${id}`, {
    method: 'DELETE',
  });
  
  document.querySelector(`#item-${id}`).remove();
}

Practical Tips for Beginners

Now that you’ve got a basic CRUD app, here are some practical tips for using these operations to build more complex applications:

  1. Start Small: Practice with small apps like a simple to-do list or a note-taking app.
  2. Understand the Flow: Make sure you understand how requests flow from the front-end to the back-end and vice-versa.
  3. Error Handling: Always add error handling in real-world apps to ensure they handle failed requests or invalid data.
  4. Use Tools like Postman: When developing your back-end, tools like Postman help test your API independently from your front-end.
  5. Practice Security: Once you’re comfortable, add security features like input validation to prevent harmful data from being processed.

Conclusion

Learning CRUD operations is essential for every beginner in web development. By mastering CRUD, you’ll be able to handle data in any web application you build. Whether you’re building a to-do list app or a full-fledged eCommerce platform, CRUD will be the core of your operations.

With this full-stack approach using JavaScript, you now have the tools to create, read, update, and delete data both on the front-end and back-end, helping you grow your skills as a web developer!

Updated: