Response Manipulation

The Response Manipulation Middleware allows for the dynamic modification of JSON response bodies before they are transmitted to the client. This is primarily used for security purposes, such as masking sensitive data, or for data transformation in multi-tenant environments.

Core Features

Dot Notation

Target specific fields in nested objects using standard dot notation (e.g., user.auth.token).

Circular Safety

Built-in support for circular references using XyPriss's high-performance XStringify engine.

Configuration

Configure manipulation rules globally in your server options. You can specify fields to mask, values to replace, and even use Regular Expressions for broad pattern matching.

typescript
const server = createServer({
        responseManipulation: {
            enabled: true,
            maxDepth: 10,
            rules: [
                { field: "api_key", preserve: 4 }, // ak-test-xyz -> ak-t***********
                { field: /.*(_id|Secret)$/, replacement: "[MASKED]" },
                { 
                    valuePattern: /prisma\./i, 
                    replacement: "Internal error occurred." 
                }
            ]
        },
});

Usage Scenarios

1. Surgical Content Masking

Hide database internals or sensitive error messages that might leak architectural details:

Output Masking Example
// Input
{ "message": "PrismaClientKnownRequestError: Invalid prisma.user.findUnique()..." }

// Output
{ "message": "Internal error occurred." }

2. Deep Object Protection

Ensure performance on large objects by limiting the depth of manipulation while still protecting deeply nested sensitive data.

typescript
responseManipulation: {
    enabled: true,
    maxDepth: 5,
    rules: [
        { field: "user.private_data", replacement: "[HIDDEN]" }
    ]
}

Internal Mechanism

01

Cloning

The body is cloned using XStringify, allowing safe mutation without affecting the internal state of the request cycle.

02

Recursive Traversal

The middleware performs a depth-limited traversal, applying rules in the order they are defined.

Object Processing Only
The middleware only processes objects where typeof data === 'object'. Non-object responses (strings, numbers, buffers) are passed through without modification.
XSec Security

Explore the high-performance Go-based cryptographic framework for enterprise security.