How to deploy a Node.js application?

How to deploy a Node.js application?

In this article, we’ll explain how to deploy a Node JS application. We’ll talk about Node’s advantages and disadvantages, and deployment options — including IaaS, PaaS & BaaS. Lastly, we’ll deploy a Node application to Back4app.

What is Node.js?

Node.js is an open-source and cross-platform JavaScript runtime built on Chrome’s V8 JavaScript engine. Node aims to allow JavaScript developers to go full-stack by allowing them to code server-side operations. Its use cases include server-side scripting, real-time applications, streaming web applications, single-page applications (SPAs), collaboration tools, and web games.

Node has an event-driven architecture capable of asynchronous I/O. It is blazingly fast, because of its ability to compile JavaScript into native machine code. It can handle a tremendous amount of active connections and allows developers to easily build scalable high-performant applications.

The technology was first introduced back in 2009 by its creator Ryan Dahl at the annual European JSConf. It immediately became one of the most interesting pieces of software in the JavaScript ecosystem.

Node’s popularity peaked in 2017 and remains high. It is one of the most popular development tools used by a lot of multi-million companies like IBM, LinkedIn, Microsoft, Netflix, and so on. Its simplicity and ability to scale make it a great fit for all company sizes — including startups.

In the next two sections, we’ll dive into Node’s advantages and disadvantages.

Advantages of Node.js

High performance

As mentioned in the introduction Node is powered by Google’s high-performance JavaScript engine. V8 can compile and execute JavaScript at a lightning-fast speed, mainly because it compiles JavaScript into native machine code.

Node also uses an event loop which allows it to perform non-blocking I/O operations — despite JavaScript being a single-threaded programming language. This makes it one of the speediest options on the market.

Scalability

One of the key benefits of Node.js is its ability to scale. Node applications can scale horizontally as well as vertically. Horizontal scaling is achieved by adding additional nodes to an existing system, while vertical scaling means adding additional resources to a specific node. The platform’s great scaling options make it appropriate for startups as well as big companies with tens of millions of daily users like LinkedIn, Netflix, and PayPal.

Node is also well-suited for microservices architecture, allowing developers to create small components that fit into a continuous delivery pipeline and that can easily scale on demand.

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.

Faster time to market

Time to market is one of the essential benchmarks of a lot of development teams. Everyone wants to get their product to the market as soon as possible and Node allows you to do just that.

Node’s simplicity and the vast amount of npm packages drastically reduce time to market. There are a bunch of open-sourced projects on GitHub and other platforms that can be used as templates to get your project up and running as fast as possible.

Battle-tested tool

Node is a battle-tested and mature tool that has been around since 2009. Its stability has been tested by big companies like eBay, Netflix, and LinkedIn which have millions of daily users.

Due to its awesome perks Node is included in a number of tech stacks (usually in combination with Express and a NoSQL database). Some of the tech stacks with Node include:

  • MERN
  • MEAN
  • DERN

Great community

Node.js has a strong and active community of developers and enthusiasts who keep contributing to Node to make it better and better. In case you ever get stuck on a problem or have a question there are a bunch of different places where you can look for help. Due to Node’s popularity, it isn’t hard to find already-made solutions and code on GitHub.

Another great thing about Node.js is its package manager named npm (Node Package Manager). Npm allows developers to push and use ready-made JavaScript packages instead of reinventing the wheel. The packages can significantly reduce the development cost and complexity of applications. At the time of writing, there are more than 1.3 million packages hosted on npm.

Limitations of Node.js

Decreased performance for complex tasks

The biggest drawback of Node.js is its inability to perform tasks that require heavy computing. These days a lot of programs and algorithms require parallelization to yield optimal results. As you already know Node.js is based on JavaScript, which was designed to be a single-threaded frontend language and doesn’t support multiple threads.

With the 10.5 update, the Node.js team rolled out multithreading support in form of worker threads. This module allows developers to leverage additional threads from a thread pool. Even with the worker threads Node still isn’t appropriate for heavy computing. If your project requirements include complex calculations, heavy computing, or parallelization you might be better off with another programming language.

