Favicon serving middleware with caching
npx @tessl/cli install tessl/npm-serve-favicon@2.5.00
# Serve Favicon
1
2
Serve Favicon is a Node.js middleware for efficiently serving favicon.ico files with advanced caching capabilities and performance optimizations. It handles the ubiquitous favicon requests that browsers make automatically, offering memory-based caching to avoid repeated disk I/O operations, ETag-based cache validation, and proper Content-Type headers for maximum browser compatibility.
3
4
## Package Information
5
6
- **Package Name**: serve-favicon
7
- **Package Type**: npm
8
- **Language**: JavaScript
9
- **Installation**: `npm install serve-favicon`
10
11
## Core Imports
12
13
```javascript
14
const favicon = require('serve-favicon');
15
```
16
17
For ES modules (using import):
18
19
```javascript
20
import favicon from 'serve-favicon';
21
```
22
23
Note: This package exports using CommonJS format. When using ES modules, the import syntax above will work with Node.js ES module interoperability.
24
25
## Basic Usage
26
27
```javascript
28
const express = require('express');
29
const favicon = require('serve-favicon');
30
const path = require('path');
31
32
const app = express();
33
34
// Serve favicon from file path
35
app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
36
37
// With custom options
38
app.use(favicon(path.join(__dirname, 'public', 'favicon.ico'), {
39
maxAge: '30d' // Cache for 30 days
40
}));
41
42
app.listen(3000);
43
```
44
45
## Architecture
46
47
Serve Favicon is built around a simple, efficient architecture:
48
49
- **Middleware Pattern**: Returns Express/Connect/Node.js compatible middleware function
50
- **Memory Caching**: Caches favicon data in memory after first read to avoid repeated disk I/O
51
- **ETag Generation**: Creates ETags based on file contents rather than filesystem properties
52
- **HTTP Method Handling**: Properly handles GET, HEAD, and OPTIONS requests with appropriate responses
53
- **Early Request Filtering**: Only processes requests to `/favicon.ico` path, passing others through immediately
54
55
## Capabilities
56
57
### Favicon Middleware Creation
58
59
Creates middleware to serve a favicon from a file path or Buffer with configurable caching options.
60
61
```javascript { .api }
62
/**
63
* Creates middleware to serve a favicon from the given path or Buffer
64
* @param {string|Buffer} path - Path to favicon file or Buffer containing favicon data
65
* @param {object} [options] - Configuration options
66
* @param {string|number} [options.maxAge] - Cache-Control max-age directive (default: 1 year)
67
* @returns {Function} Express/Connect/Node.js compatible middleware function
68
*/
69
function favicon(path, options);
70
```
71
72
**Parameters:**
73
- `path` (string|Buffer, required): Path to favicon file or Buffer containing favicon data
74
- `options` (object, optional): Configuration options
75
- `maxAge` (string|number, optional): Cache-Control max-age directive in milliseconds or ms-compatible string (e.g., '30d', '1y'). Defaults to 1 year (31536000000ms). Accepts values from 0 to 1 year maximum.
76
77
**Returns:** Function - Middleware function with signature `(req, res, next) => void`
78
79
**Behavior:**
80
- Only processes requests to `/favicon.ico` path, calls `next()` for all other requests
81
- Supports GET, HEAD, and OPTIONS HTTP methods
82
- Returns 405 Method Not Allowed for unsupported methods with proper Allow header
83
- Returns 200 OK with Allow header for OPTIONS requests
84
- Implements memory-based caching to avoid repeated disk I/O operations
85
- Generates ETag based on file contents (not filesystem properties)
86
- Returns 304 Not Modified for fresh requests based on ETag validation
87
- Sets appropriate Cache-Control headers with configured max-age
88
- Sets Content-Type to `image/x-icon` for maximum browser compatibility
89
- Handles file reading errors by passing them to the next() callback
90
91
**Errors:**
92
- `TypeError`: When path is not provided ("path to favicon.ico is required")
93
- `TypeError`: When path is not a string or Buffer ("path to favicon.ico must be string or buffer")
94
- `Error`: When path points to a directory (EISDIR error with code 'EISDIR', errno 28)
95
- File system errors are passed through for invalid file paths
96
97
**Usage Examples:**
98
99
```javascript
100
const express = require('express');
101
const favicon = require('serve-favicon');
102
const path = require('path');
103
104
const app = express();
105
106
// Basic file path usage
107
app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
108
109
// With Buffer data
110
const fs = require('fs');
111
const iconBuffer = fs.readFileSync('./favicon.ico');
112
app.use(favicon(iconBuffer));
113
114
// With custom cache duration
115
app.use(favicon('./favicon.ico', { maxAge: '30d' }));
116
117
// No caching
118
app.use(favicon('./favicon.ico', { maxAge: 0 }));
119
120
// Connect usage
121
const connect = require('connect');
122
const app = connect();
123
app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
124
125
// Vanilla HTTP server usage
126
const http = require('http');
127
const finalhandler = require('finalhandler');
128
129
const _favicon = favicon(path.join(__dirname, 'public', 'favicon.ico'));
130
131
const server = http.createServer(function(req, res) {
132
const done = finalhandler(req, res);
133
134
_favicon(req, res, function(err) {
135
if (err) return done(err);
136
137
// Continue processing other requests
138
res.statusCode = 404;
139
res.end('Not Found');
140
});
141
});
142
143
server.listen(3000);
144
```
145
146
### Middleware Function
147
148
The returned middleware function that handles favicon requests.
149
150
```javascript { .api }
151
/**
152
* Middleware function that handles favicon.ico requests
153
* @param {IncomingMessage} req - HTTP request object
154
* @param {ServerResponse} res - HTTP response object
155
* @param {Function} next - Next middleware function in stack
156
*/
157
function middlewareFunction(req, res, next);
158
```
159
160
**Request Processing:**
161
1. Checks if request path is `/favicon.ico` - if not, calls `next()` immediately
162
2. Validates HTTP method (GET, HEAD, OPTIONS) - returns 405 for unsupported methods
163
3. For cached icons, sends response immediately with ETag validation
164
4. For uncached icons, reads file asynchronously, caches result, then sends response
165
5. Handles 304 Not Modified responses based on ETag freshness checking
166
167
## Types
168
169
```javascript { .api }
170
interface FaviconOptions {
171
/** Cache-Control max-age directive in milliseconds or ms-compatible string */
172
maxAge?: string | number;
173
}
174
175
interface MiddlewareFunction {
176
(req: IncomingMessage, res: ServerResponse, next: NextFunction): void;
177
}
178
179
// Node.js HTTP types
180
interface IncomingMessage {
181
method?: string;
182
url?: string;
183
headers: { [key: string]: string | string[] | undefined };
184
}
185
186
interface ServerResponse {
187
statusCode: number;
188
setHeader(name: string, value: string | number | string[]): this;
189
getHeader(name: string): string | number | string[] | undefined;
190
end(chunk?: any): void;
191
}
192
193
type NextFunction = (err?: any) => void;
194
```
195
196
## Dependencies
197
198
The package relies on these runtime dependencies:
199
200
- `etag`: ~1.8.1 - ETag generation based on file contents
201
- `fresh`: ~0.5.2 - HTTP freshness checking for conditional requests
202
- `ms`: ~2.1.3 - Millisecond string parsing for maxAge values
203
- `parseurl`: ~1.3.2 - URL parsing for request pathname extraction
204
- `safe-buffer`: ~5.2.1 - Safe Buffer implementation for Node.js compatibility
205
206
## Framework Compatibility
207
208
Serve Favicon is framework-agnostic and works with:
209
210
- **Express.js**: Use as standard middleware with `app.use(favicon(...))`
211
- **Connect**: Use as Connect middleware with `app.use(favicon(...))`
212
- **Vanilla Node.js HTTP**: Call returned function directly with `req`, `res`, `next` parameters
213
- **Other frameworks**: Any framework that supports Node.js middleware pattern
214
215
## Performance Features
216
217
- **Memory Caching**: Favicon data is cached in memory after first read, eliminating repeated disk I/O
218
- **ETag-based Validation**: Uses content-based ETags rather than filesystem properties for reliable caching
219
- **Early Request Filtering**: Only processes `/favicon.ico` requests, avoiding unnecessary processing
220
- **Proper HTTP Headers**: Sets appropriate Cache-Control, Content-Type, and Content-Length headers
221
- **304 Not Modified**: Efficiently handles conditional requests with proper freshness validation
222
223
## Best Practices
224
225
- Place favicon middleware early in your middleware stack to avoid processing other middleware for favicon requests
226
- Use file paths rather than Buffers when possible to take advantage of lazy loading
227
- Configure appropriate maxAge values based on your deployment frequency
228
- Ensure favicon file exists and is readable before starting your application
229
- Consider using this middleware before logging middleware to avoid cluttering logs with favicon requests