I'm using the express-xss-sanitizer package to sanitize incoming requests in my Node.js Express application. However, I'm still seeing issues reported by Checkmarx regarding potential XSS attacks. I'm wondering if I need to sanitize response data before sending it to the client as well.
I've been under the impression that sanitizing input data is sufficient to prevent XSS attacks. However, the repeated Checkmarx warnings are making me doubt my understanding. Can someone clarify whether I need to sanitize response data as well?
[![charityApiRouter.get('/charity/getCampaigns', async (req, res) => {
const \[err, responseBody\] = await getCampaignData(req);
if (err) {
res.status(400).send({ success: false, err });
return;
}
res._end = true;
res.jsonp({
success: true,
data: responseBody.data,
});
});][1]][1]
You do not sanitize response since response is generated by your application code using the input provided. If input is sanitized, response will be clean as well(unless you have some issue with the business logic itself). But what you should do is to send the exact data you want. Meaning instead of sending data object directly(which is most likely db query result), you should send specific fields that you expect user to consume, like:
This ensures that user only gets the data you expect them to get. This is especially important if you are developing public api. This way you will also not leak any unnecessary metadata to the client.