or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

configuration.mdfile-system.mdindex.mdrequest-handling.md

index.mddocs/

0

# Serve Handler

1

2

Serve Handler is the routing foundation of the `serve` package, providing comprehensive HTTP request routing and static file serving capabilities. It offers extensive configuration options for URL rewriting, redirects, clean URLs, custom headers, directory listing, and middleware integration.

3

4

## Package Information

5

6

- **Package Name**: serve-handler

7

- **Package Type**: npm

8

- **Language**: JavaScript (Node.js)

9

- **Installation**: `npm install serve-handler`

10

11

## Core Imports

12

13

```javascript

14

const handler = require('serve-handler');

15

```

16

17

For ESM:

18

19

```javascript

20

import handler from 'serve-handler';

21

```

22

23

## Basic Usage

24

25

```javascript

26

const handler = require('serve-handler');

27

const http = require('http');

28

29

const server = http.createServer(async (request, response) => {

30

// Serve files from current directory

31

await handler(request, response);

32

});

33

34

server.listen(3000);

35

```

36

37

With configuration:

38

39

```javascript

40

const handler = require('serve-handler');

41

const micro = require('micro');

42

43

module.exports = micro(async (request, response) => {

44

await handler(request, response, {

45

public: './public',

46

cleanUrls: true,

47

trailingSlash: false

48

});

49

});

50

```

51

52

## Architecture

53

54

Serve Handler is built around several key components:

55

56

- **Main Handler**: Core async function that processes HTTP requests and responses

57

- **Path Resolution**: Intelligent path matching with support for rewrites, redirects, and clean URLs

58

- **File System Abstraction**: Pluggable file system operations for custom storage backends

59

- **Template System**: Built-in HTML templates for directory listings and error pages

60

- **Security Layer**: Path traversal protection and symlink handling

61

- **HTTP Features**: Range requests, ETag caching, custom headers, and content negotiation

62

63

## Capabilities

64

65

### Request Handler

66

67

Core HTTP request and response processing with extensive configuration options for static file serving, routing, and response customization.

68

69

```javascript { .api }

70

/**

71

* Main HTTP request handler for routing and static file serving

72

* @param request - HTTP request object

73

* @param response - HTTP response object

74

* @param config - Configuration options object

75

* @param methods - Custom file system method overrides

76

* @returns Promise that resolves when request handling is complete

77

*/

78

async function handler(

79

request: IncomingMessage,

80

response: ServerResponse,

81

config?: Config,

82

methods?: Methods

83

): Promise<void>;

84

```

85

86

[Request Handling](./request-handling.md)

87

88

### Configuration Options

89

90

Comprehensive configuration system supporting URL rewrites, redirects, clean URLs, custom headers, directory listing controls, and advanced routing patterns.

91

92

```javascript { .api }

93

interface Config {

94

/** Directory path to serve files from */

95

public?: string;

96

/** Enable clean URLs by stripping .html extensions */

97

cleanUrls?: boolean | string[];

98

/** URL rewrite rules */

99

rewrites?: RewriteRule[];

100

/** URL redirect rules */

101

redirects?: RedirectRule[];

102

/** Custom header rules */

103

headers?: HeaderRule[];

104

/** Enable/configure directory listing */

105

directoryListing?: boolean | string[];

106

/** Files/patterns to exclude from directory listings */

107

unlisted?: string[];

108

/** Force trailing slash behavior on URLs */

109

trailingSlash?: boolean;

110

/** Render single file in directory instead of listing */

111

renderSingle?: boolean;

112

/** Follow symbolic links */

113

symlinks?: boolean;

114

/** Use ETag headers instead of Last-Modified */

115

etag?: boolean;

116

}

117

```

118

119

[Configuration](./configuration.md)

120

121

### File System Methods

122

123

Pluggable file system abstraction allowing custom implementations for different storage backends, cloud storage, or specialized file handling requirements.

124

125

```javascript { .api }

126

interface Methods {

127

/** Custom lstat implementation */

128

lstat?: (path: string, fromDir?: boolean) => Promise<Stats>;

129

/** Custom realpath implementation */

130

realpath?: (path: string) => Promise<string>;

131

/** Custom read stream creator */

132

createReadStream?: (path: string, options?: object) => ReadableStream;

133

/** Custom directory reader */

134

readdir?: (path: string) => Promise<string[]>;

135

/** Custom error handler */

136

sendError?: (absolutePath: string, response: ServerResponse, acceptsJSON: boolean, current: string, handlers: object, config: Config, spec: ErrorSpec) => Promise<void>;

137

}

138

```

139

140

[File System Integration](./file-system.md)

141

142

## Types

143

144

```javascript { .api }

145

interface RewriteRule {

146

/** Source pattern (glob/regex) */

147

source: string;

148

/** Target path or URL */

149

destination: string;

150

}

151

152

interface RedirectRule {

153

/** Source pattern (glob/regex) */

154

source: string;

155

/** Target path or URL */

156

destination: string;

157

/** HTTP status code (default: 301) */

158

type?: number;

159

}

160

161

interface HeaderRule {

162

/** Source pattern (glob/regex) */

163

source: string;

164

/** Headers to apply */

165

headers: Array<{

166

key: string;

167

value: string;

168

}>;

169

}

170

171

interface ErrorSpec {

172

/** HTTP status code */

173

statusCode: number;

174

/** Error code identifier */

175

code: string;

176

/** Error message */

177

message: string;

178

/** Original error object (optional) */

179

err?: Error;

180

}

181

```