Deno nuggets: Oak middleware to serve favicon.ico

Mayank C
Tech Tonic

--

This article is a part of the Deno nuggets series, where each article attempts to suggest a pointed solution to a specific question that can be read in less than a minute. There is no ordering of nuggets.

Problem

How to serve favicon.ico file through Oak?

Modern browsers will show an icon to the left of the URL. This known as the ‘favicon.ico’ and is typically fetched from website.com/favicon.ico. Your browser will automatically request it when browsing to different sites. If your browser receives a valid favicon.ico file, it will display this icon. If it fails, it will not display a special icon.

Solution

Favicons are very popular as they add life to the website title. Usually favicons are the website/company’s logos.

The favicon can be served by adding an extra route. However, a better way is to serve it through an optimized middleware that would cache the ICO file. Here is the code of an Oak middleware that takes care of caching and serving favicon.ico file. The ICO file is loaded into cache using fetch file API.

The application can be executed using the following command:

> deno run --no-prompt --allow-net=:8000 --allow-read=/var/tmp app.ts

Once opened in the browser, we’ll see the coffee.ico next to the website title:

--

--