[DAY 108-112] I built my first full-stack app with CRUD and auth logins

WHAT TO KNOW - Sep 9 - - Dev Community

<!DOCTYPE html>





Day 108-112: Building My First Full-Stack App with CRUD and Authentication

<br> body {<br> font-family: sans-serif;<br> margin: 0;<br> padding: 20px;<br> }</p> <div class="highlight"><pre class="highlight plaintext"><code>h1, h2, h3 { margin-bottom: 10px; } img { max-width: 100%; height: auto; margin-bottom: 10px; } code { font-family: monospace; background-color: #f0f0f0; padding: 5px; border-radius: 3px; } pre { background-color: #f0f0f0; padding: 10px; border-radius: 3px; overflow-x: auto; } </code></pre></div> <p>



Day 108-112: Building My First Full-Stack App with CRUD and Authentication



Over the past five days, I embarked on an exhilarating journey to build my very first full-stack application. This project involved implementing fundamental features like CRUD (Create, Read, Update, Delete) operations and user authentication. This experience proved to be a valuable learning curve, solidifying my understanding of web development concepts and introducing me to the intricacies of building interactive and secure web applications.


Image of a developer working on a project


Understanding the Scope



My project was a simple to-do list application. While seemingly straightforward, this project allowed me to explore the core functionalities of a typical web application, serving as a solid foundation for future endeavors. The primary features included:



  • CRUD Operations:
    The ability to create, read, update, and delete tasks within the to-do list.

  • User Authentication:
    Implementing a secure login system to allow users to access their personalized to-do lists.

  • Data Persistence:
    Storing user data and tasks persistently using a database.

  • Frontend Development:
    Designing the user interface using HTML, CSS, and JavaScript to create a visually appealing and user-friendly experience.

  • Backend Development:
    Building the server-side logic using Node.js and Express to handle data requests and provide API endpoints for the frontend.


The Tech Stack



To bring this project to life, I chose a technology stack that's widely used and known for its ease of use and scalability. Here's a breakdown:



  • Frontend:
    • HTML: The foundation of the application's structure.
    • CSS: Styling the application for visual appeal and user experience.
    • JavaScript: Providing dynamic interactivity and handling client-side logic.

  • Backend:
    • Node.js: A JavaScript runtime environment for building server-side applications.
    • Express.js: A popular framework for building web applications with Node.js, simplifying routing, request handling, and middleware.

  • Database:
    • MongoDB: A NoSQL database known for its scalability and flexibility, suitable for handling structured and semi-structured data.

  • Authentication:
    • JSON Web Tokens (JWT): A standard for securely transmitting information between parties as JSON objects, used for authentication and authorization.


Building the Frontend



The frontend was built using HTML, CSS, and JavaScript. I designed a simple yet functional user interface with a list to display tasks, input fields for creating new tasks, and buttons for editing and deleting tasks. The key features of the frontend included:



  • Dynamic Task List Rendering:
    Using JavaScript, I fetched data from the backend API and dynamically rendered the tasks on the page. This ensured that the list was updated in real-time whenever a new task was added or deleted.

  • Form Handling:
    JavaScript was used to handle user input, validate the data, and send it to the backend API for processing.

  • User Interaction:
    Event listeners were implemented to handle user interactions like clicking buttons and typing in input fields, triggering the necessary JavaScript functions.

  • Styling:
    CSS was used to style the elements of the UI, ensuring a visually appealing and user-friendly experience.

Image of a to-do list application


Backend Development: The Heart of the Application



The backend was developed using Node.js and Express.js. This layer acted as the bridge between the frontend and the database, handling data requests, processing logic, and responding to the frontend.



  • API Endpoints:
    I defined API endpoints using Express.js to handle various requests, such as creating new tasks, fetching all tasks, updating existing tasks, deleting tasks, and handling user authentication.

  • Database Interaction:
    Using MongoDB's driver for Node.js, I connected to the database, performed CRUD operations, and retrieved data for the API endpoints.

  • Authentication Middleware:
    Implemented middleware to verify user authentication using JWTs. This middleware intercepted requests and ensured that only authorized users could access protected resources.

  • Error Handling:
    Implemented error handling middleware to catch and gracefully handle potential errors, providing meaningful responses to the frontend.


Implementing Authentication



Authentication was a crucial part of the application, ensuring that only registered users could access their personalized to-do lists. I chose JSON Web Tokens (JWT) as the authentication mechanism. JWTs are compact and self-contained tokens that securely transmit information between parties. The authentication process involved the following steps:



  1. User Registration:
    Users could register by providing their username and password. This information was stored in the MongoDB database.

  2. Login:
    Upon login, the user's credentials were verified against the database. If successful, a JWT was generated and sent back to the client.

  3. JWT Verification:
    The frontend sent the JWT with every subsequent request. The backend middleware verified the JWT's validity and extracted the user's information.

  4. Authorization:
    Based on the user's role or permissions, the backend could restrict access to certain resources or functionalities.


Code Examples



Here are some code snippets illustrating key concepts of the application:



Frontend (JavaScript): Adding a New Task



function addNewTask() {
const taskInput = document.getElementById('taskInput');
const newTask = {
title: taskInput.value,
};

fetch('/tasks', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': Bearer ${localStorage.getItem('token')}
},
body: JSON.stringify(newTask)
})
.then(response => response.json())
.then(data => {
// Update the task list on the frontend
// ...
})
.catch(error => {
console.error('Error adding task:', error);
// Handle error on the frontend
// ...
});
}



Backend (Node.js): Creating a New Task Endpoint



const express = require('express');
const router = express.Router();
const Task = require('../models/Task');
const authMiddleware = require('../middleware/auth');

router.post('/', authMiddleware, async (req, res) => {
try {
const { title } = req.body;
const newTask = new Task({ title, userId: req.user._id });
await newTask.save();
res.status(201).json(newTask);
} catch (error) {
console.error('Error creating task:', error);
res.status(500).json({ message: 'Internal server error' });
}
});

module.exports = router;






Conclusion





Building my first full-stack application was a rewarding and challenging experience. It allowed me to delve into fundamental concepts like CRUD operations, user authentication, and backend development. The project also highlighted the importance of a well-defined technology stack, clear code organization, and robust error handling. Through this journey, I gained a deeper understanding of web development principles, reinforcing my passion for creating dynamic and interactive web applications.





As I continue to learn and grow, I am eager to explore more advanced techniques and build even more complex and feature-rich applications. This project served as a stepping stone, providing a solid foundation for my future endeavors in the world of web development.




. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player