Instagram
youtube
Facebook
Twitter

ExpressJS Middleware

ExpressJS-Middleware

  • Express.js Middleware functions are functions that have access to the response object(res), request object(req), and the next function in the request-response cycle.
  • It appears in middle between an initial request and the final intended route.
  • It is used to perform tasks like body parsing for URL-encoded or JSON requests, cookie parsing or even building JavaScript modules on the fly.

Function or tasks of Middleware Function:

  • Execute any code.
  • Make changes to the request and the response objects.
  • End the request-response cycle.
  • Call the next middleware in the stack.

Example:

const express = require('express')
const app = express()
# function is middleware function
const myLogger = function (req, res, next) { 
  console.log('LOGGED')
  next()
}

app.use(myLogger)

app.get('/', (req, res) => {
  res.send('Hello World!')
})

app.listen(3000)

Types of Middleware

  • Application-level middleware
  • Router-level middleware
  • Error-handling middleware
  • Built-in middleware
  • Third-party middleware

Application-level middleware

  • Application-level middleware is bound to an instance of the app object by using app.use() and app.method() functions here method is the HTTP method.

Example:

const express = require('express')
const app = express()
app.use('/user/:id', (req, res, next) => {
  console.log('Request Type:', req.method)
  next()
})

Router-level middleware

  • Router-level middleware is the same as application-level middleware except it is bound to an instance of express.Router().

Example:

const express = require('express')
const app = express()
const router=express.Router
router.use('/user/:id', (req, res, next) => {
  console.log('Request Type:', req.method)
  next()
})

Error-handling middleware

  • Error-handling middleware is the same as other middleware except the middleware function takes four arguments instead of three.

Example:

const express = require('express')
const app = express()
app.use((err, req, res, next) => {
  console.error(err.stack)
  res.status(500).send('Something broke!')
})

Built-in middleware

  • Built-in middleware functions are included with express.
  • Built-in middleware functions present in Express are: express.static, express.json, and express.urlencoded.
  • express.static serves static assets such as HTML files, images, and so on.
  • express.json parse incoming requests with JSON payloads.
  • express.urlencoded parse incoming requests with URL-encoded payloads.

Third-party middleware

  • Install the Node.js module 
npm install cookie-parser
const express = require('express')
const app = express()
const cookieParser = require('cookie-parser')

// load the cookie-parsing middleware
app.use(cookieParser())