Practical Guide | Building Node.js Apps

In this article, we will show you how to use Node JS for building a real world scalable web app. We’ll talk about Node’s advantages and disadvantages, as well as deployment options — including IaaS, PaaS & BaaS. Lastly, we’ll show you how to deploy a Node app by using Back4app.

What is Node.js?

Node.js is a runtime JavaScript engine built on Chrome’s V8 JavaScript engine for creating apps that works across different platforms. Better still, it is opensource. It helps JavaScript developers write codes that works on the backend and frontend as well. It can be used for writing scripts that run on the server, build real-time apps,  single-page application frameworks, web-based games, and other online tools. That is why many companies rely on node js for building real world scalable web apps.

Node makes use of events and asynchronous architecture that performs exceptionally well. It’s blazingly fast and empowers developers to build high performance apps that scales without hassles.

NodeJS was first launched to the JavaScript ecosystem in 2009. It instantly become a popular development tool, and it continues to be a very active project.

Node’s popularity has continued to increase over the years, and its acceptance has surged in recent times. Popular companies like Netflix, Microsoft, LinkedIn, and IBM use Node to help expand their reach across the globe. It’s a simple solution that’s great for all businesses, whether they’re startups or full-size operations with millions of customers.

Let’s take the time to explore Node JS benefits and demerits.

Node.js Benefits

Efficiency

Node uses by Google’s high-performing JavaScript engine popularly known as V8. This engine can compile codes into machine code and execute it very fast.

Node.js is a powerful, lightweight platform that can handle an event loop — it does non-blocking I/O operations with JavaScript that can only handle single-threads. That is why Node.js is one of the fastest-growing development platforms on the market.

Highly Scalable

Node.js is quite versatile and has great scaling capabilities; it scale apps horizontally or vertically. Horizontal scaling requires adding extra nodes while vertical scaling means the adding extra resources to a particular node. The platform’s scalability makes it an excellent option for both small startups and big companies with massive concurrent users like PayPal, LinkedIn, and Netflix. 

Node.js is also a good choice if you’re building microservices architectures that allows developers to build tiny components that works with continuous delivery pipelines. Plus, it’s practical way to use node js for building real world scalable web apps

Easy to learn

Node’s basis in JavaScript makes it extremely easy to learn for developers who already know the basics of JavaScript. It doesn’t have a steep learning curve and can be mastered in as little as a few weeks. Node’s simplicity makes it a great fit for all types of projects.

Convenient and easy to learn

Since Node is a programming language based on JavaScript, it is easier coders that write JavaScript. Node doesn’t require an in-depth understanding of JavaScript and be learned quickly. Node’s is not complicated, making it the perfect choice for more complex projects.

Complete projects faster

The faster you can get your product to the market, the better. Luckily, Node allows people to develop and publish quickly so that their product is available quickly.

Node’s simple design and large collection of npm packages expedite development assignments. Developers can use codes from Github and other online sources as templates to get things off the ground quickly.

Tested and Trusted Platform

Node is a well-known development tool for the past 8 years and counting. It is at the heart of software used by large companies like LinkedIn, Netflix, and eBay. Node stability fueled by decades-long experience makes it a reliable platform for enterprises at large.

Node.js is a part of many startups’ tech stacks used in development assignments like:

  • MERN
  • MEAN
  • DERN

Active Community

Node.js has a large community of talented developers who keep adding codes the project to improve it.  If you ever get stuck with a challenge, you can ask for help from other developers online. Due to Node’s popularity, it isn’t hard to sample codes and existing solutions that others have shared on GitHub.

One of Node.js’s best features is Node Package Manager, called npm. It empowers developers to leverage custom-made JavaScript packages to develop their applications. These packages can dramatically reduce the complexity and development costs of a project. Presently, there are over a million npm packages.

Node.js Drawbacks

Complex Tasks Reduce Performance

Node.js does have some drawbacks, including its lack of capability to handle tasks that requires extensive computing. These days, nearly every program and algorithm need multi-threading to achieve optimal results. This is because Node.js runs on JavaScript that was originally designed to handle frontend single-thread operations.

However, Node.js version 10.5, promises to support for multithreading. This means developers now have access add extra threads when the need arises. For projects with demanding requirements, such as computing or parallelization, Node.js might not be the best choice of programming language.

Asynchronous programming style

Node.js is an asynchronous technology that depends on callbacks. While callbacks are a helpful functionality, they become more challenging to manage in code as they increase in number. Additionally, if nested too deeply, your code might become very confusing and unmanageable, which many programmers refer to as “callback hell.”

If you use clean code principles, then you can avoid the problems that come with asynchronous programming like callback hell.

