1

I'm trying to monitor the status codes of the responses sent by my express server which has quite a few routes. One way to do this would be to manually save the error code before I send it with res.send() but I'd rather have a cleaner way of doing this. I tried using a middleware that is called after the route handler but it doesnt get called, presumably because res.send ends the execution of middlewares. Is there a clean way of doing this?

ninesalt
  • 4,054
  • 5
  • 35
  • 75
  • 1
    Possible duplicate of [express.js - how to intercept response.send() / response.json()](https://stackoverflow.com/questions/33732509/express-js-how-to-intercept-response-send-response-json) – Nino Filiu Feb 22 '19 at 20:27
  • 1
    Thanks this solved my issue – ninesalt Feb 22 '19 at 20:47

1 Answers1

0

res.send() doesn't end the execution of middlewares, but the lack of calling next() will. So, in your case, I think chaining another middleware after your route handler is the correct approach, just ensure it ends with calling next().

Example:

// router.js
const express = require('express')
const router = express.Router()
const routeHandler = require('../controllers/route-handler')
const logResponse = require('../middleware/log-response')
router.get('/', routeHandler, logResponse)
// controllers/route-handler.js
function routeHandler(req, res, next) {
  // Do some stuff
  res.status(200).json({})
  return next() // <-- This is the key -- it will continue to the next  middleware
}

module.exports = {
  routeHandler
}
// middleware/log-response.js
function logResponse(req, res, next) {
  console.log(res.status, res.statusText) // 200 OK
}

module.exports = {
  logResponse
}

Hope that helps!

john-goldsmith
  • 2,969
  • 1
  • 19
  • 18