Asynchronous programming model

Node.js uses the asynchronous programming model. Due to this it heavily relies on the use of callbacks. Callbacks are functions that run in the background and (at some point) return a result. By using callbacks your code can become messier and more difficult to debug. Additionally, if you nest callbacks multiple levels deep you might end up with a so-called “callback hell”.

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

Unstable API

Another big problem with Node.js is its application programming interface (API) instability. Node’s API frequently changes with backward-incompatible changes that can break pieces of code. As consequence Node developers need to keep an eye out for changes and make sure their codebases are compatible with the latest Node.js API versions.

Lacking a strong library support system

JavaScript doesn’t come with a good library system compared to other programming languages. This forces a lot of developers to take on the support of various common tasks like image processing, XML parsing, object-relational mapping (ORM), handling databases, and more.

An overgrown and immature module registry

Node has a huge community of developers who produce thousands of open-source modules that are published on npm. The problem with this is that npm doesn’t implement any checks that make sure that the module code works and is well-written.

A lot of modules randomly become unsupported or break with newer Node versions and then the developers are forced to look for an alternative. In the past, some of the npm modules were also hacked and injected with viruses and crypto miners. Due to this, it’s hard to find modules that can be used in an enterprise environment.

Don’t get me wrong, I think npm is great, but you should still be careful when installing random modules.

Node.js Deployment Options

There are multiple ways of deploying a Node.js application. Generally speaking, we can split them into the following four groups:

  1. Conventional hosting
  2. Infrastructure as a Service (IaaS)
  3. Platform as a Service (PaaS)
  4. Backend as a Service (BaaS)

We can display them in a pyramid chart based on their level of abstraction:

Cloud deployment models

The deployment options take care of the following abstraction layers:

IaaS vs PaaS vs BaaS

Let’s take a look at each of the groups. We’ll skip conventional hosting since I’m sure you know how that works.

IaaS services like AWS

Infrastructure as a Service (IaaS) is a cloud computing service model that provides computing resources like servers, networking, operating systems, and storage in a virtualized environment. These cloud servers are typically provided to the organization through high-level APIs or advanced dashboards giving the clients complete control over the entire infrastructure.

IaaS is highly scalable. It enables customers to easily scale both vertically and horizontally depending on demand. IaaS vendors typically follow a pay-as-you-go model, which means that you only pay for the resources you consume.

IaaS came to light in the early 2010s and since then became the standard abstraction model for many types of workloads. Even with the rise of new technologies like microservices and serverless, IaaS remains the most popular option.

In contrast to PaaS and BaaS, IaaS provides the lowest-level control of resources in the cloud. This makes it the most flexible cloud computing model. The downside of it is that the customer is fully responsible for managing aspects like applications, OSes, middleware, and data which usually takes a lot of time.

Some typical IaaS examples are:

  • Amazon Web Services (AWS)
  • Google Compute Engine (GCE)
  • Microsoft Azure
  • DigitalOcean
  • Linode
  • Rackspace

PaaS services like Heroku

Platform as a Service (PaaS) is a cloud computing service model that provides users with a cloud environment in which they can develop, manage and deliver applications. In addition to providing computer resources, PaaS comes with a lot of prebuilt tools for developing, customizing, and testing applications. Most of the PaaS vendors allow you to get your app up and running in a few clicks!

PaaS enables users to focus on their app instead of managing the underlying infrastructure. PaaS providers do a lot of heavy lifting for you like managing your servers, operating systems, server software, backups, and more.

Some of the PaaS advantages are:

  • Faster speed to market
  • Increased security
  • Cost-effectiveness
  • Scalability
  • High availability
  • Less code required

The downsides of PaaS are that you’re most likely going to be dependent upon the vendor’s capabilities, there’s a risk of lock-in, and a lack of flexibility and control. However, Paas still allows users to build apps faster and is less of a burden to manage.

