Favicon serving middleware with caching
npx @tessl/cli install tessl/npm-serve-favicon@2.5.0Serve 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.
npm install serve-faviconconst favicon = require('serve-favicon');For ES modules (using import):
import favicon from 'serve-favicon';Note: This package exports using CommonJS format. When using ES modules, the import syntax above will work with Node.js ES module interoperability.
const express = require('express');
const favicon = require('serve-favicon');
const path = require('path');
const app = express();
// Serve favicon from file path
app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
// With custom options
app.use(favicon(path.join(__dirname, 'public', 'favicon.ico'), {
maxAge: '30d' // Cache for 30 days
}));
app.listen(3000);Serve Favicon is built around a simple, efficient architecture:
/favicon.ico path, passing others through immediatelyCreates middleware to serve a favicon from a file path or Buffer with configurable caching options.
/**
* Creates middleware to serve a favicon from the given path or Buffer
* @param {string|Buffer} path - Path to favicon file or Buffer containing favicon data
* @param {object} [options] - Configuration options
* @param {string|number} [options.maxAge] - Cache-Control max-age directive (default: 1 year)
* @returns {Function} Express/Connect/Node.js compatible middleware function
*/
function favicon(path, options);Parameters:
path (string|Buffer, required): Path to favicon file or Buffer containing favicon dataoptions (object, optional): Configuration options
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.Returns: Function - Middleware function with signature (req, res, next) => void
Behavior:
/favicon.ico path, calls next() for all other requestsimage/x-icon for maximum browser compatibilityErrors:
TypeError: When path is not provided ("path to favicon.ico is required")TypeError: When path is not a string or Buffer ("path to favicon.ico must be string or buffer")Error: When path points to a directory (EISDIR error with code 'EISDIR', errno 28)Usage Examples:
const express = require('express');
const favicon = require('serve-favicon');
const path = require('path');
const app = express();
// Basic file path usage
app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
// With Buffer data
const fs = require('fs');
const iconBuffer = fs.readFileSync('./favicon.ico');
app.use(favicon(iconBuffer));
// With custom cache duration
app.use(favicon('./favicon.ico', { maxAge: '30d' }));
// No caching
app.use(favicon('./favicon.ico', { maxAge: 0 }));
// Connect usage
const connect = require('connect');
const app = connect();
app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
// Vanilla HTTP server usage
const http = require('http');
const finalhandler = require('finalhandler');
const _favicon = favicon(path.join(__dirname, 'public', 'favicon.ico'));
const server = http.createServer(function(req, res) {
const done = finalhandler(req, res);
_favicon(req, res, function(err) {
if (err) return done(err);
// Continue processing other requests
res.statusCode = 404;
res.end('Not Found');
});
});
server.listen(3000);The returned middleware function that handles favicon requests.
/**
* Middleware function that handles favicon.ico requests
* @param {IncomingMessage} req - HTTP request object
* @param {ServerResponse} res - HTTP response object
* @param {Function} next - Next middleware function in stack
*/
function middlewareFunction(req, res, next);Request Processing:
/favicon.ico - if not, calls next() immediatelyinterface FaviconOptions {
/** Cache-Control max-age directive in milliseconds or ms-compatible string */
maxAge?: string | number;
}
interface MiddlewareFunction {
(req: IncomingMessage, res: ServerResponse, next: NextFunction): void;
}
// Node.js HTTP types
interface IncomingMessage {
method?: string;
url?: string;
headers: { [key: string]: string | string[] | undefined };
}
interface ServerResponse {
statusCode: number;
setHeader(name: string, value: string | number | string[]): this;
getHeader(name: string): string | number | string[] | undefined;
end(chunk?: any): void;
}
type NextFunction = (err?: any) => void;The package relies on these runtime dependencies:
etag: ~1.8.1 - ETag generation based on file contentsfresh: ~0.5.2 - HTTP freshness checking for conditional requestsms: ~2.1.3 - Millisecond string parsing for maxAge valuesparseurl: ~1.3.2 - URL parsing for request pathname extractionsafe-buffer: ~5.2.1 - Safe Buffer implementation for Node.js compatibilityServe Favicon is framework-agnostic and works with:
app.use(favicon(...))app.use(favicon(...))req, res, next parameters/favicon.ico requests, avoiding unnecessary processing