0
# Request Handling
1
2
Core HTTP request and response processing functionality that routes requests, resolves file paths, handles directory listings, serves static files, and manages error responses.
3
4
## Capabilities
5
6
### Main Handler Function
7
8
Processes incoming HTTP requests and generates appropriate responses, handling static file serving, directory listings, redirects, and error conditions.
9
10
```javascript { .api }
11
/**
12
* Main HTTP request handler for routing and static file serving
13
* @param request - HTTP request object with url, headers properties
14
* @param response - HTTP response object with writeHead, end, setHeader methods
15
* @param config - Configuration options object (optional)
16
* @param methods - Custom file system method overrides (optional)
17
* @returns Promise that resolves when request handling is complete
18
*/
19
async function handler(
20
request: IncomingMessage,
21
response: ServerResponse,
22
config?: Config,
23
methods?: Methods
24
): Promise<void>;
25
```
26
27
**Usage Examples:**
28
29
```javascript
30
const handler = require('serve-handler');
31
const http = require('http');
32
33
// Basic static file server
34
const server = http.createServer(async (req, res) => {
35
await handler(req, res);
36
});
37
38
// With custom configuration
39
const server = http.createServer(async (req, res) => {
40
await handler(req, res, {
41
public: './dist',
42
cleanUrls: true,
43
headers: [{
44
source: '**/*.js',
45
headers: [{
46
key: 'Cache-Control',
47
value: 'max-age=31536000'
48
}]
49
}]
50
});
51
});
52
53
// With custom file system methods
54
const server = http.createServer(async (req, res) => {
55
await handler(req, res, {}, {
56
lstat: async (path) => {
57
// Custom stat implementation
58
return await customLstat(path);
59
},
60
createReadStream: (path, options) => {
61
// Custom read stream (e.g., from cloud storage)
62
return customReadStream(path, options);
63
}
64
});
65
});
66
```
67
68
### Request Processing Flow
69
70
The handler processes requests through the following stages:
71
72
1. **URL Parsing**: Decodes the request URL and validates it
73
2. **Path Resolution**: Resolves the file system path and checks for path traversal
74
3. **Redirect Handling**: Applies clean URL, trailing slash, and custom redirect rules
75
4. **File Resolution**: Attempts to locate the requested file, including clean URL fallbacks
76
5. **Directory Handling**: Renders directory listings or serves single files from directories
77
6. **File Serving**: Streams file content with appropriate headers and range support
78
7. **Error Handling**: Generates error responses for missing files or server errors
79
80
### Response Types
81
82
The handler can generate several types of responses:
83
84
- **Static Files**: Direct file serving with proper MIME types and caching headers
85
- **Directory Listings**: HTML or JSON directory listings with navigation
86
- **Redirects**: 301/302 redirects for clean URLs, trailing slashes, or custom rules
87
- **Error Pages**: 404, 500, and other HTTP error responses with custom error pages
88
- **Range Responses**: Partial content responses (206) for range requests
89
90
### Content Negotiation
91
92
The handler supports content negotiation based on request headers:
93
94
- **Accept Header**: Detects JSON preference for directory listings
95
- **Range Header**: Handles partial content requests for large files
96
- **If-None-Match**: Supports conditional requests with ETag headers
97
98
### Security Features
99
100
Built-in security protections:
101
102
- **Path Traversal Protection**: Prevents access to files outside the public directory
103
- **Symlink Control**: Configurable symlink following to prevent security issues
104
- **File Exclusion**: Automatic exclusion of sensitive files (.git, .DS_Store, etc.)
105
106
### Error Handling
107
108
Comprehensive error handling with custom error page support:
109
110
```javascript
111
// Custom error handling
112
const server = http.createServer(async (req, res) => {
113
await handler(req, res, {}, {
114
sendError: async (absolutePath, response, acceptsJSON, current, handlers, config, spec) => {
115
// Custom error response logic
116
if (spec.statusCode === 404) {
117
response.statusCode = 404;
118
response.setHeader('Content-Type', 'text/html');
119
response.end('<h1>Custom 404 Page</h1>');
120
} else {
121
// Fallback to default error handling
122
await handlers.sendError(absolutePath, response, acceptsJSON, current, handlers, config, spec);
123
}
124
}
125
});
126
});
127
```