json-parse-better-errors and secure-json-parse are both utilities designed to wrap the native JSON.parse method, but they solve different primary problems. json-parse-better-errors focuses exclusively on improving the developer experience by providing clearer, more actionable error messages when parsing fails. secure-json-parse, maintained by the Fastify team, prioritizes security by preventing prototype pollution attacks while also offering helpful error messaging. While both replace JSON.parse, their use cases diverge based on whether your main concern is debugging ease or runtime security.
Parsing JSON is a daily task in JavaScript development, but the native JSON.parse method has two well-known drawbacks: cryptic error messages and security vulnerabilities. When JSON.parse fails, it throws a generic SyntaxError that often lacks context about where the issue occurred. More critically, parsing untrusted JSON can lead to prototype pollution, a severe security flaw where attackers manipulate object prototypes to execute arbitrary code or crash applications.
The packages json-parse-better-errors and secure-json-parse address these issues, but with different priorities. Let's examine how they handle parsing, errors, and security.
json-parse-better-errors assumes the input is safe.
// json-parse-better-errors usage
const parse = require('json-parse-better-errors');
// No security checks performed on this object
const data = parse('{"__proto__": {"isAdmin": true}}');
// Result: { isAdmin: true } on the prototype - VULNERABLE
secure-json-parse treats all input as potentially malicious.
__proto__, constructor, and prototype.SyntaxError if dangerous keys are detected during parsing.// secure-json-parse usage
const sjson = require('secure-json-parse');
// Blocks prototype pollution attempts
try {
const data = sjson.parse('{"__proto__": {"isAdmin": true}}');
} catch (err) {
console.error(err.message);
// "Prototype pollution detected" - SAFE
}
json-parse-better-errors enhances the standard error output.
Unexpected token message.// json-parse-better-errors error output
const parse = require('json-parse-better-errors');
try {
parse('{"key": }'); // Invalid JSON
} catch (err) {
console.log(err.message);
// "Unexpected token } in JSON at position 8"
// Includes position index for easier debugging
}
secure-json-parse also provides clear errors but focuses on security violations.
// secure-json-parse error output
const sjson = require('secure-json-parse');
try {
sjson.parse('{"__proto__": {}}'); // Valid JSON, unsafe keys
} catch (err) {
console.log(err.message);
// "Prototype pollution detected"
// Clearly indicates a security block, not just a syntax issue
}
json-parse-better-errors offers a minimal API.
JSON.parse.// json-parse-better-errors API
const parse = require('json-parse-better-errors');
// Direct replacement for JSON.parse
const obj = parse('{"valid": "json"}');
// No options object supported
// parse('{"valid": "json"}', null, true); // Invalid
secure-json-parse provides a slightly richer API.
parse and stringify methods.stringify method ensures safe serialization as well.// secure-json-parse API
const sjson = require('secure-json-parse');
// Parse with security checks
const obj = sjson.parse('{"safe": "data"}');
// Stringify is also safe
const str = sjson.stringify(obj);
// Options can be passed to customize behavior
const obj2 = sjson.parse('{"data": 1}', { protoAction: 'remove' });
json-parse-better-errors is deprecated.
// Deprecation Notice
// npm WARN deprecated json-parse-better-errors@1.0.2:
// This package is no longer maintained.
// Consider using secure-json-parse or native JSON.parse with try/catch.
secure-json-parse is actively maintained.
// Active Maintenance
// Regular releases on npm
// Used in production by Fastify and many other frameworks
// Community support and issue tracking are active
You are loading a config file that your team controls and validates before commit.
json-parse-better-errorsJSON.parse with try/catch or secure-json-parsesecure-json-parse for consistency.// Modern approach for trusted config
import sjson from 'secure-json-parse';
try {
const config = sjson.parse(fs.readFileSync('config.json'));
} catch (err) {
console.error('Config parse failed:', err.message);
}
You are building an API that accepts JSON payloads from unknown users.
secure-json-parse{"__proto__": {"polluted": true}} to affect your application logic.// Secure API handling
import sjson from 'secure-json-parse';
app.post('/data', (req, res) => {
try {
// Safely parse incoming body
const data = sjson.parse(req.body);
processData(data);
} catch (err) {
res.status(400).send('Invalid or unsafe JSON');
}
});
You are fetching data from a third-party API in a React application.
secure-json-parse// Frontend data fetching
import sjson from 'secure-json-parse';
async function fetchData() {
const response = await fetch('/api/data');
const text = await response.text();
// Safe parsing of external data
const data = sjson.parse(text);
return data;
}
| Feature | json-parse-better-errors | secure-json-parse |
|---|---|---|
| Primary Goal | Better error messages | Security + Error messages |
| Prototype Pollution | β No protection | β Blocked by default |
| Maintenance | β Deprecated / Archived | β Active (Fastify team) |
| API | parse(text) | parse(text, options), stringify |
| Use Case | Legacy trusted data (Not recommended) | Untrusted data / Production APIs |
| Dependencies | None | None |
json-parse-better-errors should not be used in new projects.
It is deprecated, offers no security benefits, and solves a problem (better errors) that is now handled better by other tools or custom wrappers. If you need better error messages for trusted data, consider writing a small utility function around native JSON.parse that catches errors and adds context.
secure-json-parse is the industry standard for safe JSON parsing.
It provides critical security protections against prototype pollution without sacrificing performance or developer experience. It is actively maintained and widely adopted in the Node.js ecosystem. For any application handling external or user-generated JSON, this package is a necessary dependency.
Final Thought: Security should always come before convenience. Since secure-json-parse offers both security and improved error handling, it is the superior choice in almost every scenario. Avoid deprecated packages unless you are maintaining legacy code that cannot be refactored.
Choose json-parse-better-errors if your primary goal is to improve debugging and error reporting in a trusted environment where security risks like prototype pollution are already mitigated. It is a lightweight drop-in replacement that makes it easier to identify syntax errors in JSON payloads without adding security overhead. However, note that this package is deprecated and no longer maintained, so it should generally be avoided in new projects in favor of modern alternatives.
Choose secure-json-parse if you are parsing untrusted JSON input, especially in API servers or frontend applications handling external data. It protects against prototype pollution by default, which is a critical security vulnerability in JavaScript. It is actively maintained by the Fastify team and provides a robust, secure default for production environments where input validation is essential.
json-parse-better-errors is a Node.js library for
getting nicer errors out of JSON.parse(), including context and position of the parse errors.
$ npm install --save json-parse-better-errors
const parseJson = require('json-parse-better-errors')
parseJson('"foo"')
parseJson('garbage') // more useful error message
The npm team enthusiastically welcomes contributions and project participation! There's a bunch of things you can do if you want to contribute! The Contributor Guide has all the information you need for everything from reporting bugs to contributing entire new features. Please don't hesitate to jump in if you'd like to, or even ask us questions if something isn't clear.
All participants and maintainers in this project are expected to follow Code of Conduct, and just generally be excellent to each other.
Please refer to the Changelog for project history details, too.
Happy hacking!
> parse(txt, ?reviver, ?context=20)Works just like JSON.parse, but will include a bit more information when an
error happens.