Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

149
Views
Express custom json response

I want to send a custom json response on each request at the end like:

{
  "message": "Something",
  "type": "success",
  "payload": /*object, array, anything else */
}

What I can do is at the end of each request use:

res.status(200).json({message: 'Something', type: 'success', payload});

If for some reason I want my responses to have another format, I have to go and change each res.json, which is bad.

But since I know all my responses will have this format, is there any way to create a middleware and pass some variables like payload, message, type which gets executed at the end of each request?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

It is possible to create a midleware for the reponse

router.get('/some-route', controller.someFunction, resposeMiddleware)

You would need to pass the response as an argument on the next call

someFunction (req, res, next) => {
    res.local.payload = {/* some data */}
    next()
}

the resposeMiddleware would be something like this

const resposeMiddleware = (req, res) => {
      const { payload } =  res.local
      res.status(200).json({message: 'Something', type: 'success', payload})
}
about 4 years ago · Juan Pablo Isaza Report

0

Create a helper method like bellow (successResponse.js). You can also set any property to default.

    successResponse = (res, statusCode, message, data) => {
      res.status(statusCode || 200).json({
      code: statusCode || 200,
      message: message || "success",
      data: data || {},
    });
   };

   module.exports = successResponse;

now in your controller just import successResponse and use it like

successResponse(res, 200, "Your Success message", data);
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!