PaaS services include:

  • Heroku
  • AWS Elastic Beanstalk
  • DigitalOcean App Platform
  • Microsoft Azure App Service
  • The Fly Platform (Fly.io)
  • Render

BaaS services like Back4app

Backend as a Service (BaaS) is a platform that automates the backend side of development and takes care of the cloud infrastructure. On top of that, it provides features like user management, email notifications, push notifications, cloud code functions, social media integrations, file storage, and payments.

This allows developers to focus on the core business and building the frontend without worrying about the underlying backend and infrastructure. The frontend is usually developed via specialized APIs and SDKs offered by the BaaS vendor. This makes apps less complex and easier to maintain.

BaaS gives all of the benefits of IaaS and PaaS while including the abstraction of the backend. Teams that leverage BaaS greatly reduce time to market, lower engineering costs, and require fewer engineers.

BaaS can be used for many types of projects — including making an MVP (Minimum Viable Product), stand-alone apps or apps that require a small number of integrations & enterprise apps that are not mission-critical.

The downsides of BaaS are that it is less flexible than IaaS and PaaS, gives a lower level of control and customization, and there’s a possibility of lock-in for non-open-source platforms.

A few BaaS examples:

  • Back4app
  • AWS Amplify
  • Firebase
  • Parse
  • Cloudkit
  • Backendless

Node.js Deployment Process

In this part of the article, we’ll look at Back4app and learn how how to build and deploy Node JS application

What is Back4app?

Back4app is one of the best open-source Backend as a Service (BaaS) solutions on the market. It offers an extensive range of features and benefits to its users allowing developers to rapidly build web and mobile applications. By using Back4app you’ll be able to focus on the core business instead of worrying about the backend or the underlying infrastructure.

The solution comes with a feature-rich and easy-to-use dashboard and a command line interface (CLI). They also provide SDKs for all your favorite tools like Flutter, React Native, Node.js, Angular, Android, iOS & more!

Back4app’s key features include:

  • Spreadsheet-like database
  • REST and GraphQL APIs
  • Live Queries
  • Authentication (including social authentication)
  • Scalable Hosting
  • Push and Email Notifications

For more information on their features check out Back4app Features.

Back4app follows a simple and straightforward price model that can suit an app of any size. They offer a generous free plan (no credit card required) that is great for prototyping and testing out the platform. It includes:

  • 25k requests
  • 250 MB data storage
  • 1 GB transfer
  • 1 GB file storage

For more information about Back4app pricing take a look at the Pricing page.

Project Introduction

We’re going to code and deploy a simple TODO web application. The web app is going to support basic CRUD operations — create, retrieve, update, and delete. We’ll code it in Node.js using the Express web framework, data storage will be handled by Parse, and we’ll use Twig as the templating engine.

Click here to see the deployed app in action!

Prerequisites:

  • Basic understanding of Node.js
  • Basic understanding of Express
  • Experience with a templating engine
  • Basic understanding of databases and ParseJS

Back4app CLI

The following steps will require you to have a Back4app account. If you already have it log in otherwise go ahead and sign up for the free account.

Back4app CLI is a command-line interface that allows you to interact with the Back4app platform.

To install it on Mac/Linux run:

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

The command is going to download the latest CLI binary and store it in /usr/local/bin/b4a.

For other operating systems please refer to the official docs.

To use the CLI you’ll have to authenticate with your account. To do that you first need to generate an account key. Navigate to your Back4app dashboard and click on your username (top right of the screen), and then “Account Keys”:

Back4app account keys

To add a new account key enter a custom key name and then press “+”. Take note of the key since we’ll need it in the next step:

Back4app account keys

After you’ve successfully created the key, go back to the terminal and run:

$ 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:

If your account is brand new like mine no apps will be listed.

Create App

Moving along, let’s create a Back4app app.

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

The command is going to create a directory with the following structure:

nodejs-back4app/
├── cloud/
│   └── main.js
├── public/
│   └── index.html
├── .parse.local
└── .parse.project
  1. cloud is a directory for all the cloud code and functions
  2. public is a directory for public files like images, stylesheets & more
  3. .parse.local and .parse.project are used to store Parse configuration

