Understand core concepts of the Express server Node.js framework,
Posted
Updated
Europe’s developer-focused job platform
Let companies apply to you
Developer-focused, salary and tech stack upfront.
Just one profile, no job applications!
This article is based on Node v16.14.0.
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.
💰 The Pragmatic Programmer: journey to mastery. 💰 One of the best books in software development, sold over 200,000 times.
This article is part of a series about Express. You can find all articles here - Express Framework.
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`);
});
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}`);
});
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.
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 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:
/home
, send back the HTML for the homepage./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');
});
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.
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.
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 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:
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);
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();
};
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);
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.
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.
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):
Never miss an article.