User authentication api


This blog is simple tutorial to create a simple api which can also be used as a microservice or individually for authenticating a user in any application. This api tutorial also covers authentication using JWT and user verification using an alphanumeric OTP.

Project Structure

Project structure of a user authentication api using Nodejs

The above structure follows a Model View Controller(MVC) pattern.

  1. The /bin folder contains the the code to run the http server in order to execute the api.
  2. The /common folder contains all the shared code and resources in the api i.e constants, status, error codes and messages, middleware like loggers, interceptors, authentication for other services, plugins schema attribute injections i.e mongoose plugins, and utility scripts and other small parsing functions.
  3. The /config folder contains all the configuration variables used across the project.
  4. The /connections folder contains the connections to the database.
  5. The /controllers folder contains all the controllers i.e in this case the userControllers which controls the request and the response exchange interface.
  6. The /models folder contains the core schema of the user document which will be saved in the database with all the respective types and properties.
  7. The /public folder contains a basic stylesheet for the .pug files in /views and the /views contains a basic .pug template which can be used to check if the API is up and running.
  8. The /routes folder contains all the routing for the requests using express to the right validators and controllers.
  9. The /services part contains all the services used in the project i.e mongo, mailer and a custom query builder. I have written a custom query builder to ensure better reuse of code for large projects. For small projects, the contents of the query builder can be a part of the controller.
  10. The /validators folder contains all the request validators which validate every field of the request using express-joi-validation and joi.
  11. The /test folder which contains all the test cases for integration and unit tests with mock data. The folder contains only a sample test case for the register route.
  12. The app.js file contains all the entry point config regarding, middlewares, configs, cors, custom headers etc.

Note: This api uses an automated mailer api. You can find the mailer api git repository here and also can find the blog here.

If you would like to access the github repository, you can find it here.

Related Articles