Node.js — Securely Parse JSON

Node.js provides a global JSON object providing methods to parse a JSON string to JavaScript or stringify JavaScript values to a JSON string.

The problem is that JavaScript’s global JSON object comes with a flaw allowing prototype pollution attacks. This tutorials shows you how to securely parse JSON with prototype pollution protection.

Node.js Series Overview

Prototype Pollution in a Nutshell

Consider the following code snippet illustrating the prototype pollution:

const json = '{"name":"Supercharge", "__proto__": { "x": 1 }}'

const a = JSON.parse(json)  
// { name: 'Supercharge' }

console.log(a.x)  
// undefined

const b = Object.assign({}, a)  
console.log(b.x)  
// 1

JSON.parse keeps the __proto__ property as a key on the parsed object. This becomes a problem when assigning that object to another object or copying values to another object. Then, the __proto__ property becomes the prototype of the new object.

Secure JSON.parse

That’s why we developed the @supercharge/json package to securely parse JSON strings. The @supercharge/json removes constructor and __proto__ keys when parsing objects.

Using @supercharge/json with the example from above keeps your code secure by removing injected prototype properties:

const JSON = require('@supercharge/json')

const json = '{"name":"Supercharge", "__proto__": { "x": 1 }}'

const a = JSON.parse(json)  
// { name: 'Supercharge' }

console.log(a.x)  
// undefined

const b = Object.assign({}, a)

console.log(b.x)  
// undefined    👈

That’s it!


Mentioned Resources

Explore the Library

Find interesting tutorials and solutions for your problems.