HTTP request routing and static file serving library that powers the serve package
—
Core HTTP request and response processing functionality that routes requests, resolves file paths, handles directory listings, serves static files, and manages error responses.
Processes incoming HTTP requests and generates appropriate responses, handling static file serving, directory listings, redirects, and error conditions.
/**
* Main HTTP request handler for routing and static file serving
* @param request - HTTP request object with url, headers properties
* @param response - HTTP response object with writeHead, end, setHeader methods
* @param config - Configuration options object (optional)
* @param methods - Custom file system method overrides (optional)
* @returns Promise that resolves when request handling is complete
*/
async function handler(
request: IncomingMessage,
response: ServerResponse,
config?: Config,
methods?: Methods
): Promise<void>;Usage Examples:
const handler = require('serve-handler');
const http = require('http');
// Basic static file server
const server = http.createServer(async (req, res) => {
await handler(req, res);
});
// With custom configuration
const server = http.createServer(async (req, res) => {
await handler(req, res, {
public: './dist',
cleanUrls: true,
headers: [{
source: '**/*.js',
headers: [{
key: 'Cache-Control',
value: 'max-age=31536000'
}]
}]
});
});
// With custom file system methods
const server = http.createServer(async (req, res) => {
await handler(req, res, {}, {
lstat: async (path) => {
// Custom stat implementation
return await customLstat(path);
},
createReadStream: (path, options) => {
// Custom read stream (e.g., from cloud storage)
return customReadStream(path, options);
}
});
});The handler processes requests through the following stages:
The handler can generate several types of responses:
The handler supports content negotiation based on request headers:
Built-in security protections:
Comprehensive error handling with custom error page support:
// Custom error handling
const server = http.createServer(async (req, res) => {
await handler(req, res, {}, {
sendError: async (absolutePath, response, acceptsJSON, current, handlers, config, spec) => {
// Custom error response logic
if (spec.statusCode === 404) {
response.statusCode = 404;
response.setHeader('Content-Type', 'text/html');
response.end('<h1>Custom 404 Page</h1>');
} else {
// Fallback to default error handling
await handlers.sendError(absolutePath, response, acceptsJSON, current, handlers, config, spec);
}
}
});
});Install with Tessl CLI
npx tessl i tessl/npm-serve-handler