New:Microsoft Teams Notifications Are Now Available in Socket.Learn more
Get Started

express-fast-json

Package Overview
Dependencies
Maintainers
1
Versions
2
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install
Package was removed
Sorry, it seems this package was removed from the registry

express-fast-json

High-performance Express.js middleware for fast JSON serialization using fast-json-stringify. Up to 24% faster than standard JSON.stringify.

Source
npmnpm
Version
1.1.0
Version published
Maintainers
1
Created
Source

Express Fast JSON Stringify

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

npm version Build Status

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();

// Define a JSON schema for your data
const userSchema = {
  type: "object",
  properties: {
    id: { type: "integer" },
    name: { type: "string" },
    email: { type: "string", format: "email" },
  },
};

// Apply middleware
app.use("/api/users", fastJsonMiddleware(userSchema));

// Use fast serialization
app.get("/api/users/:id", (req, res) => {
  const user = { id: 1, name: "John Doe", email: "john@example.com" };
  res.fastJson(user); // 24% faster than res.json()
});

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" },
  },
};

// Modern middleware usage
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); // Fast serialization!
});

Replace Default Behavior

app.use(fastJsonMiddleware(schema, { replaceDefault: true }));

app.get("/api/data", (req, res) => {
  // res.json() now uses fast-json-stringify automatically
  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); // Uses user schema
});

app.get("/api/products/:id", (req, res) => {
  res.fastJson(productData); // Uses product schema
});

JSONP Support

app.use(fastJsonMiddleware(schema));

app.get("/api/data", (req, res) => {
  res.fastJsonp({ id: 1, message: "Hello World" });
  // Supports ?callback=myCallback for JSONP
});

Error Handling and Fallback

app.use(
  fastJsonMiddleware(schema, {
    fallback: true, // Default: true
    replaceDefault: false, // Default: false
  })
);

app.get("/api/data", (req, res) => {
  // If serialization fails, automatically falls back to JSON.stringify
  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:

Data TypeStandard JSON.stringifyfast-json-stringifyImprovement
Single User Object2,530,746 ops/sec3,147,171 ops/sec+24%
Simple Arrays (10 items)323,895 ops/sec304,866 ops/sec-6%
Large Arrays (100 items)33,117 ops/sec29,678 ops/sec-10%
HTTP Response Time0.113ms avg0.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
# Visit http://localhost:3000 for examples

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.

  • 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

Keywords

express

FAQs

Package last updated on 03 Nov 2025

Related posts