Koa Favicon Middleware

2.1.0 · active · verified Wed Apr 22

This middleware for Koa applications efficiently serves a `favicon.ico` file, handling requests for `/favicon.ico` and setting appropriate cache headers. Built upon the proven `serve-favicon` package, it provides a straightforward way to integrate favicon serving directly into the Koa middleware stack. The current stable version is 2.1.0, a mature release from the Koa organization. Its release cadence is generally slow, primarily responding to Koa framework updates or critical maintenance. It differentiates itself by its minimalistic API and direct compatibility with Koa's `app.use()` pattern, making it a standard choice for basic favicon serving in Koa projects. It supports custom `maxAge` caching and MIME type specification.

Common errors

Warnings

Install

Imports

Quickstart

This example demonstrates setting up a basic Koa application to serve a favicon from a specified path with a 7-day cache, showcasing typical usage with ES Modules.

import Koa from 'koa';
import favicon from 'koa-favicon';
import path from 'node:path';
import { fileURLToPath } from 'node:url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

const app = new Koa();
const port = 3000;

// Ensure you have a 'favicon.ico' file in a 'public' directory next to your app entry file.
// For example: my-app/public/favicon.ico
app.use(favicon(path.join(__dirname, 'public', 'favicon.ico'), {
  maxAge: 1000 * 60 * 60 * 24 * 7 // Cache for 7 days
}));

app.use(async (ctx) => {
  ctx.body = 'Hello, Koa favicon example!';
});

app.listen(port, () => {
  console.log(`Koa application listening on http://localhost:${port}`);
  console.log('Try accessing http://localhost:3000/favicon.ico directly in your browser or developer tools.');
});

view raw JSON →