or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/npm-serve-favicon

Favicon serving middleware with caching

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/serve-favicon@2.5.x

To install, run

npx @tessl/cli install tessl/npm-serve-favicon@2.5.0

index.mddocs/

Serve Favicon

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.

Package Information

  • Package Name: serve-favicon
  • Package Type: npm
  • Language: JavaScript
  • Installation: npm install serve-favicon

Core Imports

const 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.

Basic Usage

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);

Architecture

Serve Favicon is built around a simple, efficient architecture:

  • Middleware Pattern: Returns Express/Connect/Node.js compatible middleware function
  • Memory Caching: Caches favicon data in memory after first read to avoid repeated disk I/O
  • ETag Generation: Creates ETags based on file contents rather than filesystem properties
  • HTTP Method Handling: Properly handles GET, HEAD, and OPTIONS requests with appropriate responses
  • Early Request Filtering: Only processes requests to /favicon.ico path, passing others through immediately

Capabilities

Favicon Middleware Creation

Creates 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 data
  • options (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:

  • Only processes requests to /favicon.ico path, calls next() for all other requests
  • Supports GET, HEAD, and OPTIONS HTTP methods
  • Returns 405 Method Not Allowed for unsupported methods with proper Allow header
  • Returns 200 OK with Allow header for OPTIONS requests
  • Implements memory-based caching to avoid repeated disk I/O operations
  • Generates ETag based on file contents (not filesystem properties)
  • Returns 304 Not Modified for fresh requests based on ETag validation
  • Sets appropriate Cache-Control headers with configured max-age
  • Sets Content-Type to image/x-icon for maximum browser compatibility
  • Handles file reading errors by passing them to the next() callback

Errors:

  • 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)
  • File system errors are passed through for invalid file paths

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);

Middleware Function

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:

  1. Checks if request path is /favicon.ico - if not, calls next() immediately
  2. Validates HTTP method (GET, HEAD, OPTIONS) - returns 405 for unsupported methods
  3. For cached icons, sends response immediately with ETag validation
  4. For uncached icons, reads file asynchronously, caches result, then sends response
  5. Handles 304 Not Modified responses based on ETag freshness checking

Types

interface 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;

Dependencies

The package relies on these runtime dependencies:

  • etag: ~1.8.1 - ETag generation based on file contents
  • fresh: ~0.5.2 - HTTP freshness checking for conditional requests
  • ms: ~2.1.3 - Millisecond string parsing for maxAge values
  • parseurl: ~1.3.2 - URL parsing for request pathname extraction
  • safe-buffer: ~5.2.1 - Safe Buffer implementation for Node.js compatibility

Framework Compatibility

Serve Favicon is framework-agnostic and works with:

  • Express.js: Use as standard middleware with app.use(favicon(...))
  • Connect: Use as Connect middleware with app.use(favicon(...))
  • Vanilla Node.js HTTP: Call returned function directly with req, res, next parameters
  • Other frameworks: Any framework that supports Node.js middleware pattern

Performance Features

  • Memory Caching: Favicon data is cached in memory after first read, eliminating repeated disk I/O
  • ETag-based Validation: Uses content-based ETags rather than filesystem properties for reliable caching
  • Early Request Filtering: Only processes /favicon.ico requests, avoiding unnecessary processing
  • Proper HTTP Headers: Sets appropriate Cache-Control, Content-Type, and Content-Length headers
  • 304 Not Modified: Efficiently handles conditional requests with proper freshness validation

Best Practices

  • Place favicon middleware early in your middleware stack to avoid processing other middleware for favicon requests
  • Use file paths rather than Buffers when possible to take advantage of lazy loading
  • Configure appropriate maxAge values based on your deployment frequency
  • Ensure favicon file exists and is readable before starting your application
  • Consider using this middleware before logging middleware to avoid cluttering logs with favicon requests