# jsonbash

> Blazing-fast, standardized JSON API response builder with built-in Rate Limiter, AES-256 Encryption, Pagination, Field Picker, Express middleware, http-status-codes, and TypeScript support.

Latest version **1.2.0** (published 2026-08-28) · MIT license · 0 weekly downloads

## Install

```sh
npm install jsonbash
pnpm add jsonbash
yarn add jsonbash
bun add jsonbash
```

## Health

**Score 60/100 (C)** — status: active.

Positive: has types; no vulnerabilities; recently updated; high maintenance score.

Warnings: low downloads; no esm support.

## Facts

| | |
|---|---|
| Version | 1.2.0 |
| Published | 2026-08-28 |
| First published | 2020-09-08 |
| Weekly downloads | 0 |
| License | MIT |
| TypeScript types | bundled |
| Module format | CommonJS |
| Dependencies | 1 |
| Unpacked size | 49.4 KB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| GitHub stars | 0 |
| Author | Harshil Kaneria |
| Maintainers | harshil-kaneria |
| Keywords | jsonbash, rate-limiter, express-rate-limit, aes-256-gcm, payload-encryption, field-picker, http-status-codes, express-middleware, api-response, json-response, response-builder, http-status, status-codes, express, rest-api, api-formatter, response-formatter, node-api-response, standard-json, json-builder, express-response, typescript, fast-json, json-api, http-response |

## Links

- npm: https://www.npmjs.com/package/jsonbash
- Repository: https://github.com/Harshil-Kaneria/JsonBash
- Homepage: https://github.com/Harshil-Kaneria/JsonBash#readme
- Issues: https://github.com/Harshil-Kaneria/JsonBash/issues
- npm.io page: https://npm.io/package/jsonbash

## Dependencies (1)

