Serve Favicon Middleware

2.5.1 · active · verified Wed Apr 22

serve-favicon is a Node.js middleware designed for efficiently serving the `favicon.ico` file in web applications, primarily within the Express.js and Connect.js ecosystems. Currently at version 2.5.1, this package is actively maintained, receiving updates primarily for dependency management and CI improvements, rather than frequent feature additions. Its core purpose is to optimize favicon delivery by caching the icon in memory, generating robust ETags based on file content, and correctly setting the `Content-Type` header. A key differentiator is its specific focus on the default `/favicon.ico` path, ensuring that these high-frequency requests are handled quickly and bypass subsequent middleware in the stack, thereby improving overall application performance by reducing unnecessary processing for static assets.

Common errors

Warnings

Install

Imports

Quickstart

This example sets up a basic Express server, uses `serve-favicon` to serve a favicon from a 'public' directory, and includes logic to create a dummy favicon file if one doesn't exist, making the example runnable out-of-the-box.

const express = require('express');
const favicon = require('serve-favicon');
const path = require('path');
const fs = require('fs');

const app = express();
const publicDir = path.join(__dirname, 'public');
const faviconPath = path.join(publicDir, 'favicon.ico');

// Ensure the 'public' directory exists
if (!fs.existsSync(publicDir)) {
  fs.mkdirSync(publicDir);
}

// Create a dummy favicon.ico if it doesn't exist for the example to run
if (!fs.existsSync(faviconPath)) {
  // A minimal, valid ICO file (1x1 transparent pixel)
  const dummyFavicon = Buffer.from('0000010001001010000001000400000028000000010000000100000001000400000000001600000000000000000000000000000000000000', 'hex');
  fs.writeFileSync(faviconPath, dummyFavicon);
}

// Use serve-favicon middleware
// It should be placed early in your middleware stack
app.use(favicon(faviconPath, { maxAge: '30d' }));

app.get('/', (req, res) => {
  res.send('Hello from your Express app with a favicon!');
});

app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});

view raw JSON →