TradeRaider
TradeRaider

Reputation: 754

How do I create a json object that gets appended to the actual response in node.js

I use jSON web tokens (simple-jwt) with my node application. I have a middleware(using express.js) that checks whether the token isValid?() and returns the user data if true.

But when the user does a GET request to localhost:8080/home or any other route, I need it to return the user data(from the tokenValidation middleware) and also the actual contents of localhost:8080/home. I can't use response.json({}) twice since that would be considered as two responses.

What is the standard way to append the user data with the actual json response?

If the code is required, let me know.

Upvotes: 0

Views: 122

Answers (1)

MatthieuLemoine
MatthieuLemoine

Reputation: 706

In your middleware you can add a new property to the reqobject.

(req, res, next) => {
  const user = ...queryUser
  req.user = user;
  next();
}

And in your route handler :

(req, res) => {
  const user = req.user;
  const otherData = { data : 'junk' };
  res.status(200).send({ user, otherData });
}

Upvotes: 1

Related Questions