The Web Developer The Web Developer Guide Guide

Let's see if we can help...

#Backend #Express #Node

What is Express.js? A Comprehensive Guide to All You Need to Know

What is Express.js? Express.js is a backend web framework for Node.js that provides a great selection of features for building web applications, RESTful APIs, and other server-side applications quickly and easily.

The Express.js website describes the framework as a:

“Fast, unopinionated, minimalist web framework for Node.js”

Sounds great, right? Let’s catch the Express train and find out a little more!

(That’s an awful joke and I’m not even sorry).

what is express.js? All you need to know about express.js!

How does Express.js work?

Express JS works by providing a set of methods that developers use to create web applications and APIs using node.js.

An Express.js application is typically set up by:

Install

what is express.js? Using NPM to install express.js

Install Express.js using Node Package Manager. This is done via the command line using:

 $ npm install express  

…more on this later. 

Users can use the express command to create a project with a basic Express.js application structure, which is also a really cool feature.

Define Routes

Next, developers typically define the routes for the application using Express.js router, which maps incoming requests and connects with the define handler function.

The Express.js website defines it in a little more detail:

“Routing refers to determining how an application responds to a client request to a particular endpoint, which is a URI (or path) and a specific HTTP request method (GET, POST, and so on).”

Middleware

Developers can also write custom middleware functions that handle various aspects of the request/response cycle including logging, authentication, and error handling.

According to the official guide on the Express.js website, Middleware can perform the following tasks:

  • Execute any code.
  • Make changes to the request and the response objects.
  • End the request-response cycle.
  • Call the next middleware in the stack.

Handle Requests

Developers write handler functions that deal with incoming requests, perform any necessary logic, then send the appropriate response back to the client.

Use Middleware

Developers can use built-in or third-party middleware functions to add functionality to their applications, such as serving static files, parsing request bodies, and handline cookies.

Start the Server

Developers start the Express.js server using the listen method, which brings the server to a specific port and begins listening for incoming requests.

In a nutshell

In a nutshell, the functionality for an Express.js application follows this lifecycle:

  1. The client makes a request to the Express.js application
  2. The router matches the request to the appropriate route handler function
  3. For some applications, this may now involve middleware functions to handle various aspects of the request/response cycle
  4. The handler then returns a response back to the client

What is the request/response cycle?

Since I’ve mentioned it a few times, I should probably explain what the request/response cycle actually is.

The request/response cycle refers to the sequence of steps that occur when a client (like a web browser) sends a request to a server, and the server responds by sending back, yeah, you guessed it…a response.

Typically, it runs like this:

  1. The client sends a request to the server. This request specifies the URL of the resource it wants to use, along with any relevant data (such as HTTP headers or request parameters)
  2. The server takes the request and then processes it
  3. A response is then generated by the server, in the form of data (whether it be HTML, JSON or something else), and sends it back to the client
  4. The client takes the data and processes it

What Is Express.js Used For?

So now we know what Express.js is and how it works, let’s take a look at what it’s actually used for.

Single Page Applications

Express.js can be used to create fantastic Single Page Applications (or SPAs for short).

What are SPAs?

SPAs are web applications that load all the necessary resources (such as HTML, CSS, and JavaScript) on the first request to the server and then dynamically update the content based on user interaction, without requiring a user to reload the page.

Express.js can be used to set up the routing for these SPAs so that the interactivity can happen all on the same page.

Real-Time Collaboration Tools

Express.js can be used to create several different types of real-time collaboration tools such as:

  • A chat application.
  • A collaborative document editor.
  • A whiteboard application for sharing top-level ideas.
  • A video-conferencing application.

Express.js is great for this kind of application because it makes integrating WebSocket into the framework easy.

Streaming Applications

Streaming applications deal with a lot of data. Often it’s layered. Pretty complex stuff. To handle it effectively, you need a strong framework that makes it easy to handle asynchronous data.

Express.js is your framework for this and you can build multiple different types of streaming applications too.

