How to write production-ready Node.js Rest API — Javascript version

How to write production-ready Node.

js Rest API — Javascript versionBhargav BachinaBlockedUnblockFollowFollowingFeb 14Node.

js Rest APIThis article list out all the necessary ingredients for the production-ready Node.

js rest API with plain vanilla javascript.

I want to categorize this into two phasesDevelopment PhaseProduction PhaseLet’s not complicate things and create simple user API where you get a list of users with Get request and save a user with post request.

since we are focussing on the Node.

js rest API, let's go with the simple API.

let’s download all the tools required for the project.

Tools Required:Node.

js (https://nodejs.

org/en/)Visual studio code (https://code.


com/)nodemonexpresseslintwebpackFor complete projectgit clone https://github.


gitfollow the below article for step by step processDevelopment PhaseInitial setupnodemonLoggingHow to handle undefined routesHow to define context pathError HandlingLinting your projectTesting your projectAny node.

js project starts with package.

json let's create a folder called user_api and cd into it and do npm init.

it will ask you all the details like package name, version, author etc.

You can leave them blank or give some values will create a package.

json in your folder.

mkdir user_apicd user_apinpm initif you notice the package.

json, index.

js is the main file which is the starting file for the project.

let's create index.

js file at root level and install express.

js framework.

Express is a web application framework for node.

js which we can use for creating HTTP server and configure routes for our project.

touch index.

jsnpm install express –savewhenever you install package and it will be added to dependencies section as you can see below.

you don’t have to add it manually when you do it with “ — save” flag, npm will take care of adding that into dependencies section.


jsonlet’s import express into index.

js and create Http server which listens on port 3070 and create a default route with “/”.


jsvar express = require("express"), app = express(), port = 3070;app.

get("/", function(req, res) { res.

send("App works!!");})app.

listen(port, function(err) { console.

log("running server on from port:::::::" + port);});run the below command and open the browser and hit http://localhost:3070and default route works!!.

node index.

jsDefault route workingLet's add scripts to package.


scripts are the great place to add all your commands so that you can run with npm command.

Add the below line to the scripts section in package.


you can run with the command npm start"scripts": { "start": "node index.

js", "test": "echo "Error: no test specified" && exit 1" },Let's add a couple of routes and test it in the browser.

add the body-parser dependency express will use this middleware to access request data from the post request.

Look at the complete index.

js file and package.

json file.

npm install body-parser –save//in the index.

js fileapp.


json());nodemonAt this moment, we have full rest API with 4 routes including default.

one problem that we have right now is a manual restart of the server whenever we edit any file.

let's add nodemon.

it’s a tool which automatically detects file changes in your directory and restarts the server without any manual intervention.

This is a dev dependency means only necessary for development, so the flag — save-dev.

add another line to the scripts section so that we can run with npm.

npm install nodemon –save-dev// dev dependencies will be added"devDependencies": { "nodemon": "^1.


10"}// scripts section in package.

json"scripts": { "start": "node index.

js", "start:dev": "nodemon index.

js", "test": "echo "Error: no test specified" && exit 1"}run the below npm command and edit the file you can see changes instantly without restart of the server.

it boosts your productivity.

npm run start:devnodemonLoggingLet’s setup logging for our project.

create a new folder called logger with a file called logger.


we can use any package like winston, log4js, but we are not using those for simplicity purpose.

This is how you create a separate file and import it in another file in nodejs.

Now you can see the logging is done by the logger that we created once you replace all console.

log statements.

in this way, you can control all your app logging from one file.

you can add any third party package into that file without changes across the app.


info("running server on from port:::::::" + port);How to handle Undefined Routeswe defined default and three other routes in our service.

let's handle undefined routes as well.

what if the user tries to enter wrong one or misspell the route.

Make sure you add this route as the last route.

if you add this at the beginning all the routes will be redirected to this.

// request to handle undefined or all other routesapp.

get("*", function(req, res) { logger.

info("users route"); res.

send("App works!!!!!");})How to define Context Pathwe don’t have any context path for our project, Let’s define it.

Since it is an API, let's define “/api” for all the routes and also define sub context path for the user module which is “/user”.

after the below changes to all the files, path changes from http://localhost:3070/users to http://localhost:3070/api/user/users// changes – create separate folder routes and two files under itmkdir routescd routestouch routes.

js user.

jsError Handlingcoming soon!!Linting your projectLet’s add eslint to our project.

it’s very important to have linting for your project to maintain the same coding standards across your team.

run following commands in a sequence// installs eslint global so that you can use eslintnpm install -g eslint//installs eslint for the projectnpm install eslint -save-dev//it will create .


js, while creating it will create bunch //of questions like which standards you want to use etc.

eslint –init//add these below to scripts section in package.

json"eslint": "eslint .

/","eslint-fix": "eslint .

/ –fix",eslint — lintwhen you first run the below command you will have lot of eslint errors you can easily fix all these with the second commandnpm run eslintnpm run eslint-fixeslint errorswith second command you can fix all the errors, if not fix it manually until you fix all the errors.

warnings are fine.

errors with eslintwe have added two files for linting and package.

json looks like itTesting your projectcoming soonProduction Phasewebpack setupenvironment variablesDockerize the appWebpack setuponce development is complete, we need to bundle our app and deploy into other environments like stage,uat and prod etc.

Let’s add webpack to our project to bundle the entire app files into a single file.

install the following to setup webpack// install webpack globalnpm install -g webpack//install webpack and webpack-cli in the projectnpm install webpack webpack-cli –save-dev// add below to scripts section in package.

json"build": "webpack"add the webpack.


js where you mention starting file and output directory and the target is important because our runtime environment is node.

when you run the below command webpack will build the entire project into single bundle file and place that in the target folder mentioned in the webpack.


jsnpm run buildwebpack buildafter the build complete, let's add the below npm script to the scripts section in the package.

json and run the command"prod": "node dist/api.


js",npm run prod //run this in the terminalEnvironment variablescoming soonDockerize the appLet’s containerize this app.

Below is the article about how to build the image and run the app in the container.

have a look:)Containerize your Node.

js Rest API and run it on DockerI recently published an article regarding production ready nodejs rest api and this article is the extension for that…medium.

comIf you want to look at the typescript version of it.

Here is the link.

How to write production ready Node.

js Rest API — Typescript versionThis article list out all the necessary ingredients for the production ready Node.

js rest api with typescript.


comThanks for reading and if you found this useful, give it a clap :).

. More details

Leave a Reply