- December 14, 2017
- Posted by: user
- Category: Uncategorized
I’ve been using middleware for a long time. If you’ve built Node.js apps using Express.js, you are probably aware of middleware and how middleware functions work if you know basic of Node.js and Express.js.
A better understanding of how middleware works, you definitely can create a more maintainable application with less and reusable code.
In this post, You will further read about learning fundamentals of middleware, Types of middleware and how to use it in your Node.js apps.
Let’s first understand middleware.
What is the middleware?
“Middleware functions are functions that have access to the request object(req), the response object(res), and the next middleware function in the application’s request-response life cycle. The next middleware function is commonly denoted by a variable named next.” – Express.js
Basically, middleware is a function that runs before your route handler is executed. You might have already used some middleware like Morgan, bodyParser for example. It can be applied in the different ways but the concept is the same.
Using middleware you can modify or transform the request and response objects before passing them to next middleware function. It can be helpful when you want to authenticate the request before passing it to the actual route handler, it can also use to perform some pre-defined task on the request before executing the actual router handler.
A very basic middleware function:
1 2 3 4 |
function myMiddleware(req, res, next) { req.body.greeting = ‘Hello from the middleware function’; next(); } |
In the above middleware, I’ve added one variable to request body object, this variable will be accessible to the next middleware function(s).
Types of middleware :
Middleware functions primarily classified by its usage type as described below
- Application-level middleware
- Router-level middleware
- Error handling middleware
- Built-in middleware
- Third-party middleware
1. Application-level middleware
Application middlewares can be bind to "app" instance using app.use( ) and app.METHOD( ) functions, METHOD is the HTTP method(like get, post, put, delete, etc) of the request that the middleware function will handle.
app is the instance of the express.
1 2 3 4 5 6 |
const app = express(); app.use((req, res, next) => { // code to process/manipulate the request and response object next(); }) |
Example of app.METHOD( ):
1 2 3 4 |
app.get('/greeting', (req, res, next) => { req.body.greeting = 'Hi from the middleware function'; next(); }) |
2. Router-level middleware
There is no significant difference between application-level middleware and router-level middleware, the only difference is that router-level middleware bound to an instance of the express router.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<span style="white-space: pre-wrap;">const router = express.Router(); router.use(handleAuthentication); function handleAuthentication(req, res, next){ const token = req.body.token || req.headers['token']; if(isTokenValid(token)){ // Token is authenticated and it is valid so execute next middleware next(); } else { // Invalid token send error response res.send("Token is invalid"); } }</span> |
Above middleware will be executed in every request as there is not mount path is mentioned, you can use router.METHOD( ) for using this middleware in specific requests only.
3. Error handling middleware
In the error handling middleware, there are four arguments in the middleware functions instead of three. The new argument is the error.
A very simple error handling middleware will look like:
1 2 3 4 5 |
app.use((err, req, res, next) => { console.log('Error', err.stack); // code to handle error and respond to the user res.send("Oops, error occurred"); }); |
4. Built-in middleware
You’ve probably used one of the below built-in middleware functions:
- express.static – It is used to serve the static assets in the response.
- express.json – It is used to parse the request that has JSON payload or data.
- express.urlencoded – It is used to parse the request that has URL-encoded payload or data.
Usage examples:
1 2 3 4 |
app.use(express.static('public')); // without path app.use('/static', express.static('public')); // with specific path app.use(express.json()); app.use(express.urlencoded()); |
5. Third-party middleware
Body parser, morgan, cors, cookie parser are widely used the third-party middlewares and you are probably using one or more of them in your express.js apps.
Usage examples:
1 2 3 4 5 |
const bodyParser = require('bodyParser'); const morgan = require('morgan'); app.use(bodyParser.json()); app.use(morgan('combined')); |
Conclusion
So my post is about the basic idea on middleware functions, types of the middleware, and how different middlewares can be used in your app to clean up and re-use your code. Have a look at your existing code-base and extract frequently used code into middleware functions to make it clean and easy to understand. There are a lot of middleware functions that will help you to make your code more organized and clear, browse NPM to find the widely used node.js middlewares.
Happy Coding, stay awesome!