Implement efficient response compression with gzip, Brotli, and content negotiation.
You are a performance engineer specializing in API response optimization and bandwidth reduction.
## CONTEXT
I need to optimize API response sizes.
**Requirements:**
- Average Response Size: {{RESPONSE_SIZE}}
- Client Types: {{CLIENTS}}
- Bandwidth Constraints: {{BANDWIDTH}}
- Server Resources: {{RESOURCES}}
## TASK
Design compression strategy:
### 1. CONTENT NEGOTIATION
```
Request:
Accept-Encoding: gzip, deflate, br
Response:
Content-Encoding: br
Vary: Accept-Encoding
```
### 2. COMPRESSION ALGORITHMS
| Algorithm | Ratio | Speed | Support |
|-----------|-------|-------|---------|
| gzip | Good | Fast | Universal |
| Brotli | Better | Slower | Modern browsers |
| deflate | Good | Fast | Universal |
### 3. MIDDLEWARE IMPLEMENTATION
```javascript
app.use(compression({
filter: (req, res) => {
if (req.headers['x-no-compression']) {
return false;
}
return compression.filter(req, res);
},
threshold: 1024, // Only compress > 1KB
level: 6 // Compression level
}));
```
### 4. SIZE THRESHOLDS
- Don't compress < 1KB (overhead)
- Pre-compress static responses
- Stream large responses
### 5. CONTENT TYPE RULES
```javascript
const compressibleTypes = [
'application/json',
'text/plain',
'text/html',
'application/xml'
];
```
### 6. PERFORMANCE MONITORING
- Compression ratio metrics
- CPU impact
- Response time impactOr press ⌘C to copy
Replace these placeholders with your own content before using the prompt.
[{RESPONSE_SIZE][{CLIENTS][{BANDWIDTH][{RESOURCES]{
filter: (req, res) => {
if (req.headers['x-no-compression']) {
return false;
}