A look at sveltejs/devalue: 2.8k stars on GitHub, written primarily in JavaScript. Gets the job done when JSON.stringify can't
Snapshot summary built from the project's own GitHub metadata — there's no written TopGit review yet. The page will update automatically when a full review is published.
WHY NO REVIEW YET
TopGit writes full reviews for the most-starred, most-requested repositories. This page is a snapshot until then — see the READ ME tab for the original README in full.
Stability of serialization mechanisms between versions (i.e. if you devalue.stringify with one version and devalue.parse with another, things may break)
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:
Use stringify and parse when evaluating JavaScript isn't an option.
stringifyAsync
stringifyAsync is an async version of stringify that can handle promises:
import * as devalue from 'devalue';
let obj = {
quick: 'data',
slow: fetch('/api/slow').then((r) => r.json())
};
let stringified = await devalue.stringifyAsync(obj);
devalue.parse(stringified); // { quick: 'data', slow: { ... } }
Promises are awaited and their resolved values are serialized. The output format is identical to stringify, so parse and unflatten work unchanged.
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:
Note that any variables referenced in the resulting JavaScript (like Vector in the example above) must be in scope when it runs.
Custom operations
Every introspection stringify performs on the value being serialized — property reads, prototype method calls, iteration, type classification — goes through an operations interface that you can override via the operations option. Omitted members fall back to the defaults (exported as defaultStringifyOperations), which behave exactly as devalue always has.
This is useful in two situations:
Side-effect-free serialization. By default, serializing a value can execute user code: getters and proxy traps fire during property reads, Object.prototype.toString consults (potentially getter-defined) Symbol.toStringTag, and patched prototype methods like Date.prototype.toISOString or Map.prototype[Symbol.iterator] are invoked. Deterministic or sandboxed runtimes can replace these operations with implementations based on captured intrinsics and property descriptors:
const originalToISOString = Date.prototype.toISOString;
const stringified = devalue.stringify(value, undefined, {
operations: {
// use a captured intrinsic instead of a (possibly patched) prototype method
toISOString: (date) => originalToISOString.call(date),
// read through descriptors so getters are never invoked
get: (object, key) => {
const descriptor = Object.getOwnPropertyDescriptor(object, key);
if (descriptor?.get) throw new Error(`refusing to invoke getter for "${key}"`);
return descriptor?.value;
}
}
});
Foreign-runtime serialization. The stringify algorithm never touches the value directly, so "value" can be an opaque handle to something living in another JavaScript runtime — a node:vm context, a WASM-hosted engine, a remote process — as long as the operations know how to inspect it. Implement typeOf/tagOf for classification, toPrimitive/get/entriesOf/etc. for extraction, and identify to key deduplication and cycle detection on the underlying value's identity rather than the handle's:
const stringified = devalue.stringify(rootHandle, undefined, {
operations: {
identify: (handle) => handle.pointer,
typeOf: (handle) => handle.typeOf(),
get: (handle, key) => handle.getProperty(key)
// ... see StringifyOperations for the full interface
}
});
Some operations have a non-obvious contract that is easy to get subtly wrong. Where the work is not specific to your values, devalue exports the pieces so you don't have to reimplement them — filterArrayIndices does the array-index filtering that indicesOf needs, given keys you already have:
Reducers compose with custom operations: they receive the raw value/handle, and whatever they return is serialized through the same operations.
Customizing parse
The mirror image: parse and unflatten build every value through construction operations (ParseOperations, defaults exported as defaultParseOperations), so you can control what gets created. The members mirror StringifyOperations with the host/value-space boundary running the other way: each fromXxx inverts the corresponding toXxx, fromXxxInfo inverts xxxInfo, and the bare-verb mutators invert the bare-verb accessors (set/get, addValue/valuesOf, addEntry/entriesOf, box/unbox).
Cross-realm revival. By default the revived value is built from the intrinsics of whichever realm devalue is running in, so instanceof checks fail elsewhere. Constructing from a target realm's intrinsics fixes that:
Foreign-runtime revival.parse never inspects the values it creates — it only passes them back into other operations — so the operations can build values inside another runtime and return opaque handles:
const rootHandle = devalue.parse(serialized, undefined, {
operations: {
fromPrimitive: (primitive) => vm.toHandle(primitive),
createObject: () => vm.newObject(),
set: (handle, key, value) => handle.setProp(key, value)
// ... see ParseOperations for the full interface
}
});
Containers are created empty and populated afterwards (createMap then addEntry, createObject then set, and so on) — that ordering is what allows cyclic values to be revived, since the empty container is cached before its contents are built.
Revivers compose the same way reducers do: they receive whatever the operations built, and their return value is used as-is.
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:
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:
TopGit's last sync did not record any GitHub topics for sveltejs/devalue. GitHub topics appear in the right sidebar of a repository page; that's the authoritative place to check.
How active is development on sveltejs/devalue?
The most recent commit recorded on sveltejs/devalue was 16 days ago, based on the GitHub push timestamp. The repository has 92 forks — one of the better signals of community interest.
How many stars does sveltejs/devalue have?
sveltejs/devalue has 2.8k GitHub stars — refresh the page for the live number, or check github.com/sveltejs/devalue. TopGit mirrors GitHub's count but does not claim minute-by-minute accuracy.
Is sveltejs/devalue open source?
Yes — sveltejs/devalue ships under the MIT license, which makes its source code freely readable (and, depending on license terms, forkable and reusable). Source: github.com/sveltejs/devalue.
Where can I see sveltejs/devalue in action?
The project maintains a homepage at https://svelte.dev/repl/138d70def7a748ce9eda736ef1c71239. The README tab on this page also usually contains screenshots and a quickstart.
Where do I read more about sveltejs/devalue?
This TopGit page is a snapshot — the READ ME tab shows the project's own README content (links stripped, images preserved). The GitHub repository at github.com/sveltejs/devalue is the definitive source.
Read full README in the tab above.
Is devalue worth your time?
ChatGPT, Claude and Perplexity can all read this page. Ask one of them what it makes of devalue.