NodeJs Best Practices

Node.js is a cross-platform open-source Javascript runtime environment for executing javascript code outside of the web browser. It is a popular runtime for writing high-quality applications used by many people. We will see some practices for developing and maintaining the quality of Node.js applications.

The worst problem with large applications is maintaining a huge code base with hundreds of dependencies. In this post, I will explore node js best practices.

Folder structure Properly organize your code files.

When we write code, we may think we know how it works, but that could be a problem when we come back to it a few months later. So if we cannot understand it ourselves, we really cannot expect our colleagues to understand it right away. So just keep it simple. It’s easy to read a small piece of code rather than reading thousands of lines of code, so the best practice is to organize our code into small chunks and then shrink them even further. By using this approach, we can avoid complications by making it easier for us and other developers to understand the code. The first place to start is folder structure, below is a good example of how to organized project folders.

 src
      ├── app.js			app entry point
      ├── /api			controller layer: api routes
      ├── /config			config settings, env variables
      ├── /services		service layer: business logic
      ├── /models			data access layer: database models	
      ├── /scripts		miscellaneous NPM scripts
      ├── /controllers		handles requests and response
      └── /test               test suites

Use HTTP Methods And API Routes

Building a Nodejs Restful API for CRUD operation HTTP already has the appropriate toolset for these operations: POST, PUT, GET, PATCH, or DELETE. As a best practice, API routes should always use nouns as resource identifiers. Speaking of user resources, routing might look like this:

POST /user   //create a new user record,
GET /user  //retrieve a list of users,
GET /user/:id   //retrieve a user,
PATCH /user/:id  or PUT /user/:id   //modify an existing user record,
DELETE /user/:id     //remove a user.

Use HTTP Status Codes

It is a good practice to return each request with a status code, either something goes wrong or every request is processed correctly, there should be a status code tied to each response.

2xx, if everything was okay,
3xx, if the resource was moved,
4xx, if the request cannot be fulfilled because of a client error,
5xx, if something went wrong on the API side,

//examples
res.status(500)  // Internal Server Error

res.status(200)  // OK

res.status(201)  // Created

res.status(401)  // Unauthorized

res.status(403)  // Forbidden
 

You can view a full list of HTTP status codes here.

Use Controllers and Exports modules

Writing your API in a single file can make your code looks cumbersome and may be difficult to maintain. Below is an example of controller and module export

// importation  of  user controller
const userController = require('../controllers/user_controller');


// example of router controller for login and sign up
router.post('/login', userController.login);
router.post('/sign-up', userController.createUser);

below is the userController.js file


const login = (req, res, done)=> {
  // write your logic here
    }


 const createUser = (request , response)=> {
// write your logic here
}


module.exports = { login, createUser}

Pick the right framework for your Node.js REST API

It is important to pick the framework that suits your use case the most.

Express, Koa or Hapi

Express, Koa, and Hapi can be used to build browser applications and as such support template and rendering – just to name a few features. If your app also needs to provide a user-facing page, it’s a good idea to choose them.

Restify

On the other hand, Restify focuses on helping build REST services. It exists to enable you to build “strict” API services that you can maintain and observe. Restify also comes with automatic DTrace support for all handlers. Restify is used in production in major applications such as npm or Netflix.

 Create a Proper API Documentation

You write APIs so that others can use them and benefit from them. Providing API documentation for your Node.js REST API is essential. The following open source projects can help you create documentation for the API:

API BlueprintSwagger In addition, if you want to use a hosted product, you can choose Api

Alternatively, if you want to use a hosted product, you can go for Apiary.


swagasoft

Fully stack(MEAN) software engineer with over five years of experience participating in the complete product development lifecycle of successfully launched applications. Eager and willing to deliver mission- critical technology solutions.

View all posts by swagasoft →

3 thoughts on “NodeJs Best Practices

  1. Hi there, just changed into aware of your blog via Google, and found that it is really informative. I抦 gonna be careful for brussels. I抣l appreciate if you continue this in future. Many other folks can be benefited out of your writing. Cheers!

Leave a Reply

Your email address will not be published. Required fields are marked *