,

Project 2: Building a User Authentication System with MongoDB using Full-Stack Development

Posted by


Introduction:

In this tutorial, we will be creating a Full-Stack application for User Authentication System using MongoDB as our database. We will be creating a front-end using HTML, CSS, and JavaScript, and a back-end using Node.js with Express and MongoDB for the database.

Prerequisites:

Before starting, make sure you have the following installed on your system:

  • Node.js
  • MongoDB
  • Express
  • npm package manager
  • Any code editor (Visual Studio Code recommended)

Step 1: Setup a new Node.js project

  1. Create a new directory for your project and navigate into it:

    mkdir user-auth-system
    cd user-auth-system
  2. Initialize a new Node.js project using the following command:

    npm init -y
  3. Install Express and Mongoose (for MongoDB) using the following commands:
    npm install express mongoose

Step 2: Setting up MongoDB

  1. Start MongoDB server using the following command:

    mongod
  2. Create a new database in MongoDB:
    use user-auth-system

Step 3: Create a database schema

  1. Create a new directory called "models" and create a new file called "User.js" inside it.

  2. Define the schema for the user in User.js file:
    
    const mongoose = require('mongoose');
    const userSchema = new mongoose.Schema({
    username: String,
    email: String,
    password: String
    });

const User = mongoose.model(‘User’, userSchema);
module.exports = User;


Step 4: Create a backend server

1. Create a new file called "server.js" in the root directory.

2. Create an Express server and connect it to MongoDB:
```javascript
const express = require('express');
const mongoose = require('mongoose');

const app = express();
app.use(express.json());

mongoose.connect('mongodb://localhost/user-auth-system', {
    useNewUrlParser: true,
    useUnifiedTopology: true
});

Step 5: Create API endpoints for user authentication

  1. Create a new directory called "routes" and create a new file called "auth.js" inside it.

  2. Define API endpoints for user authentication in auth.js file:
    
    const express = require('express');
    const router = express.Router();
    const User = require('../models/User');

router.post(‘/register’, async (req, res) => {
const { username, email, password } = req.body;
const user = new User({ username, email, password });
await user.save();
res.json({ message: ‘User registered successfully’ });
});

module.exports = router;


3. Import the auth.js file into server.js:
```javascript
const authRoutes = require('./routes/auth');
app.use('/api/auth', authRoutes);

Step 6: Create a front-end using HTML, CSS, and JavaScript

  1. Create a new directory called "public" and create three new files inside it: index.html, style.css, and script.js.

  2. Build a basic front-end for user registration in index.html file:

    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <title>User Authentication System</title>
    <link rel="stylesheet" href="style.css">
    </head>
    <body>
    <h1>User Registration</h1>
    <form id="register-form">
        <input type="text" placeholder="Username" name="username" required>
        <input type="email" placeholder="Email" name="email" required>
        <input type="password" placeholder="Password" name="password" required>
        <button type="submit">Register</button>
    </form>
    <script src="script.js"></script>
    </body>
    </html>
  3. Add some basic styling in style.css file:
    
    body {
    font-family: Arial, sans-serif;
    text-align: center;
    }

form {
margin: 20px auto;
padding: 20px;
border: 1px solid #ccc;
max-width: 300px;
}

input {
margin: 10px 0;
padding: 5px;
}

button {
padding: 5px 10px;
background-color: #007bff;
color: white;
border: none;
}


4. Add JavaScript functionality to make an API call for user registration in script.js file:
```javascript
const form = document.getElementById('register-form');
form.addEventListener('submit', async (e) => {
    e.preventDefault();
    const username = form.username.value;
    const email = form.email.value;
    const password = form.password.value;

    const response = await fetch('/api/auth/register', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ username, email, password })
    });

    const data = await response.json();
    alert(data.message);
});

Step 7: Start the server and test the application

  1. Start the Express server by running the following command:

    node server.js
  2. Open a web browser and navigate to http://localhost:3000 to see the user registration form.

  3. Fill in the details and click on the "Register" button to register a new user. You should see a success message upon successful registration.

Conclusion:

In this tutorial, we have successfully created a Full-Stack application for User Authentication System using MongoDB as our database. We have implemented user registration functionality and tested it using a basic front-end. You can further enhance this application by adding user login, authentication, and authorization functionalities. Feel free to explore and customize the application to meet your requirements.