Callback hell and other problems of asynchronous programming can be easily avoided by following clean code principles.

Unstable API

Perhaps the biggest downside to Node.js is its API instability. Node’s API updates frequently with backward compatibility issues that can make codes to stop working. As a result, developers must keep up with the latest changes to ensure their source code works with the latest version of Node.js API.

The lack of an extensive library support system

JavaScript has a lot of capabilities and libraries to take advantage of. However, a big downside is that the library system is woefully underdeveloped. That is why JavaScript developers are compelled to write codes for common tasks such as parsing, databases, image processing, XML  handling, and more.

Bloated and underdeveloped Module Registry

Thousands of codes are written by the massive developers in the Node.js communities. So you have access to lots of codes. But the drawback is that npm does not have a way to monitor the quality or workability of a module code. 

As Node versions change, modules can suddenly become deprecated or broken and developers are compelled to seek alternatives. There are instances where modules were hacked and injected with malicious codes. Due to this, it’s tough finding modules that can be used in a business setting.

While we consider npm an awesome technology, you should take a cautious approach to install modules arbitrarily.

Node.js Deployment Options

You can deploy Node.js applications in many ways, but generally speaking, they can be divided into four groups:You can deploy Node.js applications in many ways, but generally speaking, they can be divided into four groups:

  1. Traditional hosting
  2. IaaS – Infrastructure as a Service
  3. PaaS – Platform as a Service
  4. BaaS – Backend as a Service

See the following pyramid showing the hosting options in their various abstraction levels.

Cloud deployment models

You can effectively handle these abstraction layers with development options.

IaaS vs PaaS vs BaaS

Let’s review the groups one after the other. This article won’t go into detail on how traditional hosting works since you probably already know how it operates.

IaaS services, such as Amazon Web Services

Infrastructure as a service offers resources for hosting, like web servers and operating systems, network infrastructure, and storage. IaaS providers give organizations access to the tools they need through advanced dashboards or APIs. You can then customize your space by moving things around and managing your server properties with ease. 

One of the best things about IaaS is that it can easily be scaled up or down, depending on what resources are needed. This means you’re not paying a set fee every month. Instead, you get billed for the resources your business consumes.

This cloud computing solution came to the market in the year 2010 and became an industry standard. Even with new types of technology like microservices, IaaS remains a practical way to use node.js for building real world scalable web apps

IaaS gives you extensive control over these resources, it also offers the greatest flexibility. This can be a downside because it requires that you manage things like applications and operating systems for yourself which are time-consuming.

A few examples are:

  • Rackspace
  • AWS
  • GCP
  • Azure
  • DigitalOcean
  • Linode

PaaS services like Heroku 

Platform as a Service offers lots of the tools they need to build, manage and deploy apps in a few clicks. PaaS is an all-in-one solution for those who don’t want to spend time building infrastructure. A PaaS vendor’s ready-made tools empower you to build, customize and test apps so you can deliver your app in just a few steps!

Platform as a service (PaaS) is a service that “hosts” your app so you don’t have to worry about the underlying system. It does a lot of the hardwork for you, including server management, providing backups, and more.

The Advantages of PaaS include:

  • Low-code development
  • Increased availability
  • Scalability
  • Lower development costs
  • Higher security
  • Faster app development

One shortfall of this PaaS solution is that it makes you rely on the provider’s capabilities. It means you could become locked in and lose control over changes. But the upside is that it takes less time to build and maintain your application, which is a boon for those who don’t have a developer.

Some PaaS services are:

  • Heroku
  • Elastic Beanstalk
  • Railway.app
  • Google App Engine
  • CapRover

BaaS platforms like Back4app

BaaS is a backend application platform that provides an automated backend. It also includes features such as cloud code functions, social media integrations, push notifications, email notifications, user management, and more-all the tools you need to successfully run your business.

Backend as a Service (BaaS) is excellent for developers who want to focus on the  frontend and scaling your business while outsourcing their backend development. Typically, these backends are built with custom SDKs and APIs from the service provider. As such, apps development and management becomes easier and the code cleaner.

BaaS combines IaaS and PaaS, but with the added services from the backend. By using BaaS, teams are able to dramatically finish projects faster, lower development costs, and reduce development teams to save costs.

BaaS has been used extensively for development projects like creating MVP (Minimum Viable Product), simple web apps, and enterprise apps. It is one of the best options for someone seeking a practical way to use node.js to build real-world scalable web apps.

The drawbacks are that there’s less customization and flexibility than in IaaS or PaaS, and some platforms are not open-source while others lock-in their customers.

A few BaaS examples:

  • Back4app
  • Backendless
  • Firebase
  • Parse

Node.js Deployment Procedure

