DEV Community

Mario
Mario

Posted on • Originally published at mariokandut.com on

What Is the Express Node.js Framework?

One of the most common usages for Node.js is for writing web applications, and many of these applications are using Express.js. Node.js is a great choice for building web applications and services, so why do we need a server framework like Express? Express reduces complexity and makes developing and maintaining applications much easier than doing it with the Node.js built-in tools.

This article is part of a series about Express. You can find all articles here - Express Framework.

Introduction to Express.js

Creating a basic Hello World http server with built-in utilities in Node.js is fairly simple. The code below listens to requests on port 8000 and returns Hello World.

const http = require('http');
const port = 8000;

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

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

For simple servers like this, you don't need Express. In a real world scenario, I have never seen something simple as this example.

The Hello World example in Express looks like this. Maybe you can already see some simplification on this example?

const express = require('express');
const app = express();
const port = 8000;

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

app.listen(port, () => {
  console.log(`Server listening on port ${port}`);
});
Enter fullscreen mode Exit fullscreen mode

Under the hood Express uses the same built-in utilities as provided from Node.js, but Express provides a set of handlers, settings, and other tools to increase the developer experience and increase the speed of creating web servers.

Core concepts of Express

Most web servers listen for requests that come to the server, receive http requests at an endpoint, run some code in response to the type of HTTP verb was used and respond to the request in some way. Express.js has tools to achieve all of these steps in just a few lines of code.

Express is a project of the OpenJS Foundation and describes itself as Fast, unopinionated, minimalist web framework for Node.js.

The three big concepts in Express.js are:

  • Routing
  • Middleware
  • Request/Response

Routing in Express

Routing refers to how an application’s endpoints (URIs) respond to client requests.This is typically done with the combination of the URL pattern, and the HTTP method (verb) associated.

For example:

  • If a GET request for the url /home, send back the HTML for the homepage.
  • Or if a POST request with some payload is sent to /product, create a new product based on the data in the payload.

A Route definition takes the following structure: app.METHOD(PATH, HANDLER)

  • app is an instance of express.
  • METHOD is an HTTP request method, in lowercase.
  • PATH is a path on the server.
  • HANDLER is the function executed when the route is matched.

Routing is considered the basic building block of any API or web application, and the Express Framework provides flexible, unopinionated ways to write code to handle requests.

Let's look at an example of routes that are defined for the GET method to the root of the app.

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

// GET method route
app.get('/', (req, res) => {
  res.send('GET request to the homepage');
});
Enter fullscreen mode Exit fullscreen mode

In the above example, app is an instance of the express server, app.get is the HTTP request method and / is the URL path. The function passed in, is the handler that will run when a GET request is made to /. The req and res parameters stand for Requests and Response.

Request and Response

They are often shortened to req and res and stand for the request which was received by the server, and the response which will eventually be send back. These are based on built-in objects in Node.js, the ClientRequest and ServerResponse. There will be a dedicated Express routing blog post in the future.

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

  • A client sends a request to the server.
  • The server receives the request, reads the data (request headers, URL path, HTTP method, query parameters, cookies, data or payload, etc.).
  • The server sends a response back to the client. It includes status code, headers, content-encoding, any data being returned.
  • Once the response has been sent back, the HTTP transaction is completed.

Augmenting the req and res objects is a big part of how Express enhances functionality, while still maintaining control over how requests and responses are handled.

Middleware

Middleware is code that executes during the request/response cycle. It is typically used to add functionality or augment the behaviour of the server. Middleware functions have access to the request object req, the response object res, and the next function in the application’s request-response cycle.

Middleware functions 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.

Let's look at an example for a middleware. We want to print a simple log message, when a request has ben received.

The Hello-World example from before.

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

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

app.listen(3000);
Enter fullscreen mode Exit fullscreen mode

We create a middleware function myLogger, which will print LOG when a request to the app passes through it.

const myLogger = function(req, res, next) {
  console.log('LOG');
  next();
};
Enter fullscreen mode Exit fullscreen mode

To load the middleware we have to call app.use() specifying the middleware function.

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

const myLogger = function(req, res, next) {
  console.log('LOGGED');
  next();
};

app.use(myLogger);

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

app.listen(3000);
Enter fullscreen mode Exit fullscreen mode

Middlewares are a flexible and powerful pattern to add logic and customize the Request/Response cycle. It enables to add more functionality to an Express server. There will also be dedicated blog post about middlewares in Express.

Community

What really makes Express powerful is the community of developers working with it in production. Express is one of the most popular server frameworks used with Node.js. The Node.js ecosystem emphasizes using modules as building blocks for applications, and the Express community is taking full advantage of this with countless existing middlewares to add functionality.

Express is a solid choice, when building a web application with Node.js. Though, please consider that, Express is unopinionated and best practices should be followed.

TL;DR

  • Express is a minimal and extensible framework.
  • It provides a set of utilities for building servers and web applications.
  • The Express Framework provides flexible, unopinionated ways to write code to handle requests.
  • Middlewares are a flexible and powerful pattern to add logic and customize the Request/Response cycle.
  • Express is one of the most popular server frameworks for Node.js developers.
  • It is battle-tested in production environments, and a solid choice for web servers.

Thanks for reading and if you have any questions , use the comment function or send me a message @mariokandut.

If you want to know more about Express, have a look at these Express Tutorials.

References (and Big thanks):

HeyNode,ExpressJS,Github - Express,Node.js - HTTP

Top comments (0)