DEV Community

Truong Vu
Truong Vu

Posted on • Edited on

Structuring Node.js Project

If you are looking for the NodeJS project structure based on the best practices to build the RESTful API. It might be helpful for you guys.

Some of the good practices followed in this repository:

  • Code Style Practices via Node Best Practices
  • ES6 Support.
  • Morgan Logger.
  • Error Handling.
  • Open API Specification implemented through apidocjs.
  • JWT Authentication.
  • Joi & Express Validation.
  • Environment variables via .env file.
  • Linting with Prettier.
  • Security (Helmet, CORS, Express Brute).
  • Husky as git hook for linting & running unit test before commit.
  • Unit & E2E Testing with Jest.
  • Backpack build system

Prerequisite

  1. NodeJS
  2. Node Package Management (yarn or npm)
  3. Docker

Installation

  1. Clone the project git clone git@github.com:vukhanhtruong/nodejs-api-boilerplate.git.
  2. Install dependencies yarn install or npm i
  3. Copy .env.example to .env file.

Running Docker

docker-compose up -d.

Raven Log

Create account at Sentry, then put your url to .env file at variable SENTRY_DSN.

Api Doc

Api Doc is hosted on surge. For change the url and have your own docs just modify your link in the .env file. Running the following command to publish your documentation.

# Generate document
yarn doc
# Deploy document to surge.sh
yarn doc:deploy

# or
npm run doc
npm run doc:deploy
Enter fullscreen mode Exit fullscreen mode

Pre-Commit Hook

Using husky for linting your code before commit & running unit test before push.

Scripts

DEV

yarn dev

# or

npm run dev
Enter fullscreen mode Exit fullscreen mode

DEBUG

Debug with VSCode. See VSCode Auto-Attach

yarn debug

# or

npm run debug
Enter fullscreen mode Exit fullscreen mode

TEST

yarn test

# or

npm run test
Enter fullscreen mode Exit fullscreen mode

NOTE: If you have the issue with ENOSPC, run the below command to avoid:

echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf && sudo sysctl -p
Enter fullscreen mode Exit fullscreen mode

Test Watch

yarn test:watch
Enter fullscreen mode Exit fullscreen mode

COVERAGE

# run jest coverage
yarn test:cover

# show html report
yarn test:cover:open

# or

npm run test:cover

npm run test:cover:open
Enter fullscreen mode Exit fullscreen mode

JSDOC

# generate documentation
yarn doc

# Publish documentation to surge.sh
yarn doc:deploy

#or

npm run doc

npm run doc:deploy
Enter fullscreen mode Exit fullscreen mode

Find out more here

Happy Coding!

Top comments (0)