- [http-status-codes](https://npm.io/package/http-status-codes.md) ^2.3.0

## Alternatives

- [@mapbox/jsonlint-lines-primitives](https://npm.io/package/@mapbox/jsonlint-lines-primitives.md) — 5.3M weekly downloads
- [reftools](https://npm.io/package/reftools.md) — 3.5M weekly downloads
- [@hey-api/openapi-ts](https://npm.io/package/@hey-api/openapi-ts.md) — 3.5M weekly downloads
- [@mapbox/geojson-rewind](https://npm.io/package/@mapbox/geojson-rewind.md) — 2.4M weekly downloads
- [turbo-stream](https://npm.io/package/turbo-stream.md) — 1.7M weekly downloads

## Recent versions

- 1.2.0 (latest) — 2026-08-28
- 1.1.0 — 2026-08-28
- 1.0.1 — 2020-09-11
- 1.0.0 — 2020-09-08

## README

# JsonBash ⚡

> **A blazing-fast (46M+ ops/sec), feature-packed JSON API response framework for Node.js & Express. Features built-in Express Rate Limiter, AES-256-GCM Payload Encryption & Decryption, Selective Field Picker (`pick`), Data Sanitization (`sanitize`), Pagination, Validation Error formatting, `http-status-codes` integration, and native TypeScript support.**

---

## 📋 Table of Contents

- [Why JsonBash?](#-why-jsonbash)
- [Standard API Response Schema](#-standard-api-response-schema)
- [Installation](#-installation)
- [Usage Examples](#-usage-examples)
  - [1. Express Middleware & Global Configuration](#1-express-middleware--global-configuration)
  - [2. Semantic Helper Methods](#2-semantic-helper-methods)
  - [3. Express Rate Limiter: Global & Route-Level (`jsonbash.rateLimiter`)](#3-express-rate-limiter-global--route-level-jsonbashratelimiter)
  - [4. Data Filtering: Selective Picking (`pick`) & Sanitization (`sanitize`)](#4-data-filtering-selective-picking-pick--sanitization-sanitize)
  - [5. AES-256-GCM Payload Encryption & Decryption (Global & Route-Level)](#5-aes-256-gcm-payload-encryption--decryption-global--route-level)
  - [6. Pagination Helper (`jsonbash.paginate`)](#6-pagination-helper-jsonbashpaginate)
  - [7. Validation Error Formatter (`jsonbash.validationError`)](#7-validation-error-formatter-jsonbashvalidationerror)
  - [8. Global Express Error Handler (`jsonbash.errorHandler`)](#8-global-express-error-handler-jsonbasherrorhandler)
  - [9. Custom Response Builder (`jsonbash.build`)](#9-custom-response-builder-jsonbashbuild)
  - [10. Built-in `http-status-codes` Re-exports](#10-built-in-http-status-codes-re-exports)
  - [11. Direct Express Sender (`jsonbash.send`)](#11-direct-express-sender-jsonbashsend)
  - [12. Standard Function Call](#12-standard-function-call)
- [TypeScript Support](#-typescript-support)
- [License](#-license)

---

## 🚀 Why JsonBash?

- **Unified API Responses**: Gives every API endpoint in your backend a consistent, predictable JSON schema.
- **Blazing Performance**: Optimized for V8 engine execution (**46+ million operations/sec** with zero hidden-class de-optimizations).
- **🚦 Express Rate Limiter Built-in**: Configure global or route-level rate limiting (`rateLimit: { windowMs, max }`) returning structured HTTP 429 responses.
- **🔒 AES-256-GCM Encryption**: Zero-dependency payload encryption and decryption for high-security APIs.
- **🎯 Field Picker (`pick`) & Sanitizer (`sanitize`)**: Filter allowed fields or mask sensitive data recursively before sending.
- **📊 Pagination & Validation**: Auto-calculates `totalPages`, `hasNextPage`, and formats Zod/Joi/Express-Validator errors cleanly.
- **`http-status-codes` Included**: Re-exports all HTTP constants (`StatusCodes.OK`, `ReasonPhrases.NOT_FOUND`, etc.) out-of-the-box.
- **Express Ready**: Attach response helpers (`res.jsonbash.success()`, `res.jsonbash.paginate()`, `res.jsonbash.pick()`) with one line of middleware.

---

## 📐 Standard API Response Schema

All responses generated by `jsonbash` follow this clean, intuitive structure:

```json
{
  "success": true,
  "statusCode": 200,
  "statusText": "OK",
  "message": "User list retrieved successfully",
  "data": [
    { "id": 1, "name": "Harshil Kaneria" }
  ]
}
```

| Property | Type | Description |
| :--- | :--- | :--- |
| `success` | `boolean` | `true` for 2xx status codes; `false` for 4xx/5xx error codes. |
| `statusCode` | `number` | The HTTP status code (e.g. `200`, `201`, `400`, `404`, `422`, `429`, `500`). |
| `statusText` | `string` | Standard HTTP reason phrase (e.g. `"OK"`, `"Not Found"`, `"Too Many Requests"`). |
| `message` | `string` | Human-readable response summary or message. |
| `encrypted` | `boolean` | *(Optional)* Set to `true` when data payload is encrypted via AES-256-GCM. |
| `iv` | `string` | *(Optional)* Initialization vector hex string for decryption. |
| `authTag` | `string` | *(Optional)* GCM authentication tag hex string for security integrity. |
| `data` | `any` | *(Optional)* Main response payload (or ciphertext string if encrypted). |
| `pagination` | `object` | *(Optional)* Pagination details (`page`, `limit`, `totalItems`, `totalPages`, `hasNextPage`, `hasPrevPage`). |
| `errors` | `array` | *(Optional)* Array of validation errors (`[{ field, message }]`). |
| `retryAfterSeconds` | `number` | *(Optional)* Included on HTTP 429 Rate Limit responses. |
| `...extra` | `any` | *(Optional)* Any custom extra properties (e.g., `executionTimeMs`, `timestamp`). |

---

## 📦 Installation

```bash
npm install jsonbash
```

---

## 💻 Usage Examples

### 1. Express Middleware & Global Configuration

Register `jsonbash.middleware()` at the top of your Express app to attach `res.jsonbash` methods to every route. You can configure **Global Encryption** and **Global Rate Limiting** in one single call:

```javascript
const express = require('express');
const jsonbash = require('jsonbash');

const app = express();
app.use(express.json());

// Enable Global Encryption AND Global Rate Limiting across your whole Express app!
app.use(jsonbash.middleware({
  encryptKey: 'my-global-super-secret-key-32-chars', // Global AES-256 Encryption Key
  rateLimit: {
    windowMs: 15 * 60 * 1000, // 15 minutes window
    max: 100,                 // Max 100 requests per IP per window
    message: 'Global rate limit reached, please try again later'
  }
}));

// Route 1 - Automatically Rate Limited & Encrypted via Global Config
app.get('/api/users', (req, res) => {
  const users = [{ id: 1, name: 'Harshil Kaneria' }];
  return res.jsonbash.success(users, 'Users fetched successfully');
});

app.listen(3000, () => console.log('Server running on port 3000'));
```

---

### 2. Semantic Helper Methods

Semantic helper methods provide instant, pre-configured HTTP status response builders for Node.js & Express.

#### `jsonbash.success(data, message, statusCode, extra)` — HTTP 200 OK
```javascript
const response = jsonbash.success({ id: 1, name: 'Harshil' }, 'User details retrieved');
```
**JSON Response Output:**
```json
{
  "success": true,
  "statusCode": 200,
  "statusText": "OK",
  "message": "User details retrieved",
  "data": { "id": 1, "name": "Harshil" }
}
```

#### `jsonbash.created(data, message, extra)` — HTTP 201 Created
```javascript
const response = jsonbash.created({ id: 99, email: 'new@example.com' }, 'Account created successfully');
```
**JSON Response Output:**
```json
{
  "success": true,
  "statusCode": 201,
  "statusText": "Created",
  "message": "Account created successfully",
  "data": { "id": 99, "email": "new@example.com" }
}
```

#### `jsonbash.badRequest(message, data, extra)` — HTTP 400 Bad Request
```javascript
const response = jsonbash.badRequest('Invalid parameter format');
```
**JSON Response Output:**
```json
{
  "success": false,
  "statusCode": 400,
  "statusText": "Bad Request",
  "message": "Invalid parameter format"
}
```

#### `jsonbash.unauthorized(message, data, extra)` — HTTP 401 Unauthorized
```javascript
const response = jsonbash.unauthorized('Authentication bearer token missing or expired');
```
**JSON Response Output:**
```json
{
  "success": false,
  "statusCode": 401,
  "statusText": "Unauthorized",
  "message": "Authentication bearer token missing or expired"
}
```

#### `jsonbash.forbidden(message, data, extra)` — HTTP 403 Forbidden
```javascript
const response = jsonbash.forbidden('Insufficient permissions to access resource');
```
**JSON Response Output:**
```json
{
  "success": false,
  "statusCode": 403,
  "statusText": "Forbidden",
  "message": "Insufficient permissions to access resource"
}
```

#### `jsonbash.notFound(message, data, extra)` — HTTP 404 Not Found
```javascript
const response = jsonbash.notFound('Requested user profile not found');
```
**JSON Response Output:**
```json
{
  "success": false,
  "statusCode": 404,
  "statusText": "Not Found",
  "message": "Requested user profile not found"
}
```

#### `jsonbash.tooManyRequests(message, data, extra)` — HTTP 429 Too Many Requests
```javascript
const response = jsonbash.tooManyRequests('Rate limit exceeded, please slow down');
```
**JSON Response Output:**
```json
{
  "success": false,
  "statusCode": 429,
  "statusText": "Too Many Requests",
  "message": "Rate limit exceeded, please slow down"
}
```

#### `jsonbash.internalServerError(message, data, extra)` — HTTP 500 Internal Server Error
```javascript
const response = jsonbash.internalServerError('Database connection timeout');
```
**JSON Response Output:**
```json
{
  "success": false,
  "statusCode": 500,
  "statusText": "Internal Server Error",
  "message": "Database connection timeout"
}
```

#### `jsonbash.error(message, statusCode, data, extra)` — Generic Custom Error
```javascript
const response = jsonbash.error('Service temporarily under maintenance', 503);
```
**JSON Response Output:**
```json
{
  "success": false,
  "statusCode": 503,
  "statusText": "Service Unavailable",
  "message": "Service temporarily under maintenance"
}
```

---

### 3. Express Rate Limiter: Global & Route-Level (`jsonbash.rateLimiter`)

Protect your Express endpoints against DDoS and brute-force attacks with zero external dependencies.

#### Option A: Global Rate Limiting (Across Entire App)
Set rate limiting globally inside `jsonbash.middleware()`:

```javascript
app.use(jsonbash.middleware({
  rateLimit: {
    windowMs: 15 * 60 * 1000, // 15 minutes window
    max: 100,                 // Limit each client IP to 100 requests per window
    message: 'Global rate limit reached, please try again later'
  }
}));
```

#### Option B: Route-Level / Individual Endpoint Rate Limiting
Apply strict custom rate limits to sensitive routes (e.g. Login, Password Reset, OTP verification):

```javascript
// Protect login route with max 5 requests per 1 minute per IP
app.post('/api/login', jsonbash.rateLimiter({
  windowMs: 60 * 1000, // 1 minute
  max: 5,              // Max 5 attempts
  message: 'Too many login attempts, please try again in a minute'
}), (req, res) => {
  return res.jsonbash.success({ token: 'jwt_token' }, 'Login successful');
});
```

**JSON Output when Rate Limit is exceeded (HTTP 429 Too Many Requests):**
```json
{
  "success": false,
  "statusCode": 429,
  "statusText": "Too Many Requests",
  "message": "Too many login attempts, please try again in a minute",
  "retryAfterSeconds": 58,
  "limit": 5
}
```

*Sets standard HTTP rate-limit headers automatically: `X-RateLimit-Limit`, `X-RateLimit-Remaining`, `X-RateLimit-Reset`, and `Retry-After`.*

---

### 4. Data Filtering: Selective Picking (`pick`) & Sanitization (`sanitize`)

Filter payloads cleanly before sending over the network:

#### Selective Field Picker (`pick`)
Select **only** specific allowed fields from objects or data arrays:

```javascript
const rawUser = {
  id: 101,
  username: 'harshil_k',
  email: 'harshil@example.com',
  passwordHash: '$2b$10$...',
  internalFlags: { admin: true }
};

// Includes ONLY 'id', 'username', and 'email' in data output!
res.jsonbash.success(rawUser, 'User profile', 200, {
  pick: ['id', 'username', 'email']
});
```

**JSON Output:**
```json
{
  "success": true,
  "statusCode": 200,
  "statusText": "OK",
  "message": "User profile",
  "data": {
    "id": 101,
    "username": "harshil_k",
    "email": "harshil@example.com"
  }
}
```

#### Data Sanitization (`sanitize`)
Strip sensitive keys recursively from objects or data arrays:

```javascript
// Automatically strips 'password' & 'twoFactorSecret' from output!
res.jsonbash.success(userProfile, 'User profile fetched', 200, {
  sanitize: ['password', 'twoFactorSecret']
});
```

#### Standalone Utility Functions
```javascript
const pickedData = jsonbash.pick(dataArray, ['id', 'name', 'price']);
const sanitizedData = jsonbash.sanitize(rawData, ['password', 'ssn']);
```

---

### 5. AES-256-GCM Payload Encryption & Decryption (Global & Route-Level)

Zero-dependency payload encryption and decryption using Node's native C++ `crypto` module.

#### Option A: Global Encryption (Across Entire App)
Set `encryptKey` in `jsonbash.middleware()` to automatically encrypt response data payloads across all Express routes:

```javascript
app.use(jsonbash.middleware({
  encryptKey: 'my-global-super-secret-key-32-chars'
}));
```

#### Option B: Route-Level / Individual Endpoint Encryption
Override the global key or encrypt a specific route with a custom key:

```javascript
app.get('/api/top-secret', (req, res) => {
  const secretData = { bankAccount: 'CHASE-998127398', balance: 75000.00 };

  // Encrypts using a key specific to this route!
  return res.jsonbash.success(secretData, 'Top secret payload', 200, {
    encrypt: 'route-specific-secret-key-777'
  });
});
```

#### Option C: Per-Endpoint Skip (`encrypt: false`)
Skip global encryption for specific public endpoints to return plain unencrypted JSON:

```javascript
app.get('/api/public-info', (req, res) => {
  return res.jsonbash.success(publicData, 'Public operational data', 200, {
    encrypt: false // 👈 Skips global encryption for this endpoint!
  });
});
```

**Encrypted Response Output:**
```json
{
  "success": true,
  "statusCode": 200,
  "statusText": "OK",
  "message": "Sensitive data",
  "encrypted": true,
  "iv": "e9d589f364bce7ab7db112d8",
  "authTag": "8aa4fa8d4b3fa988a99037c76a04b047",
  "data": "c40089992aa5f24e5c247f8dbfcc9f1f218ed..."
}
```

#### Option D: Standalone Payload Decryption (`jsonbash.decrypt`)
Use `jsonbash.decrypt(encryptedPayload, secretKey)` anywhere in Node.js to decrypt ciphertext payloads back to original objects:

```javascript
const jsonbash = require('jsonbash');

const decryptedData = jsonbash.decrypt(encryptedResponsePayload, 'route-specific-secret-key-777');

console.log(decryptedData);
// Output: { bankAccount: "CHASE-998127398", balance: 75000 }
```

---

### 6. Pagination Helper (`jsonbash.paginate`)

Auto-calculates `totalPages`, `hasNextPage`, and `hasPrevPage` automatically:

```javascript
app.get('/api/products/paginated', (req, res) => {
  const page = parseInt(req.query.page || 1, 10);
  const limit = parseInt(req.query.limit || 5, 10);

  const products = [
    { id: 1, name: 'Headphones', price: 99.99 },
    { id: 2, name: 'Keyboard', price: 149.50 }
  ];

  return res.jsonbash.paginate(products, { page, limit, totalItems: 45 }, 'Products fetched');
});
```

**JSON Output:**
```json
{
  "success": true,
  "statusCode": 200,
  "statusText": "OK",
  "message": "Products fetched",
  "data": [
    { "id": 1, "name": "Headphones", "price": 99.99 },
    { "id": 2, "name": "Keyboard", "price": 149.50 }
  ],
  "pagination": {
    "page": 1,
    "limit": 5,
    "totalItems": 45,
    "totalPages": 9,
    "hasNextPage": true,
    "hasPrevPage": false
  }
}
```

---

### 7. Validation Error Formatter (`jsonbash.validationError`)

Formats error objects from **Zod**, **Joi**, **Express-Validator**, or custom objects into a clean, uniform list under **HTTP 422 Unprocessable Entity**:

```javascript
app.post('/api/register', (req, res) => {
  const zodResult = schema.safeParse(req.body);

  if (!zodResult.success) {
    return res.jsonbash.validationError(zodResult.error, 'Invalid input parameters');
  }
});
```

**JSON Output (HTTP 422):**
```json
{
  "success": false,
  "statusCode": 422,
  "statusText": "Unprocessable Entity",
  "message": "Invalid input parameters",
  "errors": [
    { "field": "email", "message": "Invalid email address format" },
    { "field": "password", "message": "String must contain at least 8 character(s)" }
  ]
}
```

---

### 8. Global Express Error Handler (`jsonbash.errorHandler`)

Catch uncaught exceptions across Express routes:

```javascript
app.get('/api/crash', (req, res, next) => {
  throw new Error('Database connection failed');
});

// Register Global Error Handler at the bottom of all routes
app.use(jsonbash.errorHandler({ stackTrace: process.env.NODE_ENV !== 'production' }));
```

**JSON Output (HTTP 500):**
```json
{
  "success": false,
  "statusCode": 500,
  "statusText": "Internal Server Error",
  "message": "Database connection failed",
  "stack": "Error: Database connection failed at ..."
}
```

---

### 9. Custom Response Builder (`jsonbash.build`)

```javascript
const jsonbash = require('jsonbash');

const response = jsonbash.build({
  success: true,
  statusCode: jsonbash.StatusCodes.ACCEPTED, // 202
  message: 'Background task scheduled',
  data: { taskId: 'task_88123' },
  executionTimeMs: 14.2,
  timestamp: new Date().toISOString()
});
```

---

### 10. Built-in `http-status-codes` Re-exports

```javascript
const {
  StatusCodes,
  ReasonPhrases,
  getReasonPhrase,
  getStatusCode
} = require('jsonbash');

console.log(StatusCodes.OK);                    // 200
console.log(StatusCodes.TOO_MANY_REQUESTS);     // 429
console.log(ReasonPhrases.OK);                  // "OK"
```

---

### 11. Direct Express Sender (`jsonbash.send`)

```javascript
app.get('/api/products', (req, res) => {
  const products = [{ id: 101, title: 'Laptop' }];
  return jsonbash.send(res, 200, 'Products loaded', products);
});
```

---

### 12. Standard Function Call

```javascript
const jsonbash = require('jsonbash');

const data = { id: 1, username: 'harshil' };
const result = jsonbash(true, "Data Fetch Successfully", data, { version: "v1" });
```

---

## 📘 TypeScript Support

```typescript
import jsonbash, { StatusCodes, JsonBashResponse, RateLimiterOptions } from 'jsonbash';

const response: JsonBashResponse<{ id: number }> = jsonbash.success(
  { id: 1 },
  'Typed success response',
  StatusCodes.OK
);
```

---

## 📄 License

[MIT](LICENSE)

---
_Source: https://npm.io/package/jsonbash · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
