messerbill
messerbill

Reputation: 5639

Custom middleware for express routes

I actually implemented a custom middleware in an expressJs application. I aim for modifying the request object before sending it back. It works and the result is exactly what i was expecting, but i am not sure if this is the correct way to do so. I am kind of afraid, that manipulating the reqeust object is not the correct way to do this.

Here is the code:

expressApp.get('/apps/:id', isAuthenticated, appLinks(dbController), async (req, res) => {
  res.send(req.__appLink)
})

app-links.ts:

export const appLinks: MiddlewareWrapper = (dbController: DatabaseHandler) => async (req: Request, res: Response, next: NextFunction) => {

  dbResult = modifyMyDatabaseResult(await dbController.getApps());
  req.__appLink = dbResult
  next()

}

As you can see, in my route i send req.__appLink which was set inside the middleware. It this the correct way to do such things?

Upvotes: 0

Views: 47

Answers (2)

Deep Kumar Singh
Deep Kumar Singh

Reputation: 156

Yes this is fine. But for better presentation you can save the result of req._appLink in a variable and pass it to res object.

Upvotes: 1

Kyle DePace
Kyle DePace

Reputation: 156

This is good! Nothing is wrong with modifying the req object.

Upvotes: 1

Related Questions