Middleware is an often misunderstood topic since it sounds and appears very complicated, but in reality middleware is actually really straightforward. The entire idea of middleware is to execute some code before the controller action that sends the response and after the server gets the request from the client. Essentially it is code that executes in the middle of your request, hence the name middleware. Before I get too in depth on the details of middleware, though, I want to setup a basic Express server with two routes.

Setting Up An Express Server

To get started working with a Node.js project you will need to run npm init -y. This will create a basic package.json file with all of the default values filled in for you. From there the next thing to do is install Express by running npm i express. Lastly, we need to create a server.js file with the following code.

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

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

app.get('/users', (req, res) => {
  res.send('Users Page')
})

app.listen(3000, () => console.log('Server Started'))

This server.js file simply sets up a server on port 3000 that has two routes, a home page route and a users page route. The last thing to do is run node server.js to start up the application and if everything worked you should see a message in the console saying Server Started. You can then open up any browser to localhost:3000 and you should see the message Home Page. If you go to localhost:3000/users you should then see the message Users Page.

That is all the basic setup we will need for the rest of this article. As we make changes you will need to restart your server in the console to see the changes take effect.

What Is Middleware?

I talked briefly about middleware as functions that execute after the server receives the request and before the controller action sends the response, but there are a few more things that are specific to middleware. The biggest thing is that middleware functions have access to the response (res) and request (req) variables and can modify them or use them as needed. Middleware functions also have a third parameter which is a next function. This function is important since it must be called from a middleware for the next middleware to be executed. If this function is not called then none of the other middleware including the controller action will be called.

This is all a bit difficult to understand just from text so in the next section we are going to create a logging middleware that will log the url of the request a user makes.

#node #express #javascript #developer

NodeJS (Express) - How to Write Express Middleware
1 Likes3.10 GEEK