{"id":22485641,"url":"https://github.com/sujeet-agrahari/node-express-modular-architecture","last_synced_at":"2025-08-02T18:33:11.896Z","repository":{"id":40345352,"uuid":"270394167","full_name":"sujeet-agrahari/node-express-modular-architecture","owner":"sujeet-agrahari","description":"🚀 A modular folder structure for developing highly scalable and maintainable  APIs in nodejs using express.","archived":false,"fork":false,"pushed_at":"2024-11-12T05:22:31.000Z","size":1410,"stargazers_count":126,"open_issues_count":2,"forks_count":26,"subscribers_count":6,"default_branch":"master","last_synced_at":"2024-11-12T06:17:58.729Z","etag":null,"topics":["api","boilerplate","clean-architecture","dependency-injection","express","hapi","jwt","nodejs","orm","rest-api","sequelize","swagger"],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/sujeet-agrahari.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":".github/FUNDING.yml","license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null},"funding":{"github":null,"patreon":null,"open_collective":null,"ko_fi":null,"tidelift":null,"community_bridge":null,"liberapay":null,"issuehunt":null,"otechie":null,"custom":null}},"created_at":"2020-06-07T18:22:55.000Z","updated_at":"2024-11-12T05:22:36.000Z","dependencies_parsed_at":"2024-04-18T03:40:29.199Z","dependency_job_id":"02313f2c-fc8e-4222-b6ba-04e4d06e60f4","html_url":"https://github.com/sujeet-agrahari/node-express-modular-architecture","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sujeet-agrahari%2Fnode-express-modular-architecture","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sujeet-agrahari%2Fnode-express-modular-architecture/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sujeet-agrahari%2Fnode-express-modular-architecture/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sujeet-agrahari%2Fnode-express-modular-architecture/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/sujeet-agrahari","download_url":"https://codeload.github.com/sujeet-agrahari/node-express-modular-architecture/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":228499981,"owners_count":17929991,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["api","boilerplate","clean-architecture","dependency-injection","express","hapi","jwt","nodejs","orm","rest-api","sequelize","swagger"],"created_at":"2024-12-06T17:12:57.057Z","updated_at":"2024-12-06T17:14:49.045Z","avatar_url":"https://github.com/sujeet-agrahari.png","language":"JavaScript","funding_links":[],"categories":["JavaScript"],"sub_categories":[],"readme":"\n# Node Express Modular Architecture\nA boilerplate/starter project for quickly building RESTful APIs using Node.js, Express, and sequelize.\n\nIt incorporates the latest technologies, such as `pnpm` for package management, `jest` for test cases, and `eslint` for enforcing coding guidelines and best practices.\n\n\nBy running a single command, you will get a production-ready Node.js app installed and fully configured on your machine. The app comes with many built-in features, such as authentication using JWT, request validation, unit and integration tests, continuous integration, docker support, API documentation, pagination, etc. For more details, check the features list below.\n\n## Deployment and Production Readiness\n\nThis repository is designed to be easily deployed to production environments using Docker. The following steps are performed automatically by the Docker actions configured in this repository:\n\n- **Building Docker Image:** The Docker action builds a Docker image for this application using the provided Dockerfile.\n- **Running Unit Tests:** Before the Docker image is built and pushed, the Docker action runs the unit tests to ensure the codebase is functioning as expected.\n- **Pushing Docker Image:** Once the unit tests pass, the Docker image is pushed to a container registry, making it ready for deployment.\n- **Production Ready:** With the Docker image available in the container registry, this repository is production-ready, and the image can be deployed to production environments at any time.\n\nBy leveraging Docker and the automated workflows defined in this repository, you can ensure consistent and reliable deployments of this application, along with the confidence of passing unit tests before moving to production.\n\n### Prerequisites\n\nBefore deploying this application using Docker, make sure you have the following prerequisites installed:\n\n- Docker: [Installation Guide](https://docs.docker.com/get-docker/)\n- Container Registry Credentials: Ensure you have the necessary credentials to push Docker images to your container registry.\n\n### Deployment Steps\n\nTo deploy this application to a production environment using Docker, follow these steps:\n\n1. Clone this repository: `git clone \u003crepository-url\u003e`\n2. Navigate to the repository's root directory: `cd \u003crepository-folder\u003e`\n3. Build the Docker image: `docker build -t \u003cimage-name\u003e .`\n4. Push the Docker image to your container registry: `docker push \u003cimage-name\u003e`\n5. Deploy the Docker image to your production environment using the container registry and deployment tooling of your choice.\n\nMake sure to replace `\u003crepository-url\u003e`, `\u003crepository-folder\u003e`, and `\u003cimage-name\u003e` with the appropriate values for your setup.\n\n### Continuous Integration and Delivery (CI/CD)\n\nThis repository is equipped with continuous integration and delivery capabilities using Docker actions. With every code change and pull request, the defined workflows will automatically run the unit tests and perform the necessary steps for building and pushing the Docker image. This ensures that the application is always production-ready and provides a streamlined process for deploying updates.\n\nTo configure or customize the CI/CD workflows, refer to the `.github/workflows` directory in this repository and modify the workflow files according to your requirements.\n\n## Manual Installation\n\nIf you would still prefer to do the installation manually, follow these steps:\n\nClone the repo:\n\n```bash\ngit clone --depth 1 https://github.com/sujeet-agrahari/node-express-modular-architecture.git\ncd node-express-modular-architecture\nnpx rimraf ./.git\n```\n\nInstall the dependencies:\n\n```bash\npnpm install\n```\n\nSet the environment variables:\n\n```bash\n# open .env and modify the environment variables (if needed)\n```\n\n## Table of Contents\n\n- [Node Express Modular Architecture](#node-express-modular-architecture)\n  - [Deployment and Production Readiness](#deployment-and-production-readiness)\n    - [Prerequisites](#prerequisites)\n    - [Deployment Steps](#deployment-steps)\n    - [Continuous Integration and Delivery (CI/CD)](#continuous-integration-and-delivery-cicd)\n  - [Manual Installation](#manual-installation)\n  - [Table of Contents](#table-of-contents)\n  - [Features](#features)\n  - [Commands](#commands)\n  - [Environment Variables](#environment-variables)\n  - [Project Structure](#project-structure)\n  - [CLI Support](#cli-support)\n  - [API Documentation](#api-documentation)\n    - [API Endpoints](#api-endpoints)\n  - [Error Handling](#error-handling)\n  - [Validation](#validation)\n  - [Authentication](#authentication)\n  - [Authorization](#authorization)\n  - [Logging](#logging)\n  - [Linting](#linting)\n  - [Contributing](#contributing)\n  - [Inspirations](#inspirations)\n  - [License](#license)\n\n## Features\n\n- **Postgresql**: [Sequelize](https://sequelize.org/) \n- **Authentication and authorization**: using [jsonwebtoken](https://www.npmjs.com/package/jsonwebtoken)\n- **Validation**: request data validation using [Joi](https://github.com/hapijs/joi)\n- **Logging**: using [winston](https://github.com/winstonjs/winston) \n- **Testing**: unit and integration tests using [ava](https://jestjs.io)\n- **Error handling**: centralized error handling mechanism [express-async-errors](https://www.npmjs.com/package/express-async-errors)\n- **API documentation**: with [swagger-jsdoc](https://github.com/Surnet/swagger-jsdoc) and [swagger-ui-express](https://github.com/scottie1984/swagger-ui-express)\n- **Process management**: advanced production process management using [PM2](https://pm2.keymetrics.io)\n- **Dependency management**: with [npm](https://www.npmjs.com/)\n- **Environment variables**: using [dotenv](https://github.com/motdotla/dotenv) and [node-config](https://www.npmjs.com/package/config)\n- **CORS**: Cross-Origin Resource-Sharing enabled using [cors](https://github.com/expressjs/cors)\n- **Graceful Shutdown**:  with [stoppable](https://www.npmjs.com/package/stoppable) releases database connection and other resource before closing the server also _listens_ for signals like `SIGINT` and `SIGTERM`\n\n\n## Commands\n\nRunning locally:\n\n```bash\npnpm start \n```\n\nRunning in production:\n\n```bash\n# set NODE_ENV=production in .env \npnpm start \n```\nDocker:\n\n```bash\n# development\ndocker build ---target dev -t sujeet-agrahari/your-project:latest \n\n#production\ndocker build --target prod -t sujeet-agrahari/your-project:latest  \n```\n\nLinting:\n\n```bash\n# run ESLint\npnpm run lint\n\n# fix ESLint errors\npnpm run lint:fix\n```\n\n## Environment Variables\n\nThe environment variables can be found and modified in the `.env` file. They come with these default values:\n\n```bash\n# Port number\nPORT=3000\n\n# Set environment\nNODE_ENV=development\n\n# node-config directory path\nNODE_CONFIG_DIR=./src/config\n```\n\n## Project Structure\n\n```\nsrc/\n|--config/                  # Environment variables and configuration-related files.\n|--components/              # Contains individual components.\n   |--component.module.js   # Entry file for the component.\n   |--component.controller.js   # Controller for the component.\n   |--component.service.js      # Service for the component.\n   |--component.routes.js       # Routes for the component.\n   |--component.validator.js    # Validators for the component.\n|--docs/                    # Swagger files for API documentation.\n|--middlewares/             # Custom Express middlewares.\n|--db/                      # Sequelize ORM files for the data layer.\n   |--models/               # Sequelize models.\n   |--seeders/              # Sequelize seeders.\n   |--migrations/           # Sequelize migrations.\n|--utils/                   # Utility classes and functions.\n|--loaders/                 # Lodash routes and configurations; also validates configurations.\n|--support/                 # Wrapper for used packages, enabling easy package replacement.\n|--app.js                   # Express app setup.\n|--server.js                # Entry point for the application.\n```\n## CLI Support\nnode-express-modular-architecture comes with `cli` support. Instead of creating components and files manully you can use command line tool to automate the process.\n\nTo create a new component simply run,\n```\nnpm run create:component -- --name=\"ComponentNameHere\"\n```\n\n## API Documentation\n\n\n### API Endpoints\n\nList of available routes:\n\n**Auth routes**:\\\n`POST /v1/auth/register` - register\n`POST /v1/auth/login` - login\n\n## Error Handling\n\nThe app has a centralized error handling mechanism, no `try{..} catch() {..}`\n\nAll errors are captured, logged and managed through one file: `src/middlewares/error.js`\n\nIt will log errors, debugs, and infos on console in `development` mode,  and in production mode it also logs to files: `logs/errors.log` and `logs/combined.log` \n\n\nThe error handling middleware sends an error response, which has the following format:\n\n```\n{\n  error: {\n    \"code\": 404,\n    \"message\": \"Not found\"\n  }\n}\n```\n\nWhen running in development mode, the error response also contains the error stack.\n\nThe app has a utility ApiError class to which you can attach a response code and a message, and then throw it from anywhere \n\nFor example, if you are trying to get a user from the DB who is not found, and you want to send a 404 error, the code should look something like:\n\n```javascript\nconst { NodeFoundError } = require('../utils/api-errors');\nconst { User } = require('../db/models');\n\nconst getUser = async (userId) =\u003e {\n  const user = await User.findByPk(userId);\n  if (!user) {\n    throw new NotFoundError('User not found');\n  }\n};\n```\n\n## Validation\n\nRequest data is validated using [Joi](https://joi.dev/). Check the [documentation](https://joi.dev/api/) for more details on how to write Joi validation schemas.\n\nThe validation schemas are defined in the `src/components/{eachComponent}/validations` directory and are used in the routes by providing them as parameters to the `validate` middleware.\n\n```javascript\nrouter.post(\n  '/login',  \n  makeValidatorCallback(AuthValidator.validateLogin), \n  makeExpressCallback(AuthController.login)\n  );\n```\n\n## Authentication\n\nTo require authentication for certain routes, you can use the `auth` middleware.\n\n```javascript\n// Routes\nconst { AuthRoutes } =  require('../components/Auth/auth.module');\nmodule.exports  =  function  getRoutes(app) {\napp.use('/api/v1/auth', AuthRoutes);\n};\n```\n\nThese routes require a valid JWT access token in the Authorization request header using the Bearer schema. If the request does not contain a valid access token, an Unauthorized (401) error is thrown.\n\n**Generating Access Tokens**:\n\nAn access token can be generated by making a successful call to the register (`POST /v1/auth/register`) or login (`POST /v1/auth/login`) endpoints. The response of these endpoints also contains refresh tokens (explained below).\n\nAn access token is valid for one day. You can modify this expiration time by changing the  config variable in the `config/default.yaml` file.\n```\nJWT_SIGN_OPTIONS:\n  issuer:  My Compny Pvt Ltd\n  audience:  https://example.in\n  expiresIn:  1d\n```\n\n**Refreshing Access Tokens**:\n\nAfter the access token expires, a new access token can be generated, by making a call to the refresh token endpoint (`POST /v1/auth/refresh-tokens`) and sending along a valid refresh token in the request body. This call returns a new access token and a new refresh token.\n\nAn access token is valid for one day. You can modify this expiration time by changing the  config variable in the `config/development.yaml` file.\n\n\n## Authorization\n\nThe `auth` middleware can also be used to require certain rights/permissions to access a route.\n\n```javascript\nconst express = require('express');\nconst auth = require('../../middlewares/auth');\nconst userController = require('../../controllers/user.controller');\n\nconst router = express.Router();\n\nrouter.post('/users', auth('manageUsers'), userController.createUser);\n```\n\nIn the example above, an authenticated user can access this route only if that user has the `manageUsers` permission.\n\nThe permissions are role-based. You can view the permissions/rights of each role in the `src/config/roles.js` file.\n\nIf the user making the request does not have the required permissions to access this route, a Forbidden (403) error is thrown.\n\n## Logging\n\nImport the logger from `src/config/logger.js`. It is using the [Winston](https://github.com/winstonjs/winston) logging library.\n\nLogging should be done according to the following severity levels (ascending order from most important to least important):\n\n```javascript\nconst logger = require('\u003cpath to src\u003e/config/logger');\n\nlogger.error('message'); // level 0\nlogger.warn('message'); // level 1\nlogger.info('message'); // level 2\nlogger.http('message'); // level 3\nlogger.verbose('message'); // level 4\nlogger.debug('message'); // level 5\n```\n\nIn development mode, log messages of all severity levels will be printed to the console.\n\nIn production mode, only `info`, `warn`, and `error` logs will be printed to the console.\\\nIt is up to the server (or process manager) to actually read them from the console and store them in log files.\\\nThis app uses pm2 in production mode, which is already configured to store the logs in log files.\n\nNote: API request information (request url, response code, timestamp, etc.) are also automatically logged (using [morgan](https://github.com/expressjs/morgan)).\n\n\n## Linting\n\nLinting is done using [ESLint](https://eslint.org/) and [Prettier](https://prettier.io).\n\nIn this app, ESLint is configured to follow the [Airbnb JavaScript style guide](https://github.com/airbnb/javascript/tree/master/packages/eslint-config-airbnb-base) with some modifications. It also extends [eslint-config-prettier](https://github.com/prettier/eslint-config-prettier) to turn off all rules that are unnecessary or might conflict with Prettier.\n\nTo modify the ESLint configuration, update the `.eslintrc.json` file. To modify the Prettier configuration, update the `.prettierrc.json` file.\n\nTo prevent a certain file or directory from being linted, add it to `.eslintignore` and `.prettierignore`.\n\nTo maintain a consistent coding style across different IDEs, the project contains `.editorconfig`\n\n## Contributing\n\nContributions are more than welcome! Please check out the [contributing guide](CONTRIBUTING.md).\n\n## Inspirations\n\n- [danielfsousa/express-rest-es2017-boilerplate](https://github.com/danielfsousa/express-rest-es2017-boilerplate)\n- [madhums/node-express-mongoose](https://github.com/madhums/node-express-mongoose)\n- [kunalkapadia/express-mongoose-es6-rest-api](https://github.com/kunalkapadia/express-mongoose-es6-rest-api)\n\n## License\n\n[MIT](LICENSE)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsujeet-agrahari%2Fnode-express-modular-architecture","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fsujeet-agrahari%2Fnode-express-modular-architecture","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsujeet-agrahari%2Fnode-express-modular-architecture/lists"}