Such as:

  • Live streaming: real-time streaming is great because of the previously mentioned ease in which WebSockets can be integrated into the Express JS framework.
  • Video on demand: Express JS can be used to build video-on-demand streaming applications that allow users to stream pre-recorded video content. Easy integration of HLS or MPEG-DASH modules allows Express JS applications to deliver video content into manageable chunks.
  • Audio streaming: Using WebSockets, Express JS can be used to deliver audio streaming content to users.

Fintech Applications

Express .js can also be used to create Fintech Applications…

…hang on. What are Fintech Applications?

Great question – here’s our answer.

What are Fintech Applications?

Fintech Applications are applications, programs, or platforms that handle financial services. These are designed to make financial transactions easy to do, efficient, and cost-effective.

Examples of such are applications like:

  • Mobile payment apps like Paypal.
  • Digital wallets like Google Wallet or Apple pay.
  • Personal finance apps like Mint.

…and many more.

Express.js Fintech Applications

With Express.js you can build the following kinds of Fintech Applications:

  • Payment processing. Express.js can be used to build a solid payment processing application that can utilise powerful 3rd party APIs such as Stripe, Paypal, or Klarna.
  • Trading platform. Express.js can also be used to build trading platforms to buy or sell cryptocurrencies, utilising the Coinbase or Alpha Vantage APIs.
  • Personal Finance management. Express.js can be used to make an application to track personal finances, set financial goals, and manage investments. To do this, Express JS can utilising such APIs as Plaid or Yodlee to securely connect to users’ bank accounts and retrieve transaction data.
  • Crowdfunding platform. With Express.js, an application can be built using Paypal or Stripe APIs to serve as a great crowdfunding platform.

Why You Should Use Express.js

what is express.js? express.js features

You should use Express.js for many reasons.

Easy to Learn

Express JS is a simple framework that’s easy to pick up for developers already familiar with JavaScript.

Flexible and Speedy

Because Express.js is an unopinionated framework, it’s flexible to allow you to integrate any number of additional modules to suit the needs of your application with ease and no fuss.

As well as being unopinionated, it’s a minimal framework. This means there’s no clutter and it’s extra speedy.

Part of the MEAN and MERN Stacks

With Node.js at the foundation, many tech stacks are combined to create a full-stack system. These are often combined to create cool names.

MEAN and MERN tech stacks are probably the most popular, with the E in each stack representing Express JS, the N in each stack representing Node.js, and the M in each stack representing MongoDB.

The A and R letters stand for Angular and React respectively.

Easy Integration

As touched upon elsewhere in this article, another reason why you should use Express.js is the fact that you can easily integrate other modules during application creation. Anything from MongoDB to Paypal is fair game.

Scalability

Express.js applications are highly scalable and this is proven by the number of big companies using the technology.

With Express.js being flexible, lightweight, and built on top of Node.js, Express inherits many of the scalability features that comes with Node.

Community Support

Express.js has a large community that regularly contributes to the project, developing features, bug fixing, providing support in the forums, writing documentation, and adding tutorials.

Powerful Routing System

Express.js has a robust and flexible routing system that allows developers to define routes that correspond to specific URLs and HTTP methods. 

This makes it easier to handle different types of requests and route them to the correct functions or handlers.

In addition, Express.js routing allows for:

  • Support for multiple HTTP methods. Express allows developers to define roots for GET, POST, PUT, and DELETE HTTP methods and therefore making it easier to respond with the appropriate data.
  • Parameterisation. Express also allows developers to define routes with parameters, such as /users/:id. This makes it easy to handle dynamic URLs and deal with data from the request.
  • Middleware. Express allows developers to attach middleware functions to routes, which can perform tasks such as authorisation, logging, or error handling. This makes it easy to add common functionality to multiple routes – AKA a more single source of truth. This will make the code easy to maintain going forward.
  • Route groups. Express allows developers to group related routes, which makes it easier to apply middleware and other settings to multiple routes at once.
  • Route nesting. Express allows developers to nest routes inside other routes, which makes it easier to make complex routing structures.

Limitation of Using Express.js

So now that we’ve covered all of the positives of using Express.js, let’s take a look at some of the negatives.

Potentially Steep Learning Curve

