DEV Community

Cover image for Overview: Express.js Framework Middleware's
Marcos Silva for Webcrumbs

Posted on

6 3 3 3 3

Overview: Express.js Framework Middleware's

One of the most important things about Express.js is how minimal this framework is. Known for its simplicity and performance, Express.js is one of the most popular frameworks in the Node.js ecosystem.

Let's dive into interesting parts:

Using Middleware functions, is possible to access the request and response objects, making it easy to add functionalities like logging, authentication, and data parsing. Check the example:

const requestLogger = (req, res, next) => {
  console.log(`${req.method} ${req.url}`);
  next();
};
Enter fullscreen mode Exit fullscreen mode

The next() function, is responsible to pass the control for the next middleware. Without calling this function, the request will not proceed to the next middleware or route handler, and the request-response cycle will be left hanging.

You can also apply this middleware for all the routes, using only a line of code.

app.use(requestLogger);
Enter fullscreen mode Exit fullscreen mode

This show to how Express.js is really simple to read! 😁

Testing

This is my favorite part, let's test it!!
Adding some basic routes to test the middleware

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

app.get('/about', (req, res) => {
  res.send('About Page');
});
Enter fullscreen mode Exit fullscreen mode

Follow the full code for test the Middleware functions:

Note: Create a file 'index.js' and add the full code.

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

const requestLogger = (req, res, next) => {
  console.log(`${req.method} ${req.url}`);
  next(); // Pass control to the next middleware function
};

app.use(requestLogger);

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

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

app.listen(port, () => {
  console.log(`Server running at http://localhost:${port}/`);
});

Enter fullscreen mode Exit fullscreen mode

IMPORTANT

Before run check if the port in the const port is in use.

Run in the terminal:

node app.js
Enter fullscreen mode Exit fullscreen mode

Thank you, Please Follow: Webcrumbs

Webcrumbs

Bibliography: Express.js Docs

Image of Datadog

How to Diagram Your Cloud Architecture

Cloud architecture diagrams provide critical visibility into the resources in your environment and how they’re connected. In our latest eBook, AWS Solution Architects Jason Mimick and James Wenzel walk through best practices on how to build effective and professional diagrams.

Download the Free eBook

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free β†’