Home > Mobile >  How to write independent/isolated express middleware with access to raw request body
How to write independent/isolated express middleware with access to raw request body

Time:12-22

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.

CodePudding user response:

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));
  • Related