Express.js is a simple and unopinionated framework, which means it doesn’t have tons of functionality out-of-the-box and also means to build a full application a developer is going to need to use several modules.

As the application grows and gets more complex, more modules will be required.

This might be quite daunting for a new developer and they might find it difficult to learn, especially if they’re unfamiliar with Node.js and how the runtime works.

Even if a developer is familiar with Express and Node, if they come to a project late and it’s already complex with a lot of 3rd party functionality, it could still be difficult to pick it all up. 

Lack of Built-In Functionality

One of the things that makes it great, could be a disadvantage for someone looking for a solution that has everything they need out of the box.

As I previously mentioned, Express.js is simple and unopinionated – designed for developers to add modules to build additional functionality.

If someone isn’t looking for that, then this is a disadvantage for them choosing the Express framework.

Security

Because of the nature of 3rd party modules, you’re relying on multiple developers to keep their code up-to-date with the latest security patches.

This is particularly a concern if a module or your application deals with potentially sensitive user data.

How To Create an Express.js App

Now comes the exciting bit: getting started with Express JS code!

Installing Express.js

First, let’s install Express.

Get Your Directory

In your command line of choice (Visual Studio Code terminal will do us just fine), get to where you want to install the code. 

If you’re using Visual Studio Code, just click the Terminal option in the main menu, then click New Terminal. 

This will open your command line terminal in the location of your current project.

If you need to go to a subfolder from here, you can use the CD (change directory) command to reach where you need to be.

For example, if you’re in your main project folder and want to install express in your app subfolder, you could just do:

Cd app/

For me, I wanted to go to my tutorials folder and then my express folder, so I did:

Cd tutorials/

And then:

Cd express/

Install Command

Now we’re in the right directory, let’s run the install command:

$ npm install express

Here we’re using Node Package Manager to grab the modules from the online Node directory and then install them.

Hello World Example

Now we have Express installed, let’s set up a super simple Hello World app. 

Create Your JS File

In the directory where you installed Express, create a JS folder. Call it app.js./

Then copy and paste the following into your app JS file:

const express = require('express')const app = express() 
const port = 3000

app.get('/', (req, res) => {
  res.send('Hello World!')
})

app.listen(port, () => {
  console.log(`Example app listening on port ${port}`)
})

Next, in your terminal run:

node app.js

This will run the app locally on the port we’ve specified. So, in the example above port 3000.

Essentially, we have a local server running on port 3000 and we can test it’s working by typing http://localhost:3000 in your web browser.

Let’s Add a New Page

So, in the above example, we have Express listening for ‘/’ AKA the localhost:3000 index page. But what if we wanted to add a new page? What would we do then?

Let’s take a look – we’ll add an about page! In your code, add the following:

app.get('/about', (req, res) => { 
    res.send('About page innit')
})

Run your app again with:

node app.js

Now, in your web browser go to https://localhost:3000/about and you will see the content of your about page.

So…what is Express.js?

Let’s sum up everything we’ve covered here.

What is Express.js? Express.js is:

  • Is a fast, straightforward, minimal, and unopinionated framework for Node.js.
  • Express JS provides developers with a set of methods that will help create web applications and APIs.
  • Express JS can be used to create SPAs, Real-time Collaboration Tools, Streaming Applications, and Fintech Applications.
  • The advantages of Express.js are that it’s easy to learn if you’re used to Node.js and the way it works, it’s flexible and speedy, it’s part of the MEAN and MERN tech stacks so widely adopted, it’s easy to integrate, it’s easy to scale an Express JS app, great community support, and it comes with a powerful routing system right out of the box.
  • The disadvantages of Express.js is that it can be hard to learn if you’re not used to the Node.js tech stack and how it works, or if you come to a complex application late into the project, lack of built-in functionality, and potential security issues.
  • Installing and creating a simple routing takes minutes to set up.

Further Reading

#Backend #Express #Node
Avatar photo Kris Barton has been coding for over 20 years and has worked at some of the biggest companies in the UK. He's worked in Frontend, Backend, Fullstack, and even System Architecture. He's also forgotten more than he knows.