Nodejs and Middlewares

Created At: 2023-11-27 00:25:56 Updated At: 2023-11-27 00:58:03

It's essentially a piece of software that sits between your application and the server, acting as a bridge to handle various tasks and operations. Here's a breakdown of what middleware is and why it's crucial:

  1. Intermediary: Middleware is a layer of software that intercepts and processes incoming HTTP requests or outgoing responses. It's like a middleman between your application and the server or client.
  2. Functions and Actions: Middleware consists of functions or code snippets that can perform a wide range of tasks. These tasks can include processing data, authentication, logging, error handling, and more.

You can think of them as "LISTENERS" if you come from flutter, they constantly listen, in this case to http requests and execute the code you put in their body when the event they are listening for occurs. So, you could say that middlewares are just essentially http request listeners.

  1. Middlewares can be saved and used in particular http requests or just set globally to be triggered for each and every http request.
  2. Middlewares run in the order you write them, if I write middleware1, then on the next line, I write the second one, the first will always execute before the second one.

Registering Global Middlewares

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

// Middleware
app.use((req, res, next) => {
   console.log('A request has been made to your server');
   // Always call next() or it won't move to the next middleware or continue to your actual route
   next();
});

Notice a few things, Express.js provides us with the ability to register middlewares, and after doing something in a user-defined middleware, always call next() to enable your listener exit itself.

This is Global, meaning that we literally registered it into our express app, so, every single time an http request is sent, our middleware will be triggered. So, for every call to the API, we will get a log in our console.

Registering Contextual Middlewares

Middlewares that are saved to a variable and later applied to a particular route, so, it will only be triggered whenever that route is hit

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

const authenticateUser = (req, res, next) => {
  const isUserAuthenticated = true;
  if (isUserAuthenticated) {
    next(); // User is authenticated, move to the next middleware
  } else {
    res.status(401).send('Unauthorized');
  }
};

// Use authenticateUser Middleware in this function only
app.get('/profile', authenticateUser, (req, res) => {
   res.send('Welcome to your profile');
});

So, the authenticateUser won't be triggered at all unless a request was made to /profile.

Body Parser

Installation: npm install body-parser

body-parser is a crucial middleware in Express.js that simplifies the process of parsing and working with the data from incoming HTTP request bodies.

When an HTTP request is received by your Express application, the request body may contain data. This data could be in various formats, including JSON, URL-encoded form data, or even binary data. body-parser parses this data and makes it available for use in your application.

You can think of body parser as jsonDecode() in flutter. Now since it's a middleware, we will have to register it, and we usually want it to convert all our request bodies to readable format, so, we usually register it as a "global middleware"

const express = require('express');
const bodyParser = require('body-parser');

const app = express();
app.use(bodyParser.json());

Morgan

Installation: npm install morgan

The same is the story for Morgan as it is for Body Parser, it's a middleware that we can register for all requests to log them, print them to the console.

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

const app = express();

app.use(morgan('tiny'));

when you visit the npmjs page for morgan, you can see it has a few configurations we can choose from, but the one they recommend or use in the documentation is tiny, so that's what we stick with for this tutorial.

When you make a request to any endpoint, you will see this in your console

GET /api/v1/products 200 54 - 2.595 ms

CORS

Installation: npm install cors

CORS (Cross-Origin Resource Sharing), you might have heard of it before, or you might not have heard of it. either way, it's an important security feature implemented by web browsers to control how web pages in one domain can request and interact with resources from another domain. This restriction is in place to prevent potentially harmful "cross-origin" requests.

const cors = require('cors');

app.use(cors());
app.options('*', cors());

The idea behind CORS is rooted in the same-origin policy, a security measure that restricts web pages from making requests to a different domain than the one that served the web page. While this policy is essential for security, it can pose challenges when you legitimately want your web application to fetch resources from different origins, like an API hosted on a separate server.

Now, this is where CORS middleware in Node.js (specifically in Express) comes into play. When your frontend, hosted on one domain, wants to make a request to an API on another domain, the browser enforces the same-origin policy. The CORS middleware, when added to your server, helps relax these restrictions.

You could read more on google, but the TLDR; the entire process of testing the safety from the browser to your server, and responding from your server and other processes that happen between them is quite complex, but using a CORS middleware simplifies this process.

Comment

Add Reviews