What Is the Express Node.js Framework?

In this tutorial we'll learn about Express, the free and open-source Node.js web application framework. Built on top of the Node.js built-in http module, Express helps us set up routing and handle the request/response cycle.

In this written and video tutorial, we'll take a look at some of the features of Express, learn what it can offer us that the built-in HTTP modules in Node.js can't, and explain why it's a great tool in any Node developer's toolbox.

By the end of this tutorial, you should be able to:

  • Understand the benefits of working with a web framework like Express
  • Identify core components that make up the Express framework
  • Learn how Express uses middleware to extend its capabilities

Goal

Understand core concepts of the Express server Node.js framework, including how it helps create web applications.

Prerequisites

  • None

Watch: What Is the Express Node.js Framework?

Express.js overview

The most common use for Node.js is writing Web applications, and a large percentage of these web applications today are using Express.js as their server framework. Express can be used to create JSON APIs, Server-side rendered web applications, or Microservices.

But why? You don't need Express to create a basic HTTP server with Node.js. You can do that using the built in http module:

const http = require("http");

const server = http.createServer((req, res) => {
  res.writeHead(200, { "Content-Type": "text/plain" });
  res.write("Hello World");
  res.end("\n");
});

server.listen(8000, () => {
  console.log(`Server listening on port 8000`);
});

This code creates a basic HTTP server that listens to requests on port 8000 and returns "Hello World".

For something that simple, you don't need Express. But when are things that simple?

According to the Express website itself, Express is a "Fast, unopinionated, minimalist web framework for Node.js". In our own words, Express (and the other web frameworks in the Node.js ecosystem) makes developing and maintaining a web server much friendlier than doing it using built-in Node.js utilities.

Express uses those built-in utilities under the hood, but provides you with a set of common handlers, settings, utilities, and other tools which greatly improve the experience and speed of creating a web server. The Express framework comes with the basics of what you need to get started, and doesn't impose any strict rules on how you use those tools to create your application.

The community-supported ecosystem around Express provides countless extensions in the form of "middleware" (more on that later) to add any kind of functionality or help you accomplish just about any task you might want. This combination of sane defaults and common tools combined with the rich ecosystem is what has made Express the most popular server framework for Node.js.

Core concepts in Express.js

Most web servers do something like the following:

  • Listen for requests that come to the server
  • Receive HTTP requests at an endpoint, such as /home, and parse the information sent with the request
  • Run code in response to the type of HTTP verb the request was made from
  • Respond to the request in some way

When working with Express, we have tools to help us achieve these steps in only a few lines of code. The three big concepts that Express works with are:

  1. Routing
  2. Middleware
  3. Request/Response

Routing

Routing aims to describe what code needs to be run in response to a request that the server received. This is typically done based on the combination of the URL pattern and the HTTP Method associated with the request.

For example, if a GET request is received for the URL /home, send back the HTML for the homepage. Or if a POST request is sent to /products, create a new product listing.

These are the basic building blocks of any API or web application, and Express provides us with flexible ways to define code to handle these requests.

We'll cover routing in depth in our [tutorial about Express routing](./NEEDS LINK), but here is a quick example of what routing looks like with Express:

app.get("/test", function(req, res) {
  // run some code
  res.json({ ok: true });
});

In this example, app is an instance of our Express server, app.get is the HTTP request method, and "/test" is a URL path we are defining for our server. The function passed in here is the handler that will run when a GET request is made to /test. The req and res parameters we'll cover next, but they stand for Request and Response respectively.

Request/Response

Often shortened to req and res, you'll see these everywhere when working with Express and other Node.js server frameworks. They represent the Request which was received by the server, and the Response which you will eventually send back.

These are based on objects that come built in to Node.js, the ClientRequest and ServerResponse objects -- integral parts of an HTTP transaction.

