NodeJS Login and Registration Rest API with MongoDB

In this tutorial, I will explain to you the complete process of creating a user registration and login system where users can create an account by providing name, username, email, and password, log in using NodeJS and MongoDB. I will help you how to create step by step register login and API in NodeJS and MongoDB.
Before started to implement the NodeJS Login and Registration Rest API, look files structure:
  • node-js-login-registration-rest-api-mongodb
    • application
      • config
        • config.js
        • db.js
        • error-handler.js
        • jwt.js
      • models
        • user.model.js
      • controllers
        • users.controller.js
      • service
        • user.service.js
    • node_modules
    • server.js
    • package.json
    • package-lock.json
Step 1 – Install express, express-jwt, cors, mongoose,rootpath and dotenv Modules
Step 2 – Create file named config.js
Step 3 – Connect App to MongoDB
Create a file named db.js inside the folder name “application/config/” and add the following code into it to connect your app to the MongoDB database.
Step 4 – Global Error Handler Middleware
Global Error Handler, It is configured as middleware in the server.js
Step 5 – JWT token Middleware
JWT middleware checks that the JWT token received in the http request from the client side is valid before allowing access to the web API.
Step 6 – Create Models
Create a file named user.model.js inside the folder name “application/models/” and add the following code
Step 7 – Create controllers
Create a file named users.controller.js inside the folder name “application/controllers/” and add the following code
Step 8 – Create service
Create a file named user.service.js inside the folder name “application/service/” and add the following code. User service contains the core business logic for user authentication and management.
Step 9 – Start App Server
It is configures application middleware, binds controllers to routes and starts the Express web server for the API.
Finally, We will run the application with help of the postman
1-Register using POST method
Output
2-Login using POST method
Output
3-Get All Users using GET method
Output
4-Get User using GET method
Output
5-Update User using PUT method
Output
6-Delete User using DELETE method
Output