In this section, we shall take a look at how Back4app can help you build and deploy Node JS applications.

Back4App Quick Overview

The offering a wide range of features and benefits that enhances development assignments make Back4app one of the best Backend as a Service (BaaS) solutions available today. With Back4app, you can focus on what’s most important to your business while leaving other considerations, such as backend support or infrastructural needs, to us.

The powerful features designed to enhance developer efficiency include SDKs for all your favorite frameworks, including Android, Angular, Node.js, React Native, Flutter, and iOS.

Back4app has the following features

  • Scalable hosting
  • Spreadsheet-like database
  • GraphQL and REST APIs
  • Live Queries
  • Push-Notifications
  • Email-Notifications

With Back4app, you can enjoy a simple and predictable pricing plan. It’s great for apps of all sizes, with a free plan that is perfect for creating prototypes and evaluating the platform.

Project Overview

In this section, we’ll code up a TODO web app in Node.js with the Express framework coupled with Parse data storage and templates in Twig. The app will support CRUD operations (create, retrieve, update and delete) and we’ll populate it with items from a good API.

See how the app works here

Prerequisites:

  • Knowledge of databases and ParseJS
  • Ability to work with a templating engine
  • Basic knowledge of Express
  • Basic knowledge of Node.js

Back4app CLI

To carry on from here, you must use a Back4app account. You can sign up for a free account here or simply log in if you have an account already.

The Back4app CLI presents the user with a command-line tool for performing various tasks on the Back4app development platform.

Run the following command to Install the CLI on Linux or a Mac:

$ curl https://raw.githubusercontent.com/back4app/parse-cli/back4app/installer.sh | sudo /bin/bash

The command simply downloads the CLI library and stores it, ready for use. 

You must authenticate your account before you can start using the CLI.  This step requires that you create an account key. Simply go back to the Back4app dashboard click (your username) > Account Keys

Back4app account keys

After that input a unique name for your key and press “+” to generate it. Save the key in a safe place since you will need it to complete the steps.

Back4app account keys

The next step is to list your app to know that the command worked.

$ b4a configure accountkey

Input your account key or press ENTER to generate a new one.       
NOTE: on pressing ENTER we'll try to open the url:                 
        "http://dashboard.back4app.com/classic#/wizard/account-key"
in default browser.
Account Key: <YOUR_GENERATED_ACCOUNT_KEY>
Successfully stored account key for: "<YOUR_EMAIL>".

To make sure the authentication worked, try listing your apps:

$ b4a list

These are the apps you currently have access to:

Kindly note that no app will be listed if the app is a new one, just like mine. 

Create App

Next, we shall create an app on Back4app.

Run:

$ b4a new

Would you like to create a new app, or add Cloud Code to an existing app?
Type "(n)ew" or "(e)xisting": n
Please choose a name for your Parse app.
Note that this name will appear on the Back4App website,
but it does not have to be the same as your mobile app's public name.
Name: nodejs-back4app
Awesome! Now it's time to set up some Cloud Code for the app: "nodejs-back4app",
Next we will create a directory to hold your Cloud Code.
Please enter the name to use for this directory,
or hit ENTER to use "nodejs-back4app" as the directory name.

Directory Name:
You can either set up a blank project or create a sample Cloud Code project
Please type "(b)lank" if you wish to setup a blank project, otherwise press ENTER: 
Successfully configured email for current project to: "<YOUR_EMAIL>"
Your Cloud Code has been created at /dev/nodejs-back4app.
  1. Create a new or existing app: new
  2. Pick an app name: Pick a custom name
  3. Directory name: press ENTER
  4. Blank or sample Cloud Code Project: press ENTER

Running the command will create a folder with the structure below

nodejs-back4app/
├── cloud/
│   └── main.js
├── public/
│   └── index.html
├── .parse.local
└── .parse.project
  1. cloud directory stores all cloud codes and functions
  2. public  stores files such as images, stylesheets & more
  3. parse.local and .parse.project stores Parse configuration

After this step delete  main.js and index.html files. You don’t have a need for them any longer.

Web Hosting

We need to create a hosting Back4app to create a Node.js app and then make it available to the world.

To activate the web hosting feature on your app, first navigate to your Back4app dashboard, then click “App Settings” towards the let of the page. Finally, locate “Webhosting and Custom Domains” and click on “Settings” again.

Click “Activate Back4app Hosting” and choose a subdomain name. I’ll choose to use nodejsback4app:

Back4app web hosting

Finally, Click Save.

You can access your app from the URL structure below:

https://<your_subdomain>.b4a.app/

You can as well use a custom domain if you like.

Express with Cloud Code Functions

After creating the app, let’s start writing the code.

Change the directory to cloud and make package.json file inside it:

