A valid JSON Patch can still write the wrong state if you apply it to the wrong document. This tutorial shows you how to create a hash-guarded bundle with jsondiffnext, apply and revert it without mutating the caller’s object, and catch a mismatched base before any operation runs.
The examples below were run on Node.js 24.22.1 against jsondiffnext 0.1.0 from npm, on 28 November 2026. They use the public API in index.ts, adapters.ts, and core.ts.
This is a usage tutorial, not a walk through the wrapper internals. If you want the design notes — how the pin is computed, how staging works, and what the README’s exploratory timings are and are not — start with jsondiffnext pins the document, not the patch. Here you will install the package, run a small script, and look at the errors and engine differences you will actually hit.
What You Will Learn
- Why a well-formed RFC 6902 patch is not enough on its own
- How to install jsondiffnext and produce a version-1 bundle with SHA-256 pins
- How apply and revert work on a clone, and why the original object stays unchanged
- What error you get when the base document does not match the bundle
- When keyed array matching is useful, and which engine actually emits a
move
Prerequisites
- Node.js 24 or later (the package
enginesfield requires>=24) - A directory where you can run ESM (
"type": "module"inpackage.json, or a.mjsfile)
Install the published package:
npm install jsondiffnext
The default diff engine is fast-json-patch. The wrapper also exposes jsondiffpatch and rfc6902. You select one with { engine: 'jsondiffpatch' }; you do not change the bundle shape when you switch.
Start With a Small Document Pair
Create pin-demo.mjs:
import { diff, applyPatch, revertPatch, canonicalHash } from 'jsondiffnext';
const before = { users: [{ id: 'a', name: 'Ada' }] };
const after = { users: [{ id: 'a', name: 'Ada Lovelace' }] };
const bundle = diff(before, after);
console.log(bundle.version); // 1
console.log(bundle.algorithm); // 'sha256'
console.log(bundle.baseHash);
console.log(bundle.resultHash);
console.log(bundle.forward);
Run it with node pin-demo.mjs. On this package version you should see:
versionis1algorithmis'sha256'baseHashandresultHashare 64-character lowercase hex stringscanonicalHash(before) === bundle.baseHashandcanonicalHash(after) === bundle.resultHash
The hashes are SHA-256 of RFC 8785 canonical JSON, not of JSON.stringify output. That matters because key order is not part of JSON equality. Confirm it:
const left = { b: 1, a: 2 };
const right = { a: 2, b: 1 };
console.log(JSON.stringify(left) === JSON.stringify(right)); // false
console.log(canonicalHash(left) === canonicalHash(right)); // true
canonicalHash sorts object keys as UTF-16 code units and keeps array order. Two documents that canonicalize the same way share a pin. Lone Unicode surrogates, cycles, getters, undefined, and bigint are rejected during the scan that runs before the hash.
The forward array is not a bare RFC 6902 document you would hand to another library unchanged. With the default fast-json-patch engine, this example produces path-level test operations plus a replace:
[
{ "op": "test", "path": "/users/0/name", "value": "Ada" },
{ "op": "replace", "path": "/users/0/name", "value": "Ada Lovelace" }
]
The bundle also has an inverse delta so you can revert later. Treat the whole object as the unit of work: version, algorithm, baseHash, resultHash, forward, and inverse.
Apply Without Mutating the Caller
const updated = applyPatch(before, bundle);
console.log(JSON.stringify(updated));
// {"users":[{"id":"a","name":"Ada Lovelace"}]}
console.log(JSON.stringify(before));
// {"users":[{"id":"a","name":"Ada"}]}
console.log(canonicalHash(updated) === bundle.resultHash); // true
console.log(Object.isFrozen(updated)); // true
applyPatch does not write into before. It clones the document, applies operations on the clone, then checks that the staged result hashes to resultHash. The value you get back is a frozen deep clone. If you need to keep mutating a working copy, clone it yourself after apply; do not expect to assign through the returned object.
Revert uses the inverse delta and the hashes in the opposite direction:
const restored = revertPatch(updated, bundle);
console.log(canonicalHash(restored) === bundle.baseHash); // true
Catch a Patch Aimed at the Wrong Document
This is the reason to use a pin. Keep the bundle from the first example, and try to apply it to a different user list:
import { SpikeError } from 'jsondiffnext';
try {
applyPatch({ users: [{ id: 'z', name: 'Other' }] }, bundle);
} catch (error) {
if (error instanceof SpikeError) {
console.log(error.code); // PreconditionFailed
console.log(error.message); // Base document hash mismatch
} else {
throw error;
}
}
With the default { verifyBase: true }, the hash is checked before any patch operation runs. The wrong document is rejected with SpikeError code PreconditionFailed and the message Base document hash mismatch. That is cheaper and clearer than discovering, halfway through a patch, that a test operation failed.
You can skip the opening hash check with { verifyBase: false }. That does not make a mismatched document succeed. On this example, apply then fails on a test operation (Document does not match expected state) because the default engine embedded those tests in forward. The result-hash check still runs if operations complete. Leave verifyBase on unless you have a specific reason to skip it.
The hash is a mismatch detector, not a signature. Anyone who can write a bundle can compute SHA-256 of a document they chose. If a bundle crosses an untrusted boundary, sign it or MAC it separately. The package README states this limit explicitly.
Send the Bundle Over the Wire
A bundle is ordinary JSON. You can serialize it, store it, and apply the parsed object later:
const wire = JSON.parse(JSON.stringify(bundle));
const fromWire = applyPatch(before, wire);
console.log(canonicalHash(fromWire) === bundle.resultHash); // true
Use the same engine on apply that you used on diff if you pass { engine }. The default is fast-json-patch on both sides.
Keyed Arrays: Reorder Versus Rewrite
Array diffs are where engines disagree, and where “keyed” mode is worth turning on — if the engine you picked actually uses identities.
Take a two-item list that is reordered, with one field change:
const beforeUsers = {
users: [
{ id: 'a', name: 'Ada' },
{ id: 'b', name: 'Bob' },
],
};
const afterUsers = {
users: [
{ id: 'b', name: 'Bob' },
{ id: 'a', name: 'Ada Lovelace' },
],
};
With jsondiffpatch and { arrays: { mode: 'keyed' } }, the wrapper matches objects by id and the forward delta is a move plus a field replace:
const keyed = diff(beforeUsers, afterUsers, {
engine: 'jsondiffpatch',
arrays: { mode: 'keyed' },
});
console.log(keyed.forward);
// [
// { from: '/users/1', op: 'move', path: '/users/0' },
// { op: 'replace', path: '/users/1/name', value: 'Ada Lovelace' }
// ]
const updatedUsers = applyPatch(beforeUsers, keyed, { engine: 'jsondiffpatch' });
console.log(JSON.stringify(updatedUsers));
// {"users":[{"id":"b","name":"Bob"},{"id":"a","name":"Ada Lovelace"}]}
The same documents with { arrays: { mode: 'position' } } and jsondiffpatch do not emit a move. They rewrite fields in place at index 0 and index 1. That still applies to the correct final JSON, but it is a different patch: a consumer that is watching “move user b” will not see a move.
The default fast-json-patch engine, in the 0.1.0 build tested for this article, produced the same in-place test/replace operations for this fixture in both position and keyed modes. rfc6902 removed and appended items rather than moving them, in both modes. If you want identity-based moves, pass engine: 'jsondiffpatch' and arrays: { mode: 'keyed' }, and require unique string or number id values. Duplicate ids throw DuplicateIdentity.
That difference is why the public API lets you choose an engine. The bundle type stays the same; the operations inside forward do not.
A Complete Script You Can Run
Save this as pin-demo.mjs and run node pin-demo.mjs. It should print ok at the end.
import {
diff,
applyPatch,
revertPatch,
canonicalHash,
SpikeError,
} from 'jsondiffnext';
const before = { users: [{ id: 'a', name: 'Ada' }] };
const after = { users: [{ id: 'a', name: 'Ada Lovelace' }] };
const bundle = diff(before, after);
if (bundle.version !== 1 || bundle.algorithm !== 'sha256') {
throw new Error('unexpected bundle profile');
}
if (canonicalHash(before) !== bundle.baseHash) {
throw new Error('base pin does not match');
}
const updated = applyPatch(before, bundle);
if (canonicalHash(updated) !== bundle.resultHash) {
throw new Error('result pin does not match');
}
if (JSON.stringify(before) !== JSON.stringify({ users: [{ id: 'a', name: 'Ada' }] })) {
throw new Error('caller document was mutated');
}
try {
applyPatch({ users: [{ id: 'z', name: 'Other' }] }, bundle);
throw new Error('mismatch should have thrown');
} catch (error) {
if (!(error instanceof SpikeError) || error.code !== 'PreconditionFailed') {
throw error;
}
}
const restored = revertPatch(updated, bundle);
if (canonicalHash(restored) !== bundle.baseHash) {
throw new Error('revert did not restore the base pin');
}
console.log('ok');
If node refuses the import, check that you are on Node.js 24+ (node -v) and that the file is treated as ESM. If apply throws InvalidOptions with Unknown adapter, you passed an engine name the package does not define. The valid names are fast-json-patch, jsondiffpatch, and rfc6902.
When You Should Not Use the Wrapper
jsondiffnext clones the document, canonicalizes it, and hashes it on the way in and out. That work is the product. If you are on a tight hot path and you already trust both ends of the patch, a raw engine is simpler and cheaper. The project README reports wrapper end-to-end times in which hashing was a material fraction of the total; those figures are exploratory, single-machine numbers, not a throughput guarantee. This tutorial does not repeat them as a ranking of the three underlying libraries.
The wrapper also admits oversized or awkward input and, when a budget is exceeded or an engine cannot safely handle a key, may fall back to a hashed root replace. The bundle is still version 1 and still pinned. The patch is just larger. Do not assume every bundle contains a minimal in-place delta.
If you are comparing this wrapper to “just call fast-json-patch,” ask what happens when a stored patch is replayed against a document that has since changed. A raw library may apply the first operations, fail later, and leave you to reason about partial state. jsondiffnext’s default path refuses a hash mismatch up front, and it stages work on a clone so a mid-patch failure does not mutate the object you passed in. That is the trade you are paying for.
Other limits that are easy to miss:
- Only plain JSON values are accepted. Custom prototypes, sparse arrays, and circular references throw
InvalidJson. - A pointer segment of
__proto__is rejected as an unsafe write path. That is a pollution guard, not a general authorization system. applyPatchreturns a frozen clone of the result, not a live view of your application state.
Conclusion
A JSON Patch describes a change. It does not, by itself, prove you are holding the document that change was computed from. jsondiffnext’s version-1 bundle adds two SHA-256 pins of canonical JSON, applies on a clone, and refuses a mismatched base before operations run.
If you want to go further, read RFC 6902 and RFC 8785, then try one change in the demo: switch engines on the same documents and print forward. The interesting part is not that all three can reach the same result. It is how differently they get there, and how the hash still binds each bundle to one base and one result.
The package source is at github.com/2tsoftwareapp/jsondiffnext. An earlier write-up on how the wrapper is built lives at truongsoftware.com/blog/how-i-built-jsondiffnext. This tutorial is the companion that starts from npm install and a runnable file.