Link Search Menu Expand Document

Code Injection in NodeJS

Vulnerable example

The following snippet defines the HTTP /update endpoint that receives a JSON object in a GET request and performs some back-end update procedures.

app.get('/update',function (req, res) {
  // Get the JSON object from "json" GET parameter
  var queryData = querystring.parse(url.parse(req.url).query);
    var jsonObj = eval('('+queryData.json+')');
    if( {
      // Do something with the parsed JSON object

The json HTTP parameter passed in the GET request is parsed by the eval() JavaScript function that evaluates code represented as a string. Since the content of json is provided by the user, this mechanism can be abused to execute arbitrary JavaScript code and conduct a Code Injection attack.

For example, an attacker could enter the URL /update?json=require('fs').writeFileSync('/tmp/maliciousfile','') to execute the JavaScript code in the json parameter and create /tmp/maliciousfile on the server’s disk.


Do not parse user-input using eval() or similar commands such as setTimeOut(), setInterval(), and Function().

For parsing JSON input, use the proper native function JSON.parse(). For type conversions, use parse functions such as parseInt() and parseFloat().


MDN web docs - eval() - JavaScript OWASP - Code Injection CWE - CWE-94: Improper Control of Generation of Code (‘Code Injection’)