Express 🤔 🛠

July 03, 2020

Overview and practice

Express.js is the best choice when it comes to building web applications with Node.js.

However, when saying web applications with Node.js, it's often not for anything visible in the browser (excluding server-side rendering of a frontend application). Instead, Express.js, a web application framework for Node.js, enables you to build server applications in Node.js.

👉As a backend application, it is the glue between your frontend application and a potential database or other data sources (e.g. REST APIs, GraphQL APIs). Just to give you an idea, the following is a list of tech stacks to build client-server architectures:

👉 React.js (Frontend) + Express.js (Backend) + PostgreSQL (Database)

👉 Vue.js (Frontend) + Koa.js (Backend) + MongoDB (Database)

👉 Angular.js (Frontend) + Hapi.js (Backend) + Neo4j (Database)

Express.js vs. Node.js

There isn’t really any competition between Node.js and Express.js. In fact, the first thing to know about Express.js is that in a way Express.js is Node.js. Express.js is a framework that runs inside Node.js.

Node.js is a JavaScript runtime. It lets you run JavaScript code outside of your web browser. JavaScript is pretty useful, and you can do a lot of stuff with it. Being able to run JavaScript programs outside of a browser is especially useful when coding server-side backends for web programs in JavaScript. This is because most front end web programming is already written in JavaScript, so letting those programs communicate with a backend that’s also JavaScript makes for better functionality and speed.

Express.js is Server side

The only problem with Node.js is, that while it’s very useful for setting up servers, it wasn’t designed specifically for that application. That’s where Express.js comes in. 👉 Express.js is a framework designed to utilize Node.js specifically for running web servers. It takes out the effort of having to code complex server-side integrations for Node.js. It’s kind of like a server in a box for JavaScript; it helps you easily use templating solutions and organize your application’s routing with readable and well-organized code.

Express.js comes with a number of built-in features that work well in the server environment. These benefits include:

👉 Faster server-side programming:

Express.js takes a number of commonly used Node.js features and packages them into functions. These functions can be called anywhere in the program. This can save hundreds of lines of code by just calling these functions instead of having to write them.

Routing: Node.js has a routing mechanism already, but it’s a little rudimentary.

Express.js features are significantly more advanced and efficient routing mechanism that allows the web application to keep web page states through just their URLs.

Templating:

👉 Express.js also features a templating engine. This lets the server-side build the webpage on its end, then send all of those values to the front end to display. This allows for dynamic content and reduces the load on the client-side.

Express.js Lives in the Stack

Express.js is at its best when implemented in a stack (a stack is all of the code required to run a web application, from the front end user’s interaction all the way back to the backend processes that result from that click). Front end and back end development are usually split, for good reason. However, it usually means that different developers are working on different parts of a puzzle that, in the end, needs to fit together.

Express.js functions powerfully as the second half to JavaScript front end applications, allowing users to create an entire stack that sticks to one language.

👉 This is incredibly efficient because when it’s time for the front end developers to connect with backend dev work, there are fewer integration issues. It stands to reason that things will (usually) work out smoother if it’s all coded in the same language.

Let's put hands on Practice

Installation

Express is very simple to install. Simply install it via npm as you would with any other package.

$ npm install express --save

Usage

Now that Express is installed, here’s what the most basic server looks like:

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

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

app.listen(3000, () => console.log('Beginners app listening on port 3000!'))

Now, run this script, and navigate to localhost:3000 in your browser. You should see the message A Beginners approaches! in your browser window!

What exactly does it mean? 🤔

Let’s go over each section of this code to explain how Express works.

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

👉 The first line here is grabbing the main Express module from the package you installed.

👉 This module is a function, which we then run on the second line to create our app variable.

You can create multiple apps this way, each with their own requests and responses.

app.get('/', (req, res) => {
  res.send('A Beginners approaches!')
})

Actually, this bite of code is where we tell Express server how to handle a GET request to our server. Express includes similar functions for POST, PUT, etc. using app.post(...), app.put(...), and so on.

These functions take two main parameters. The first is the URL for this function to act upon. In this case, we are targeting '/', which is the root of our website: in this case, localhost:3000.

The second parameter is a function with two arguments: req, and res.

👉 req represents the request that was sent to the server; We can use this object to read data about what the client is requesting to do.

👉 res represents the response that we will send back to the client. Here, we are calling a function on res to send back a response: 'An alligator approaches!'.

app.listen(3000, () => console.log('Beginners app listening on port 3000!'))

Finally, once we’ve set up our requests, we must start our server! We are passing 3000 into the listen function, which tells the app which port to listen on. The function passed-in as the second parameter is optional, and runs when the server starts up. This just gives us some feedback in the console to know that our application is running.

And there we have it, a basic web server! However, we definitely want to send more than just a single line of text back to the client.

Middleware

What middleware is and how to set this server up as a static file server! 🤔

With Express, we can write and use middleware functions, which have access to ALL http requests coming to the server. Which are:

👉 Execute any code.

👉 Make changes to the request and the response objects.

👉 End the request-response cycle.

👉 Call the next middleware function in the stack.

We can write our own middleware functions, or use third-party middleware by importing them the same way we would with any other package. Let’s start by writing our own middleware, then we’ll try using some existing middleware to serve static files.

🛑 To define a middleware function, we call app.use() and pass it a function.

Here’s a basic middleware function to print the current time in the console during every request:

app.use((req, res, next) => {
  console.log('Time: ', Date.now())
  next()
})

The next() call tells the middleware to go to the next middleware function, if there is one. 👉 ❗️This is important to include at the end of our function - otherwise, the request will get stuck on this middleware.

We can optionally pass a path to the middleware, which will only handle requests to that route. For example:

By passing '/nest' as the first argument to app.use(), this function will only run for requests sent to localhost:3000/nest.

Now, let’s try using existing middleware to serve static files. Express comes with a built-in middleware function: express.static. We will also use a third-party middleware function, serve-index, to display an index listing of the files.

First, inside the same folder where the express server is located, create a folder called public and put some files in there (any files will do, perhaps some images/avatars ).

Then, install the package serve-index:

\$ npm install serve-index --save

Import the serve-index package at the top of the server file:

const serveIndex = require('serve-index')

Now, let’s include the express.static and serveIndex middlewares and tell them the path to access from and the name of our folder:

app.use('/beginners', express.static('public'))
app.use('/beginners', serveIndex('public'))

Now, restart your server and navigate to localhost:3000/beginners. You should see a listing of all your files!

Up next