A single HTTP transaction can be described by the Request and Response cycle.

  • A client sends a request to the server.
  • The server receives the request and reads the data that accompanies it. This includes the headers, the URL path the request is being sent to, the HTTP method used to send the request, query parameters, cookies, the data or payload sent with the request (if any) -- and more.
  • The server must send a response back to the client: this involves a status code, headers, content encoding, any data being returned, and again, many other possible things.
  • Once the server has sent the response back to the client, the HTTP transaction has completed.

That is a rough explanation of what the Request/Response cycle looks like, but this interaction makes up the core of most HTTP transactions.

Express helps us complete these transactions by helpfully augmenting the built in Request and Response objects that the Node.js core http module provides when a request is received by your server.

Let's take a look at the example from above one more time.

app.get("/test", function(req, res) {
  // run some code
  res.json({ ok: true });
});

In the handler function we are receiving two parameters, req and res. The req object will have all the information from the request we received. We can access properties on the req object to get data about the request like the URL path, the body of the request, headers, and more.

The res object represents the response we send back to the client. Express adds useful methods to res that help us send the response. Once the response is sent, the HTTP transaction has completed.

The example above is using res.json() to send a JSON response back to the client. That's one of the methods added by Express, and it will parse the object we pass into a JSON string and add it to the response body, set a Content-Type: application/json header on the response, and then send the response to the client.

Augmenting the req and res objects is a large part of how Express exposes and enhances functionality for your server, while still giving you control over how requests and responses are handled.

Check out the Express documentation to learn more about the request object as well as the response object.

Middleware

Middleware is code that executes somewhere during the life cyle of the request/response cycle, and is commonly used to add functionality or augment the behaviour of webserver. We [cover middleware in it's own tutorial](./NEEDS LINK), but here is a general overview.

Middleware are functions that have access to the Request and Response objects. They can run any arbitrary code, and are executed one after another according to what order the middleware are stacked. Middleware are part of the program that add some kind of functionality to your application, often by augmenting or adding things to the req and res objects themselves. Middleware can be added into your application without needing to change much.

Express uses Connect style middleware which is a common format for Node.js server frameworks. That means middleware written for Express can also be used in many other frameworks that implement Connect style middleware.

A common middleware used with Express is cookie-parser. It parses the Cookie header of an incoming request and populates the cookie values on the req object under req.cookies as an object. This means that any other route handlers or middlewares that run after cookie-parser will have access to the cookies sent with the request.

Express itself is essentially just a collection of middlewares, plus routing capabilities. You can write your own middleware functions as well as use any of the countless middleware that are publicly available on the npmjs.com package registry.

Middleware is one of the key ways that you add functionality to an Express server. It's a flexible and powerful pattern that allows customization and additional logic to be introduced to the Request/Response cycle of your server.

Community

The final piece of what makes Express so powerful is the community of developers working with Express in production. It is one of the most popular server frameworks used with Node.js, and as a result there is a lot of knowledge and documentation that exists on the internet about it.

That is evident by the countless middlewares that exist to add functionality to an Express application. The Node.js ecosystem emphasizes using modules as building blocks, and Express takes full advantage of that.

Because of the large community, extensive documentation, and battle tested experience readily available on the internet, Express is a solid choice when building a web application with Node.js.

Recap

In this tutorial, we introduced the core concepts of the Express server framework. Express is a minimal and extensible framework that provides a set of common utilities for building servers and web applications. It's built on top of Node.js' built-in http module, but helps us accomplish the tasks of routing and handling the Request/Response cycle. Express uses middleware to extend its capabilities with code that we either write ourselves or that has been contributed by the large community using the project.

Further your understanding

  • Search the internet for information about other Node.js server frameworks. Examples include Hapi, Koa, and Fastify. How are they different from Express?
  • Express is unopinionated; it doesn't tell you the "right way" to build a server. Can you think of some pros and cons of that level of flexibility?
  • Try and build (or look up an example of) a JSON API written in Node.js without using any frameworks. Think about how much boilerplate and how many lines of code the application requires.

Additional resources

Sign in with your Osio Labs account
to gain instant access to our entire library.