@pas7/nestjs-strict-json
v1.1.1
Published
Strict JSON parsing for NestJS (Express/Fastify) with duplicate-key detection
Downloads
825
Maintainers
Readme
NestJS Strict JSON Parser for Security and Performance
@pas7/nestjs-strict-json is a strict JSON parser for NestJS, Express, and Fastify.
Read our article: Understanding JSON Security Vulnerabilities and How We Solve Them - deep dive into the problems this package solves.
It blocks dangerous and ambiguous payloads at parser level:
- duplicate JSON keys
- prototype pollution keys (
__proto__,constructor,prototype) - excessive JSON depth (DoS-style payloads)
- disallowed key paths (whitelist/blacklist)
If you need secure JSON parsing in Node.js APIs, this package is built for that exact use case.
Why teams use this
- Security first: parser-level rejection of duplicate keys and prototype pollution attempts.
- Production ready: works with NestJS, vanilla Express, and vanilla Fastify.
- Performance controls: cache, lazy mode, streaming threshold, fast path.
- Typed and explicit errors: stable error codes for monitoring and incident response.
Security
| Capability | Native JSON.parse | express.json() / default parsers | @pas7/nestjs-strict-json |
|---|---|---|---|
| Duplicate key rejection | No | No | Yes |
| Prototype pollution key blocking | No | No | Yes |
| Max depth enforcement | No | No | Yes |
| Key whitelist/blacklist | No | No | Yes |
| Unified behavior across Nest/Express/Fastify | No | Partial | Yes |
| Structured parser error codes | No | Limited | Yes |
Supported JSON Content-Types
| Content-Type | RFC | Supported |
|---|---|---|
| application/json | - | Yes |
| application/json-patch+json | RFC 6902 | Yes |
| application/vnd.api+json | JSON API | Yes |
| application/merge-patch+json | RFC 7396 | Yes |
| application/problem+json | RFC 7807 | Yes |
Installation
npm install @pas7/nestjs-strict-jsonQuick Start
NestJS + Fastify
import { NestFactory } from "@nestjs/core";
import { AppModule } from "./app.module";
import { registerStrictJson } from "@pas7/nestjs-strict-json";
async function bootstrap() {
const app = await NestFactory.create(AppModule);
registerStrictJson(app);
await app.listen(3000);
}
bootstrap();NestJS + Express
Important: disable default body parser so duplicate keys are not lost before strict parsing.
import { NestFactory } from "@nestjs/core";
import { AppModule } from "./app.module";
import { registerStrictJson } from "@pas7/nestjs-strict-json";
async function bootstrap() {
const app = await NestFactory.create(AppModule, { bodyParser: false });
registerStrictJson(app);
await app.listen(3000);
}
bootstrap();NestJS Module (DI)
import { Module } from "@nestjs/common";
import { StrictJsonModule } from "@pas7/nestjs-strict-json";
@Module({
imports: [
StrictJsonModule.forRoot({
enableCache: true,
maxDepth: 20,
maxBodySizeBytes: 5 * 1024 * 1024,
}),
],
})
export class AppModule {}NestJS Module (Async / ConfigModule)
import { Module } from "@nestjs/common";
import { ConfigModule, ConfigService } from "@nestjs/config";
import { StrictJsonModule } from "@pas7/nestjs-strict-json";
@Module({
imports: [
ConfigModule.forRoot(),
StrictJsonModule.forRootAsync({
imports: [ConfigModule],
useFactory: (config: ConfigService) => ({
enableCache: config.get("STRICT_JSON_CACHE_ENABLED", true),
maxDepth: config.get("STRICT_JSON_MAX_DEPTH", 20),
}),
inject: [ConfigService],
}),
],
})
export class AppModule {}Vanilla Express
import express from "express";
import { createStrictJsonExpressMiddleware } from "@pas7/nestjs-strict-json";
const app = express();
app.use(createStrictJsonExpressMiddleware({
maxBodySizeBytes: 1024 * 1024,
enableStreaming: true,
streamingThreshold: 100 * 1024,
}));
app.post("/api", (req, res) => {
res.json({ received: req.body });
});
app.listen(3000);Vanilla Fastify
import Fastify from "fastify";
import { registerStrictJsonFastify } from "@pas7/nestjs-strict-json";
const server = Fastify();
registerStrictJsonFastify(server, { maxBodySizeBytes: 1024 * 1024 });
server.post("/api", async (request) => request.body);
server.listen({ port: 3000 });API
Nest integration
registerStrictJson(app, options?)StrictJsonModule.forRoot(options?)StrictJsonModule.forRootAsync(asyncOptions?)
Adapter integration
createStrictJsonExpressMiddleware(options?)registerStrictJsonFastify(instance, options?)
Core parser
parseStrictJson(raw, options?)parseStrictJsonAsync(raw, options?)clearParseCache()getParseCacheSize()shutdownCacheManager()resetCacheManager()isCleanupIntervalRunning()
Validation utilities
isKeyAllowed(keyPath, whitelist?, blacklist?, ignoreCase?)createKeyPolicyValidator(whitelist?, blacklist?, ignoreCase?)globToRegex(pattern)matchGlobPattern(path, pattern)
StrictJsonOptions
type StrictJsonOptions = {
maxBodySizeBytes?: number;
enablePrototypePollutionProtection?: boolean;
dangerousKeys?: string[];
whitelist?: string[];
blacklist?: string[];
maxDepth?: number;
ignoreCase?: boolean;
enableStreaming?: boolean;
streamingThreshold?: number;
chunkSize?: number;
lazyMode?: boolean;
lazyModeThreshold?: number;
lazyModeDepthLimit?: number;
lazyModeSkipPrototype?: boolean;
lazyModeSkipWhitelist?: boolean;
lazyModeSkipBlacklist?: boolean;
enableCache?: boolean;
cacheSize?: number;
cacheTTL?: number;
enableFastPath?: boolean;
onDuplicateKey?: (error: unknown) => void | Promise<void>;
onInvalidJson?: (error: unknown) => void | Promise<void>;
onBodyTooLarge?: (error: unknown) => void | Promise<void>;
onPrototypePollution?: (error: unknown) => void | Promise<void>;
onError?: (error: unknown) => void | Promise<void>;
};Error Codes
STRICT_JSON_DUPLICATE_KEYSTRICT_JSON_INVALID_JSONSTRICT_JSON_BODY_TOO_LARGESTRICT_JSON_PROTOTYPE_POLLUTIONSTRICT_JSON_DEPTH_LIMIT
Recommended Production Configuration
registerStrictJson(app, {
maxBodySizeBytes: 1024 * 1024,
enablePrototypePollutionProtection: true,
maxDepth: 20,
enableCache: true,
enableFastPath: true,
});Compatibility
| Platform | Version | |---|---| | Node.js | 20+ | | NestJS | 10+ | | Express | 5+ | | Fastify | 5+ | | TypeScript | 5.x / 6.x |
Performance
| Implementation | Avg ms/op (1MB) | Relative Speed | |---|---|---| | Native JSON.parse | 5.36 | 1.0x (baseline) | | @pas7/nestjs-strict-json | 6.30 | 0.85x (18% slower) | | jsonc-parser + JSON.parse | 51.18 | 0.10x (10x slower) |
Reproduce:
npm run bench:compareDocumentation
- Wiki - comprehensive guides
- CHANGELOG - version history and release notes
- Optimization Guide - detailed tuning
- Performance Report - benchmarks
- Article: JSON Security Vulnerabilities - deep dive
Support
License
Apache-2.0 | Maintained by PAS7
