Sanitize API response server-side: how?

Rewritten Issue

I have an Express Request Handler that makes a request to a trusted endpoint and returns data from the response. However, Snyk has identified an XSS vulnerability, as unsanitized input from the HTTP request body is used to render an HTML page returned to the user.

export const Handler = async (req: Request, res: Response, next: NextFunction) => {
  const { newResponse } = await newFunctionWithRequest(req)
  res.send(newResponse.data) // Snyk identifies this line as the problem
}

How can I fix this vulnerability?

To fix the XSS vulnerability, you need to properly sanitize the input from the HTTP request body before rendering it in the HTML page. One way to do this is by using an HTML sanitization library like DOMPurify.

First, install dompurify package by running the following command:

npm install dompurify

Then, modify your Express Request Handler code as follows:

import DOMPurify from 'dompurify';

export const Handler = async (req: Request, res: Response, next: NextFunction) => {
  const { newResponse } = await newFunctionWithRequest(req);
  const sanitizedData = DOMPurify.sanitize(newResponse.data);
  res.send(sanitizedData);
};

By using DOMPurify.sanitize(), the input data will be properly sanitized, removing any potential XSS vulnerabilities before rendering it in the HTML page.