How do I declare an express/js req.param that is scoped/passed thru every method on a route handler?

So I am building a RESTful API to modify MondoDB docs by “_id” using the app.route() handler in Express (https://expressjs.com/en/guide/routing.html#app-route).

In each chained method, I have to destructure the constant _id out of the req.params, declaring the same exact const four times. Is there a way to declare/destructure _id just once for the entire scope of this route handler to get passed through each method as needed? I’ve played around with the app.all and app.use methods, as well as tried out some initial callback functions (next();, etc.) but nothing seems to work yet; either it errors out or returns _id as undefined.

A simplified version of the working route handler is below:

app.route("/posts/:_id")
    .get((req,res)=>{
      const {_id} = req.params;
      res.send(`This is the response from the GET request for Post ID#: ${_id}`);
     })
    .put((req,res)=>{
      const {_id} = req.params;
      res.send(`This is the response from the PUT request for Post ID#: ${_id}`);
    })
    .patch((req,res)=>{
      const {_id} = req.params;
      res.send(`This is the response from the PATCH request for Post ID#: ${_id}`);
    })
    .delete((req,res)=>{
      const {_id} = req.params;
      res.send(`This is the response from the DELETE request for Post ID#: ${_id}`);
    });

In other words, how can I declare const {_id} = req.params; only once here, instead of four times? Is that possible? Thanks.

8 thoughts on “How do I declare an express/js req.param that is scoped/passed thru every method on a route handler?”

Leave a Comment