Delete the main.js and index.html file since we are not going to need them.

Web Hosting

Since we’re creating a Node.js app, we need to enable web hosting for Back4app to host our app and make it publicly accessible to the internet.

To enable the web hosting feature navigate to your Back4app dashboard, select your app, click “App Settings” on the left side of the screen, and then “Server Settings”. Search for “Webhosting and Custom Domains” and click on “Settings” again.

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

Back4app web hosting

Lastly, click “Save”.

Your app is then going to be accessible at:

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

Feel free to link a custom domain to your web app as well!

Express with Cloud Code Functions

Next, let’s start working on the actual code.

Change your directory to cloud and create package.json file within it:

Back4app uses this file to download modules via npm. We added body-parser since we’ll need it later to parse requests.

Next, create another file in the clouds folder named app.js:

This file is used to initialize and configure Express. We also defined an endpoint that is going to be used as a sanity check in the next step. As you can see we didn’t need to define app or require any dependencies since Back4app does that for us automatically.

Next, deploy the app:

$ 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)

The command is going to upload your source files to Back4app, configure everything and make your app available at the subdomain you’ve chosen in the previous section.

To make sure it works, open your favorite web browser and navigate to your app:

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

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

You should get the following response:

Good job!

In the next sections, we’ll start working on the actual TODO app.

Database with ParseJS

Let’s define the database models for the TODO app.

Navigate to the Back4app dashboard and select “Database” on the left side of the screen. After that click on “Create a new class”, name it Task and make sure to tick “Public Read and Write enabled”:

Back4app create new class

Next, add the following columns:

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

App Logic

The app is going to have the following endpoints:

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

Let’s create them.

To make our cloud code more maintainable, we’ll split it into two files.

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

An even better approach to building modern web apps is to use a Model-View-Controller (MVC) architectural pattern. A good start with Express is to use express-generator.

Go ahead and replace app.js contents with the following:

  1. We set Twig as the default view engine.
  2. Routes are no longer defined in this file, but rather in routes.js.

Next, create routes.js and put in the following code:

We defined all the routes mentioned above and used Parse to manipulate and store the data. As you can see all the routes are async since we have to wait for Parse to respond. Additionally, most of the code is wrapped in try-catch blocks in case something goes wrong.

For additional information on ParseJS take a look at the JavaScript Guide.

Next, let’s accompany the endpoints with view templates.

Create a views folder within the clouds folder, download the template files from GitHub repo and place them in the views directory.

Your final directory structure should look like this:

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

Lastly, add twing to package.json to enable Twig support:

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)

And you’re done. Wait for a few minutes and then visit the web app to make sure everything works.

Public Files

As mentioned in the previous section Back4app automatically serves files located in the public folder. To use them in your templates you’ll have to slightly modify your Express settings.

Go to app.js and add the following lines:

You can then reference public files in your templates via the relative path:

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

Displays the image located in public/back4app.png.

Conclusion

Node has been steadily growing and improving since its release in 2009. It is one of the best tools that allow developers to easily build scalable high-performant applications. Node apps can be deployed on different solutions like IaaS, PaaS & SaaS. They each have their advantages and disadvantages that should be considered when picking the deployment option.

One of the easiest ways to deploy Node applications is by using Back4app — an open-source BaaS solution with plenty of features. Back4app is great since it allows you to focus on what’s improtant while outsourcing the backend and its deployment.

Get the final source code from the nodejs-back4app repo.

FAQ

What is Node.JS?

Node.JS is a platform built on Chrome’s JavaScript runtime for easily building fast, scalable applications.

What are the advantages and disadvantages of Node.JS?

Advantages: performance, scalability, community
Disadvantages: unstable, immature module registry, asynchronous

How to deploy a Node.JS application?

– Choose your deployment model
– Options are IaaS, PaaS, BaaS, SaaS
– Choose your hosting vendor
– Read the article for details on how to build and deploy an application


Leave a reply

Your email address will not be published.