Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

devalue

Rich-Harris5.3mMIT5.1.1TypeScript support: included

Gets the job done when JSON.stringify can't

readme

devalue

Like JSON.stringify, but handles

  • cyclical references (obj.self = obj)
  • repeated references ([value, value])
  • undefined, Infinity, NaN, -0
  • regular expressions
  • dates
  • Map and Set
  • BigInt
  • ArrayBuffer and Typed Arrays
  • custom types via replacers, reducers and revivers

Try it out here.

Goals:

Non-goals:

  • Human-readable output
  • Stringifying functions

Usage

There are two ways to use devalue:

uneval

This function takes a JavaScript value and returns the JavaScript code to create an equivalent value — sort of like eval in reverse:

import * as devalue from 'devalue';

let obj = { message: 'hello' };
devalue.uneval(obj); // '{message:"hello"}'

obj.self = obj;
devalue.uneval(obj); // '(function(a){a.message="hello";a.self=a;return a}({}))'

Use uneval when you want the most compact possible output and don't want to include any code for parsing the serialized value.

stringify and parse

These two functions are analogous to JSON.stringify and JSON.parse:

import * as devalue from 'devalue';

let obj = { message: 'hello' };

let stringified = devalue.stringify(obj); // '[{"message":1},"hello"]'
devalue.parse(stringified); // { message: 'hello' }

obj.self = obj;

stringified = devalue.stringify(obj); // '[{"message":1,"self":0},"hello"]'
devalue.parse(stringified); // { message: 'hello', self: [Circular] }

Use stringify and parse when evaluating JavaScript isn't an option.

unflatten

In the case where devalued data is one part of a larger JSON string, unflatten allows you to revive just the bit you need:

import * as devalue from 'devalue';

const json = `{
  "type": "data",
  "data": ${devalue.stringify(data)}
}`;

const data = devalue.unflatten(JSON.parse(json).data);

Custom types

You can serialize and deserialize custom types by passing a second argument to stringify containing an object of types and their reducers, and a second argument to parse or unflatten containing an object of types and their revivers:

class Vector {
    constructor(x, y) {
        this.x = x;
        this.y = y;
    }

    magnitude() {
        return Math.sqrt(this.x * this.x + this.y * this.y);
    }
}

const stringified = devalue.stringify(new Vector(30, 40), {
    Vector: (value) => value instanceof Vector && [value.x, value.y]
});

console.log(stringified); // [["Vector",1],[2,3],30,40]

const vector = devalue.parse(stringified, {
    Vector: ([x, y]) => new Vector(x, y)
});

console.log(vector.magnitude()); // 50

If a function passed to stringify returns a truthy value, it's treated as a match.

You can also use custom types with uneval by specifying a custom replacer:

devalue.uneval(vector, (value, uneval) => {
    if (value instanceof Vector) {
        return `new Vector(${value.x},${value.y})`;
    }
}); // `new Vector(30,40)`

Note that any variables referenced in the resulting JavaScript (like Vector in the example above) must be in scope when it runs.

Error handling

If uneval or stringify encounters a function or a non-POJO that isn't handled by a custom replacer/reducer, it will throw an error. You can find where in the input data the offending value lives by inspecting error.path:

try {
    const map = new Map();
    map.set('key', function invalid() {});

    uneval({
        object: {
            array: [map]
        }
    });
} catch (e) {
    console.log(e.path); // '.object.array[0].get("key")'
}

XSS mitigation

Say you're server-rendering a page and want to serialize some state, which could include user input. JSON.stringify doesn't protect against XSS attacks:

const state = {
    userinput: `</script><script src='https://evil.com/mwahaha.js'>`
};

const template = `
<script>
  // NEVER DO THIS
  var preloaded = ${JSON.stringify(state)};
</script>`;

Which would result in this:

<script>
    // NEVER DO THIS
    var preloaded = {"userinput":"
</script>
<script src="https://evil.com/mwahaha.js">
    "};
</script>

Using uneval or stringify, we're protected against that attack:

const template = `
<script>
  var preloaded = ${uneval(state)};
</script>`;
<script>
    var preloaded = {
        userinput:
            "\\u003C\\u002Fscript\\u003E\\u003Cscript src='https:\\u002F\\u002Fevil.com\\u002Fmwahaha.js'\\u003E"
    };
</script>

This, along with the fact that uneval and stringify bail on functions and non-POJOs, stops attackers from executing arbitrary code. Strings generated by uneval can be safely deserialized with eval or new Function:

const value = (0, eval)('(' + str + ')');

Other security considerations

While uneval prevents the XSS vulnerability shown above, meaning you can use it to send data from server to client, you should not send user data from client to server using the same method. Since it has to be evaluated, an attacker that successfully submitted data that bypassed uneval would have access to your system.

When using eval, ensure that you call it indirectly so that the evaluated code doesn't have access to the surrounding scope:

{
    const sensitiveData = 'Setec Astronomy';
    eval('sendToEvilServer(sensitiveData)'); // pwned :(
    (0, eval)('sendToEvilServer(sensitiveData)'); // nice try, evildoer!
}

Using new Function(code) is akin to using indirect eval.

See also

License

MIT

changelog

devalue changelog

5.1.1

  • Only iterate over own properties of reducers (#80)

5.1.0

  • Handle typed arrays and array buffers (#69)
  • Add sideEffects: false to package.json (#81)
  • Better errors when keys are invalid identifiers (#82)

5.0.0

  • Ignore non-enumerable symbolic keys (#78)

4.3.3

  • Support invalid dates (#61)
  • Fix incorrect error.path when object contains a map (#64)

4.3.2

  • Better type declarations (#66)

4.3.1

4.3.0

  • Support custom types (#58)

4.2.3

  • Correctly escape control characters (#57)

4.2.2

  • Remove pkg.main (#56)

4.2.1

  • Re-use internal helper (#55)

4.2.0

  • Add unflatten (#48)

4.1.0

  • Only deduplicate non-primitives (#44)
  • Error on invalid input (#43)
  • Fix pkg.exports (#45)

4.0.1

  • Remove devalue export so that run time errors become build time errors

4.0.0

  • Rename devalue function to uneval
  • Add parse and stringify functions

3.1.3

  • Add pkg.main

3.1.2

  • Include pkg.types

3.1.1

  • Include types in pkg.files

3.1.0

  • Include path in error object if value is unserializable

3.0.1

  • Prevent duplicate parameter names (#33)

3.0.0

  • Convert to ESM
  • Change import devalue to import { devalue }
  • Support BigInt

2.0.1

  • Prevent regex XSS vulnerability in non-Node environments

2.0.0

  • Change license to MIT

1.1.1

  • Prevent object key XSS vulnerability (#19)

1.1.0

  • Escape lone surrogates (#13)

1.0.4

  • Smaller output (#10)

1.0.3

  • Detect POJOs cross-realm (#7)
  • Error on symbolic keys (#7)

1.0.2

  • Fix global name for UMD build

1.0.1

  • XSS mitigation (#1)

1.0.0

  • First release