JSON Plugin
Parses incoming JSON request bodies and populates req.body with the parsed data. Automatically handles content-type detection, size limits, and error handling.
Quick Start
import { Server } from 'balda-js';
const server = new Server({
plugins: {
json: {
sizeLimit: "10mb"
}
}
});
Configuration
sizeLimit
Maximum request body size. Supports kb and mb units.
json: {
sizeLimit: "100kb" // Default
}
json: {
sizeLimit: "10mb" // For larger payloads
}
parseEmptyBodyAsObject
Handle empty request bodies:
json: {
parseEmptyBodyAsObject: false // Default: req.body is undefined
}
json: {
parseEmptyBodyAsObject: true // Empty body becomes {}
}
encoding
Text encoding for decoding request bodies:
json: {
encoding: 'utf-8' // Default
}
json: {
encoding: 'utf-16le' // Alternative encoding
}
customErrorMessage
Customize error responses:
json: {
sizeLimit: "10mb",
customErrorMessage: {
status: 413,
message: 'Payload too large'
}
}
Usage
Basic Parsing
@controller('/api')
export class ApiController {
@post('/users')
async createUser(req: Request, res: Response) {
const { name, email } = req.body; // Automatically parsed
res.created({ name, email });
}
}
Empty Body Handling
@post('/health')
async healthCheck(req: Request, res: Response) {
if (req.body === undefined) {
// Empty body with parseEmptyBodyAsObject: false
res.json({ status: 'ok', body: 'empty' });
}
}
Error Responses
Size Limit Exceeded
// Response: 413 Payload Too Large
{
"error": "ERR_REQUEST_BODY_TOO_LARGE"
}
Invalid JSON
// Response: 400 Bad Request
{
"error": "Invalid JSON syntax"
}
Invalid Encoding
// Response: 400 Bad Request
{
"error": "Invalid request body encoding"
}
Content-Type Detection
Automatically parses requests with:
application/jsonapplication/json; charset=utf-8
Other content types are ignored.
HTTP Method Support
- Parsed: POST, PUT, PATCH
- Ignored: GET, DELETE, HEAD, OPTIONS
Environment-Based Configuration
const isProduction = process.env.NODE_ENV === 'production';
const server = new Server({
plugins: {
json: {
sizeLimit: isProduction ? "1mb" : "10mb",
customErrorMessage: isProduction ? {
status: 413,
message: 'Request too large'
} : undefined
}
}
});
Performance Tips
- Set reasonable size limits to prevent memory issues
- For large file uploads, use the File plugin instead
- Default
100kblimit is suitable for most APIs