0
# Body Parsing
1
2
Request body parsing utilities for handling JSON, text, and binary data with size limits and encoding support. All functions cache the raw body on first call, allowing multiple parsing attempts.
3
4
## Capabilities
5
6
### Buffer Function
7
8
Parses request body as a Buffer with configurable size limits and encoding options.
9
10
```typescript { .api }
11
/**
12
* Parses request body as a Buffer with size limit protection
13
* @param req - Incoming HTTP request
14
* @param options - Configuration options for parsing
15
* @returns Promise resolving to Buffer containing raw body data
16
*/
17
function buffer(req: IncomingMessage, options?: BufferInfo): Promise<Buffer>;
18
19
interface BufferInfo {
20
/** Size limit for request body (default: '1mb') - can be number of bytes or string like '5mb' */
21
limit?: string | number | undefined;
22
/** Character encoding for text data (default: determined from Content-Type header) */
23
encoding?: BufferEncoding;
24
}
25
```
26
27
**Usage Examples:**
28
29
```typescript
30
import { buffer } from "micro";
31
32
const handler = async (req, res) => {
33
// Parse as buffer with default 1mb limit
34
const buf = await buffer(req);
35
console.log(buf); // <Buffer 7b 22 6e 61 6d 65 22 3a 20 22 4a 6f 68 6e 22 7d>
36
37
// With custom limit
38
const largeBuf = await buffer(req, { limit: '10mb' });
39
40
// With specific encoding
41
const encodedBuf = await buffer(req, {
42
limit: '5mb',
43
encoding: 'utf8'
44
});
45
46
return "Processed buffer data";
47
};
48
```
49
50
### Text Function
51
52
Parses request body as a string, internally using the buffer function and converting to text.
53
54
```typescript { .api }
55
/**
56
* Parses request body as a string with size limit protection
57
* @param req - Incoming HTTP request
58
* @param options - Configuration options for parsing
59
* @returns Promise resolving to string containing body text
60
*/
61
function text(req: IncomingMessage, options?: BufferInfo): Promise<string>;
62
```
63
64
**Usage Examples:**
65
66
```typescript
67
import { text } from "micro";
68
69
const handler = async (req, res) => {
70
// Parse as text with default settings
71
const bodyText = await text(req);
72
console.log(bodyText); // '{"name": "John"}'
73
74
// With custom limit and encoding
75
const customText = await text(req, {
76
limit: '2mb',
77
encoding: 'latin1'
78
});
79
80
// Process plain text data
81
const lines = bodyText.split('\n');
82
return { lineCount: lines.length, firstLine: lines[0] };
83
};
84
```
85
86
### JSON Function
87
88
Parses request body as JSON, internally using the text function and JSON.parse with error handling.
89
90
```typescript { .api }
91
/**
92
* Parses request body as JSON with size limit protection and error handling
93
* @param req - Incoming HTTP request
94
* @param options - Configuration options for parsing
95
* @returns Promise resolving to parsed JSON data
96
* @throws HttpError with status 400 if JSON parsing fails
97
*/
98
function json(req: IncomingMessage, options?: BufferInfo): Promise<unknown>;
99
```
100
101
**Usage Examples:**
102
103
```typescript
104
import { json, createError } from "micro";
105
106
const handler = async (req, res) => {
107
try {
108
// Parse JSON with default settings
109
const data = await json(req);
110
console.log(data); // { name: "John", age: 30 }
111
112
// With custom limit
113
const largeData = await json(req, { limit: '5mb' });
114
115
// Type assertion for known structure
116
const user = data as { name: string; age: number };
117
118
return {
119
message: `Hello ${user.name}`,
120
processedAge: user.age + 1
121
};
122
} catch (error) {
123
// JSON parsing errors are automatically converted to HTTP 400 errors
124
throw error;
125
}
126
};
127
128
// Multiple calls to same request (cached)
129
const multiParseHandler = async (req, res) => {
130
const data1 = await json(req); // Parses from request
131
const data2 = await json(req); // Returns cached result
132
133
return { same: data1 === data2 }; // true
134
};
135
```
136
137
## Error Handling
138
139
All body parsing functions handle various error conditions:
140
141
- **Size Limit Exceeded**: Throws `HttpError` with status 413 when body exceeds limit
142
- **Invalid JSON**: `json()` throws `HttpError` with status 400 for malformed JSON
143
- **Invalid Body**: Throws `HttpError` with status 400 for other parsing errors
144
145
**Error Example:**
146
147
```typescript
148
import { json, HttpError } from "micro";
149
150
const handler = async (req, res) => {
151
try {
152
const data = await json(req, { limit: '1kb' });
153
return data;
154
} catch (error) {
155
if (error instanceof HttpError) {
156
if (error.statusCode === 413) {
157
return { error: "Request too large" };
158
}
159
if (error.statusCode === 400) {
160
return { error: "Invalid JSON format" };
161
}
162
}
163
throw error;
164
}
165
};
166
```