Backend With Express.js Middleware

Building a Backend with Express.js — Part 2— #ExpressSeries — Episode #01

J3
Jungletronics
4 min read3 hours ago

--

Let’s continue this Express series. Now we’ll cover something that most tutorials skip: Middleware.

What is middleware?

For instance, When I click refresh, a request is sent to the server. This request is processed by the app.get method, and middleware encompasses everything that occurs between the server receiving the request and sending out a response.

Express middleware is a function or set of functions that execute during the lifecycle of a request to an Express.js server. Middleware functions have access to the request object (req), the response object (res), and the next middleware function in the application's request-response cycle. These functions can perform tasks such as:

  • Executing code (log, auth, parsing, error).
  • Modifying the request and response objects.
  • Ending the request-response cycle.
  • Calling the next middleware function.

Middleware can be used for various purposes, including logging, authentication, data parsing, and error handling. In essence, middleware functions act as a series of layers that process incoming requests and outgoing responses, enabling developers to build modular and maintainable web applications.

00#Step —Implementation

To implement this, you just need to modify server.js.

server.js

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

// Set view engine
app.set('view engine', 'ejs')

// Custom middleware function
const loggerMiddleware = (req, res, next) => {
console.log(`${req.method} ${req.url}\n`)
next() // Pass the request to the next middleware function
}

// Another custom middleware function
const authMiddleware = (req, res, next) => {
const auth = req.headers['authorization']
if (auth === 'secret-token') {
next(); // Pass the request to the next middleware function
} else {
res.status(401).send('Unauthorized')
}
};

// Use the middleware functions in the app
app.use(loggerMiddleware)
app.use(authMiddleware)

// Import user routes
const userRouter = require('./routes/users')

// Routing configuration goes here.
app.get('/', (req, res) => {
res.render('index', { message: 'Hello Express!' })
})
app.use('/users', userRouter)

// Start the server
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`)
})

Explanation:

1#Step —Logger Middleware

loggerMiddleware logs each incoming request.

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

Issue: If you use single quotes instead of backticks in the line console.log('${req.method} ${req.url}'), it will be treated as a regular string rather than a template literal. This causes the string to be logged exactly as it is, without interpolating the req.method and req.url values.

To Fix: Use backticks (`) instead of single quotes. In Node.js, backticks are used to define a template literal, which allows for embedding expressions within strings. Template literals provide a more concise and readable way to create formatted strings compared to string concatenation.

2#Step — Authentication Middleware

authMiddleware checks for an authorization header. If the header is secret-token, the request proceeds; otherwise, it responds with 401 Unauthorized.

const authMiddleware = (req, res, next) => {
const auth = req.headers['authorization'];
if (auth === 'secret-token') {
next(); // Pass the request to the next middleware function
} else {
res.status(401).send('Unauthorized');
}
};

authMiddleware: This middleware checks the authorization header of the incoming request.

If the authorization header equals 'secret-token', it calls next() to pass control to the next middleware function.

If the authorization header does not match, it responds with a 401 Unauthorized status.

3# Step — Using Middleware in the Application

app.use(loggerMiddleware);
app.use(authMiddleware);

Routes and Views: Your existing routes and views remain unchanged.

4#Step — Testing

If you wanted to test all the CRUD operations, you could use the following curl commands:

GET Request:

curl -H "Authorization: secret-token" http://localhost:3000/users/1

POST Request:

curl -X POST -H "Authorization: secret-token" http://localhost:3000/users/1

PUT Request:

curl -X PUT -H "Authorization: secret-token" http://localhost:3000/users/1

DELETE Request:

curl -X DELETE -H "Authorization: secret-token" http://localhost:3000/users/1

Or using Rested:

Repeat for POST, PUT and DELETE. Thanks for readinG!

Conclusion

In this tutorial, we explored how to incorporate middleware into an Express.js application. Middleware functions are essential for handling various tasks during the request-response cycle, such as logging, authentication, data parsing, and error handling.

We implemented two key middleware functions:

  1. Logger Middleware: This function logs the HTTP method and URL of each incoming request. It uses backticks (`) to create a template literal, ensuring proper interpolation of variables.
  2. Authentication Middleware: This function checks for an authorization header. If the header matches a predefined token, the request proceeds; otherwise, it returns a 401 Unauthorized response.
GET http://localhost:3000/users/1 . Wrong Token!

By integrating these middleware functions, we enhanced our Express.js server to perform logging and authentication efficiently. The overall application structure remains the same, with middleware functioning as additional layers that process requests and responses, enabling modular and maintainable code.

Remember, middleware is a powerful feature of Express.js that can greatly improve the functionality and organization of your server.

See you soon!

Bye!

https://gouravmukhija.medium.com/what-is-expressjs-64b0b4334f2e

Related Posts:

00#Episode — Backend With Express.js Framework — Building a Backend with Express.js — Part 1

01#Episode — Backend With Express.js Middleware — Building a Backend with Express.js — Part 2 (this one)

Acknowledgements:

TAG IT ALL!

🤔☺️👉🥰
git tag -a express_v2 -m "Express in Nodejs 2 - v2.0: Go to https://medium.com/jungletronics/backend-with-express-js-middleware-eeb56bf63aff" -m "0- What is middleware?" -m "1- server.js Implementation;" -m "2- Logger Middleware;" -m "3- Authentication Middleware" -m "4- Using Middleware in the Application" -m "5- Testing w curl or RESTED" -m "Thank you for downloading this project 😘️👌️👋️😍️"
git push origin express_v2

Release V2

GitHub: https://github.com/giljr/express_project

--

--

J3
Jungletronics

Hi, Guys o/ I am J3! I am just a hobby-dev, playing around with Python, Django, Ruby, Rails, Lego, Arduino, Raspy, PIC, AI… Welcome! Join us!