The platform fetch modules through npm with this file. We included body-parser as it is required to parse requests later.

The next step is to create a file named app.js in the “clouds” folder.

We’re using this file to activate and configure Express. In the next step, we’ll define an endpoint for sanity check purposes. If you look here, you’ll see that everything is set up for you by Back4app. Defining apps or setting requirements is not necessary!

The next step is app deployment process.

$ b4a deploy

Uploading source files
Uploading recent changes to scripts...
Finished uploading files
New release is named v1 (using Parse JavaScript SDK v2.2.25)

With this command, you’ll upload  the source files to Back4app, configure them and make them accessible at the subdomain or custom domain you choose.

Let’s make sure this works by opening a browser and navigating to the app.

https://<your_subdomain>.b4a.app/

# Example
https://nodejsback4app.b4a.app/

This is the response what you’ll get:

Great job!

Let’s start creating the  TODO app.

Database with ParseJS

First, determine the database type you’ll use for the TODO app.

Open the Back4app dashboard and choose Database. Then click on Create a new class, use the name “Task” and set the properties as Public Read and Write.

Back4app create new class

The next step is to add columns as follows:

+-----------+-------------+---------------+----------+
| Data type | Name        | Default value | Required |
+-----------+-------------+---------------+----------+
| String    | name        | <leave blank> | yes      |
+-----------+-------------+---------------+----------+
| String    | description | <leave blank> | no       |
+-----------+-------------+---------------+----------+
| Boolean   | isDone      | false         | yes      |
+-----------+-------------+---------------+----------+

App Logic

Here are the endpoints of the app.

  1. / shows the list of tasks
  2. /create creates a task
  3. /<ID> shows the task details
  4. /<ID>/delete deletes a task
  5. /<ID>/toggle toggles task status — done/undone

We shall create them next

Splitting the code into two files allows you to maintain them easily.

  1. app.js — initializes and configures the Express server
  2. routes.js — defines endpoints and their logic

A good way to build a modern web application is using an MVC architecture. You can start with Express by using express-generator.

All you have to do is delete all of app.js, and then enter the following text:

  1. Make Twig as the default view engine
  2. The file routes.js takes over routes definition

Next, create routes.js file and paste the code below:

The routes we referenced earlier were defined and Parse was used to store and change the data. All the routes are async because Parse must respond first, and the majority of the codes are wrapped in try-catch blocks 

Check out the JavaScript Guide for more information on ParseJS.

Let’s add view templates to the endpoints next.

Download the template files from  GitHub repo and place them in the views folder within the clouds folder.

This is how the final directory structure looks.

nodejs-back4app/
├── cloud/
│   ├── views/
│   │   ├── base.twig
│   │   ├── create.twig
│   │   ├── error.twig
│   │   ├── index.twig
│   │   └── task.twig
│   ├── app.js
│   ├── routes.js
│   └── package.json
├── public
├── parse.local
└── parse.project

Finally, add twing to package.json to activate support for Twig:

Deploy the app:

$ b4a deploy

Uploading source files
Uploading recent changes to scripts...
Finished uploading files
New release is named v2 (using Parse JavaScript SDK v2.2.25)

That is all. Simply wait for some time and open the app URL to ensure everything is perfect.

Public Files

while Back4app serves files in the public folder automatically, you must edit your configuration slightly to access files from your public folder in Express templates.

Go to app.js and add the following entries.

Finally, use the relative path to reference the public files inside your template.

<img src="/back4app.png" alt="Back4app Logo">

For instance, the code above displays the image public/back4app.png.

Conclusion

Node was released in 2009, and since then it’s steadily grown and improved. It’s one of the top tools developers trust for building real world scalable web apps.. Node apps can use IaaS, PaaS, and SaaS deployment options. For each solution, there are benefits and demerits to evaluate when making a decision about where your app should be deployed.

If you want to deploy build a real world scalable app like a pro, Back4app offers an open-source, single-click install solution with many features. It’s great because it empowers you to concentrate on other important things while the platform’s experts ensures the backend works perfectrly.

Visit nodejs-back4app repo to download the source code.

FAQ

Node.JS Definition

Node.js is a JavaScript runtime that’s built on Chrome’s V8 engine for quickly building fast and apps that scale seamlessly.

Mention the Benefits and Drawbacks of Node.js

Benefits: High performance, scalability, and access to a vast community.
Demerits: asynchronous, not stable, and underdeveloped module registry.

Explain the Node.js app deployment procedure

– Select between PaaS, IaaS, and BaaS options
– Select a hosting option
– Choose your preferred hosting vendor
– To learn how to build a successful digital product, read our article found here


Leave a reply

Your email address will not be published.