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

93
Views
How to write independent/isolated express middleware with access to raw request body

I am trying to write an Express middleware that has access to the raw request body. So something like this (actually works and) would be ideal:

const middleware = [
  express.raw({ type: '*/*' }),
  (req, res, next) => {
    digest(req.body);
    next();
  },
];

However, this approach means the req.body has now been streamed/processed and is now unavailable to any handler or middleware following my middleware:

app.post(route, middleware, (req, res) => res.send(req.body)); // returns `{}`

I would it to be possible to use my middleware with other body parsers. So this should be ok:

app.use(express.json());
app.post(route, middleware, (req, res) => res.send(req.body)); // should return the JSON body posted not `{}`

As well as this:

app.post(route, middleware, express.json(), (req, res) => res.send(req.body)); // should return the JSON body posted not `{}`

Is it possible to:

  • use middlewares in the manner I am attempting here (i.e. using more than one in succession)?
  • get hold of the raw body by a means other than express.raw({ type: '*/*' })?
  • reset the request body after I am done with it so other handlers and middlewares can access it like my middleware had never been used?

I have expanded these snippets into a failing test in this repository if the above is not clear enough and would appreciate any help or pointers.

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

0

So with a bit more research (and sleep) I think my approach here is probably incorrect.

A more appropriate solution would be to use the verify option of the relevant body parser which gives you access to the buffer:

app.use(express.json({ verify: (req, res, buf, encoding) => digest(buf) || throw 'Invalid Digest' }));
app.post(route, (req, res) => res.send(req.body));
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!