What is middleware?
What is middleware?
middleware is a function that sits between the incoming request and the outgoing response in an application's request-response cycle. It intercepts and can modify the request and response objects, perform additional tasks, and pass control to the next middleware function in the stack. For tasks such as authentication, logging, error handling, etc.
Let's create an example middleware
We will create a middleware to log activities when endpoint are called.
- Create a directory
/middlewares/
on root directory. - create
logger.js
in middlewares folder.const Logger = (req, res, next) => { console.log(`Request: ${req.method} ${req.originalUrl}`); next(); }; module.exports = Logger;
- When using middleware we have 2 option to use:
- 1. Global use: the middleware will be execute on every endpoint.
- 2. Specific use: the middleware will execute only the endpoint we specified - With Logger middleware we will use the global uses
To use a middleware globally we will use app.use(`middleware`);
now us it in index.js
const cookieParser = require('cookie-parser'); const express = require('express'); const Logger = require('./middlewares/logger'); const app = express(); const port = 4000; app.use(cookieParser()); app.use(Logger); app.get('/', (req, res) => res.send('Hello World!')); app.use('/cookies', require('./routers/cookies')); app.listen(port, () => console.log(`Server running on port ${port}`));
When you are using app.use() it will affect every endpoints below it. In this case we use logger above all of our paths, it means every paths will affect all of our paths. - Try sending any request to the server and observe the terminal
Specific call middleware
- Now lets create a specific middleware for monitor the different of an execution time between
sendCookie.js
andsendSecureCookie.js
- First create a middleware file name
timer.js
in /middlewares directoryconst Timer = (req, res, next) => { const start = Date.now(); next(); const end = Date.now(); console.log(`Request took ${end - start}ms`); }; module.exports = Timer;
- Now we will use it to measure the exec time of '/cookies/' and '/cookies/secure' so we have to use our timer in this two paths. here is how you can do it:
go to cookies routes file:/routers/cookies.js
:
const express = require('express'); const SendCookie = require('../controllers/cookies/sendCookie'); const SendSecureCookie = require('../controllers/cookies/sendSecureCookie'); const ShowCookies = require('../controllers/cookies/showCookies'); const DecodeCookies = require('../controllers/cookies/decodeCookies'); const ClearCookies = require('../controllers/cookies/clear'); const Timer = require('../middlewares/timer'); const cookiesRouter = express.Router(); cookiesRouter.get('/', Timer, SendCookie); cookiesRouter.get('/secure', Timer, SendSecureCookie); cookiesRouter.get('/show', ShowCookies); cookiesRouter.get('/decode', DecodeCookies); cookiesRouter.get('/clear', ClearCookies); module.exports = cookiesRouter;
- Try sending request to these two and inspect the result in console:
Done! you know how to use middleware now.