0
# serve-static
1
2
serve-static provides Express.js middleware for serving static files from a directory. It enables web servers to efficiently serve static assets like HTML, CSS, JavaScript, images, and other files with configurable options for caching, security, and file handling.
3
4
## Package Information
5
6
- **Package Name**: serve-static
7
- **Package Type**: npm
8
- **Language**: JavaScript
9
- **Installation**: `npm install serve-static`
10
11
## Core Imports
12
13
```javascript
14
const serveStatic = require('serve-static');
15
```
16
17
## Basic Usage
18
19
```javascript
20
const express = require('express');
21
const serveStatic = require('serve-static');
22
23
const app = express();
24
25
// Basic static file serving
26
app.use(serveStatic('public'));
27
28
// With options
29
app.use(serveStatic('public', {
30
index: ['index.html', 'index.htm'],
31
maxAge: '1d',
32
dotfiles: 'ignore'
33
}));
34
35
app.listen(3000);
36
```
37
38
## Capabilities
39
40
### Middleware Factory Function
41
42
Creates a new middleware function to serve files from within a given root directory.
43
44
```javascript { .api }
45
/**
46
* Create a new middleware function to serve files from within a given root directory
47
* @param {string} root - Root directory path for serving files (required)
48
* @param {ServeStaticOptions} options - Configuration options (optional)
49
* @returns {Function} Express/Connect middleware function
50
* @throws {TypeError} When root path is missing or not a string
51
* @throws {TypeError} When setHeaders option is not a function
52
*/
53
function serveStatic(root, options);
54
```
55
56
**Usage Examples:**
57
58
```javascript
59
// Basic usage
60
const serve = serveStatic('public/assets');
61
62
// With comprehensive options
63
const serve = serveStatic('public', {
64
index: ['index.html', 'default.html'],
65
maxAge: '1 day',
66
etag: true,
67
lastModified: true,
68
dotfiles: 'ignore',
69
fallthrough: true,
70
redirect: true,
71
setHeaders: function(res, path, stat) {
72
res.setHeader('X-Timestamp', Date.now());
73
}
74
});
75
76
// Express integration
77
const express = require('express');
78
const app = express();
79
app.use('/static', serve);
80
81
// Vanilla Node.js integration
82
const http = require('http');
83
const finalhandler = require('finalhandler');
84
const server = http.createServer(function(req, res) {
85
serve(req, res, finalhandler(req, res));
86
});
87
```
88
89
### Returned Middleware Function
90
91
The middleware function returned by `serveStatic()` handles HTTP requests for static files.
92
93
```javascript { .api }
94
/**
95
* Express/Connect middleware function for serving static files
96
* @param {Object} req - HTTP request object
97
* @param {Object} res - HTTP response object
98
* @param {Function} next - Next middleware function
99
*/
100
function middleware(req, res, next);
101
```
102
103
## Configuration Options
104
105
All options are passed as properties of an options object to the `serveStatic()` function:
106
107
### acceptRanges
108
109
```javascript { .api }
110
/**
111
* Enable or disable accepting ranged requests
112
* @type {boolean}
113
* @default true
114
*/
115
acceptRanges: boolean;
116
```
117
118
### cacheControl
119
120
```javascript { .api }
121
/**
122
* Enable or disable setting Cache-Control response header
123
* @type {boolean}
124
* @default true
125
*/
126
cacheControl: boolean;
127
```
128
129
### dotfiles
130
131
```javascript { .api }
132
/**
133
* Set how "dotfiles" are treated when encountered
134
* @type {string}
135
* @default 'ignore'
136
* @values 'allow' | 'deny' | 'ignore'
137
*/
138
dotfiles: 'allow' | 'deny' | 'ignore';
139
```
140
141
- `'allow'` - No special treatment for dotfiles
142
- `'deny'` - Deny a request for a dotfile and 403/next()
143
- `'ignore'` - Pretend like the dotfile does not exist and 404/next()
144
145
### etag
146
147
```javascript { .api }
148
/**
149
* Enable or disable etag generation
150
* @type {boolean}
151
* @default true
152
*/
153
etag: boolean;
154
```
155
156
### extensions
157
158
```javascript { .api }
159
/**
160
* Set file extension fallbacks for when files are not found
161
* @type {string[] | false}
162
* @default false
163
* @example ['html', 'htm']
164
*/
165
extensions: string[] | false;
166
```
167
168
### fallthrough
169
170
```javascript { .api }
171
/**
172
* Set the middleware to have client errors fall-through as just unhandled requests
173
* @type {boolean}
174
* @default true
175
*/
176
fallthrough: boolean;
177
```
178
179
### immutable
180
181
```javascript { .api }
182
/**
183
* Enable or disable the immutable directive in the Cache-Control response header
184
* @type {boolean}
185
* @default false
186
*/
187
immutable: boolean;
188
```
189
190
### index
191
192
```javascript { .api }
193
/**
194
* Directory index file configuration
195
* @type {string | string[] | false}
196
* @default 'index.html'
197
*/
198
index: string | string[] | false;
199
```
200
201
### lastModified
202
203
```javascript { .api }
204
/**
205
* Enable or disable Last-Modified header
206
* @type {boolean}
207
* @default true
208
*/
209
lastModified: boolean;
210
```
211
212
### maxAge
213
214
```javascript { .api }
215
/**
216
* Provide a max-age in milliseconds for http caching
217
* @type {number | string}
218
* @default 0
219
*/
220
maxAge: number | string;
221
```
222
223
Also accepts string format compatible with the `ms` module (e.g., '1d', '2h', '30m').
224
225
### maxage
226
227
```javascript { .api }
228
/**
229
* Alias for maxAge option
230
* @type {number | string}
231
* @default 0
232
*/
233
maxage: number | string;
234
```
235
236
### redirect
237
238
```javascript { .api }
239
/**
240
* Redirect to trailing "/" when the pathname is a dir
241
* @type {boolean}
242
* @default true
243
*/
244
redirect: boolean;
245
```
246
247
### setHeaders
248
249
```javascript { .api }
250
/**
251
* Function to set custom headers on response
252
* @type {Function}
253
* @param {Object} res - The response object
254
* @param {string} path - The file path that is being sent
255
* @param {Object} stat - The stat object of the file that is being sent
256
*/
257
setHeaders: (res, path, stat) => void;
258
```
259
260
**Usage Example:**
261
262
```javascript
263
const serve = serveStatic('public', {
264
setHeaders: function(res, path, stat) {
265
// Set cache headers based on file type
266
if (path.endsWith('.html')) {
267
res.setHeader('Cache-Control', 'public, max-age=0');
268
}
269
// Add security headers
270
res.setHeader('X-Content-Type-Options', 'nosniff');
271
}
272
});
273
```
274
275
## Types
276
277
```javascript { .api }
278
/**
279
* Configuration options for serve-static middleware
280
*/
281
interface ServeStaticOptions {
282
acceptRanges?: boolean;
283
cacheControl?: boolean;
284
dotfiles?: 'allow' | 'deny' | 'ignore';
285
etag?: boolean;
286
extensions?: string[] | false;
287
fallthrough?: boolean;
288
immutable?: boolean;
289
index?: string | string[] | false;
290
lastModified?: boolean;
291
maxAge?: number | string;
292
maxage?: number | string;
293
redirect?: boolean;
294
setHeaders?: (res: Object, path: string, stat: Object) => void;
295
}
296
```
297
298
## Error Handling
299
300
The middleware handles various error conditions based on configuration:
301
302
- **405 Method Not Allowed**: For non-GET/HEAD requests when `fallthrough` is `false`
303
- **404 Not Found**: For missing files/directories
304
- **Server Errors (≥500)**: Always forwarded to `next(err)`
305
- **Client Errors (<500)**: Handled based on `fallthrough` setting
306
- When `fallthrough` is `true`: calls `next()` to continue to next middleware
307
- When `fallthrough` is `false`: calls `next(err)` to forward the error
308
309
## Integration Patterns
310
311
### Express.js Application
312
313
```javascript
314
const express = require('express');
315
const serveStatic = require('serve-static');
316
317
const app = express();
318
319
// Single directory
320
app.use(serveStatic('public'));
321
322
// Multiple directories with fallback
323
app.use(serveStatic('public-optimized'));
324
app.use(serveStatic('public'));
325
326
// Mount at specific path
327
app.use('/assets', serveStatic('public/assets'));
328
329
app.listen(3000);
330
```
331
332
### Vanilla Node.js HTTP Server
333
334
```javascript
335
const http = require('http');
336
const finalhandler = require('finalhandler');
337
const serveStatic = require('serve-static');
338
339
const serve = serveStatic('public', {
340
index: ['index.html', 'index.htm']
341
});
342
343
const server = http.createServer(function(req, res) {
344
serve(req, res, finalhandler(req, res));
345
});
346
347
server.listen(3000);
348
```
349
350
### Force Download Headers
351
352
```javascript
353
const contentDisposition = require('content-disposition');
354
const serveStatic = require('serve-static');
355
356
const serve = serveStatic('public/downloads', {
357
index: false,
358
setHeaders: function(res, path) {
359
res.setHeader('Content-Disposition', contentDisposition(path));
360
}
361
});
362
```