Express Fast JSON Stringify
🚀 High-performance JSON serialization middleware for Express.js using fast-json-stringify.

Features
- ⚡ Performance: Up to 24% faster JSON serialization for simple objects
- 🔧 Easy Integration: Drop-in middleware for Express applications
- 🛡️ Safe Fallback: Automatic fallback to standard JSON.stringify when needed
- 🎯 Schema-based: Uses JSON Schema for optimal serialization
- 🔄 JSONP Support: Full compatibility with Express JSONP responses
- 📊 Multiple Schemas: Support for different schemas per route
- 🎛️ Configurable: Replace default behavior or use alongside existing methods
Installation
npm install express-fast-json
Quick Start
const express = require("express");
const fastJsonMiddleware = require("express-fast-json");
const app = express();
const userSchema = {
type: "object",
properties: {
id: { type: "integer" },
name: { type: "string" },
email: { type: "string", format: "email" },
},
};
app.use("/api/users", fastJsonMiddleware(userSchema));
app.get("/api/users/:id", (req, res) => {
const user = { id: 1, name: "John Doe", email: "john@example.com" };
res.fastJson(user);
});
app.listen(3000);
Usage Examples
Basic Usage (CommonJS)
const fastJsonMiddleware = require("express-fast-json");
const schema = {
type: "object",
properties: {
id: { type: "integer" },
message: { type: "string" },
},
};
app.use(fastJsonMiddleware(schema));
app.get("/api/data", (req, res) => {
res.fastJson({ id: 1, message: "Hello World" });
});
ES6+ Module Usage
import express from "express";
import fastJsonMiddleware, { createSchemaRegistry } from "express-fast-json";
const app = express();
const userSchema = {
type: "object",
properties: {
id: { type: "integer" },
name: { type: "string" },
email: { type: "string", format: "email" },
},
};
app.use("/api/users", fastJsonMiddleware(userSchema));
app.get("/api/users/:id", async (req, res) => {
const { id } = req.params;
const user = await getUserById(parseInt(id));
res.fastJson(user);
});
Replace Default Behavior
app.use(fastJsonMiddleware(schema, { replaceDefault: true }));
app.get("/api/data", (req, res) => {
res.json({ id: 1, message: "Hello World" });
});
Multiple Schemas with Registry
const { createSchemaRegistry } = require("express-fast-json");
const registry = createSchemaRegistry();
registry.register("user", userSchema).register("product", productSchema);
app.use("/api/users", registry.middleware("user"));
app.use("/api/products", registry.middleware("product"));
app.get("/api/users/:id", (req, res) => {
res.fastJson(userData);
});
app.get("/api/products/:id", (req, res) => {
res.fastJson(productData);
});
JSONP Support
app.use(fastJsonMiddleware(schema));
app.get("/api/data", (req, res) => {
res.fastJsonp({ id: 1, message: "Hello World" });
});
Error Handling and Fallback
app.use(
fastJsonMiddleware(schema, {
fallback: true,
replaceDefault: false,
})
);
app.get("/api/data", (req, res) => {
res.fastJson(someComplexData);
});
API Reference
fastJsonMiddleware(schema, options)
Creates Express middleware for fast JSON serialization.
Parameters
schema (Object): JSON Schema for serialization
options (Object): Configuration options
replaceDefault (Boolean): Replace default res.json() behavior (default: false)
fallback (Boolean): Fallback to JSON.stringify on error (default: true)
Returns
Express middleware function that adds fastJson and fastJsonp methods to the response object.
Added Response Methods
res.fastJson(object)
Serializes and sends JSON response using fast-json-stringify.
res.fastJsonp(object)
Serializes and sends JSONP response using fast-json-stringify.
Schema Registry
createSchemaRegistry()
Creates a schema registry for managing multiple schemas.
const registry = createSchemaRegistry();
registry.register(name, schema)
Registers a schema with a given name.
registry.middleware(schemaName, options)
Returns middleware for a specific schema.
Performance Benchmarks
Based on our benchmarks using Node.js v18:
| Single User Object | 2,530,746 ops/sec | 3,147,171 ops/sec | +24% |
| Simple Arrays (10 items) | 323,895 ops/sec | 304,866 ops/sec | -6% |
| Large Arrays (100 items) | 33,117 ops/sec | 29,678 ops/sec | -10% |
| HTTP Response Time | 0.113ms avg | 0.104ms avg | +8% |
When to Use
Recommended for:
- Simple to medium complexity objects
- High-frequency API endpoints
- Consistent data structures
- Performance-critical applications
Consider alternatives for:
- Highly variable data structures
- Very large arrays (100+ items)
- One-off serializations
JSON Schema Guide
fast-json-stringify requires a JSON Schema to optimize serialization. Here are some examples:
Basic Object Schema
const userSchema = {
type: "object",
properties: {
id: { type: "integer" },
name: { type: "string" },
email: { type: "string", format: "email" },
active: { type: "boolean" },
createdAt: { type: "string", format: "date-time" },
},
required: ["id", "name", "email"],
};
Array Schema
const usersArraySchema = {
type: "array",
items: userSchema,
};
Nested Object Schema
const userWithAddressSchema = {
type: "object",
properties: {
id: { type: "integer" },
name: { type: "string" },
address: {
type: "object",
properties: {
street: { type: "string" },
city: { type: "string" },
country: { type: "string" },
},
},
},
};
Flexible Schema with anyOf
const flexibleSchema = {
anyOf: [{ type: "null" }, userSchema, { type: "array", items: userSchema }],
};
Express Settings Compatibility
The middleware respects Express application settings:
json escape: Escapes HTML-unsafe characters
json replacer: Custom replacer function (falls back to JSON.stringify)
json spaces: Pretty-printing (falls back to JSON.stringify)
jsonp callback name: Custom JSONP callback parameter name
Error Handling
When fallback: true (default), the middleware will:
- Attempt fast-json-stringify serialization
- On error, log a warning and use standard JSON.stringify
- Continue with normal Express response flow
When fallback: false:
- Attempt fast-json-stringify serialization
- On error, throw an error (handle with Express error middleware)
app.use(fastJsonMiddleware(schema, { fallback: false }));
app.use((err, req, res, next) => {
console.error("Serialization error:", err.message);
res.status(500).json({ error: "Serialization failed" });
});
Development
Running Tests
npm test
Running Benchmarks
npm run benchmark
Starting Demo App
npm start
Contributing
This project aims to enhance Express.js JSON serialization performance while maintaining full compatibility with existing Express applications.
Issue Reference
This implementation addresses Express.js Issue #5997 - "Use fast-json-stringify for improved JSON response speed and efficiency."
Pull Request Guidelines
- Maintain backwards compatibility
- Add tests for new features
- Update documentation
- Run benchmarks and include results
License
MIT License - see LICENSE file for details.
Related Projects
- fast-json-stringify - The underlying fast JSON serialization library
- Express.js - Fast, unopinionated, minimalist web framework for Node.js
- Fastify - Fast and low overhead web framework, which inspired this optimization
Made with ❤️ for the Express.js community