,

Building an Authentication System API with Node.js, Express.js, and MongoDB Database

Posted by






Authentication System APIs with Node.js, Express.js and MongoDB

Authentication System APIs with Node.js, Express.js and MongoDB

If you are building a web application that requires user authentication, you will need to implement an authentication system. In this article, we will explore how to create authentication system APIs using Node.js, Express.js, and MongoDB.

Setting up the Environment

First, you will need to have Node.js and MongoDB installed on your machine. Once you have them installed, create a new directory for your project and run npm init to initialize a new Node.js project. Then, install the required dependencies using the following commands:

    
      npm install express mongoose bcrypt jsonwebtoken
    
  

Creating the User Model

Next, create a new file for your user model. This file will define the structure of the user data and provide methods for interacting with the MongoDB database.

    
      const mongoose = require('mongoose');
      const Schema = mongoose.Schema;

      const userSchema = new Schema({
        username: { type: String, required: true, unique: true },
        password: { type: String, required: true },
        email: { type: String, required: true, unique: true }
      });

      const User = mongoose.model('User', userSchema);

      module.exports = User;
    
  

Creating the Authentication APIs

Now, create a new file for your authentication APIs. This file will define the routes and controllers for handling user authentication.

    
      const express = require('express');
      const router = express.Router();
      const bcrypt = require('bcrypt');
      const jwt = require('jsonwebtoken');
      const User = require('../models/user');

      router.post('/register', async (req, res) => {
        const { username, password, email } = req.body;
        const hashedPassword = await bcrypt.hash(password, 10);
        const user = new User({
          username,
          password: hashedPassword,
          email
        });
        try {
          await user.save();
          res.status(201).json({ message: 'User created successfully' });
        } catch (err) {
          res.status(500).json({ message: err.message });
        }
      });

      router.post('/login', async (req, res) => {
        const { username, password } = req.body;
        const user = await User.findOne({ username });
        if (!user) {
          res.status(404).json({ message: 'User not found' });
          return;
        }
        const isPasswordValid = await bcrypt.compare(password, user.password);
        if (!isPasswordValid) {
          res.status(401).json({ message: 'Invalid password' });
          return;
        }
        const token = jwt.sign({ username: user.username, email: user.email }, 'secret');
        res.status(200).json({ token });
      });

      module.exports = router;
    
  

Integrating the Authentication APIs

Finally, integrate the authentication APIs into your Express.js application by using the following code:

    
      const express = require('express');
      const mongoose = require('mongoose');
      const authRoutes = require('./routes/auth');

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

      const mongoUri = 'mongodb://localhost:27017/auth-app';
      mongoose.connect(mongoUri, { useNewUrlParser: true, useUnifiedTopology: true });

      app.use('/auth', authRoutes);

      app.listen(3000, () => {
        console.log('Server started on port 3000');
      });
    
  

Conclusion

By following these steps, you can create a simple authentication system using Node.js, Express.js, and MongoDB. This system will allow users to register, login, and authenticate their requests using JSON Web Tokens (JWT).


0 0 votes
Article Rating
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
react native
1 year ago

please do english version ?????? you are fatastic !!