Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to Change Favicon with Express.js

I tried visiting the site in Safari for the first time (I normally use Chrome) and noticed that it was showing the correct favicon. I tried clearing my cache in Chrome again (twice) to no avail, but after more searching, I found that apparently favicons aren't stored in the cache. I "refreshed my favicon" using the method described here and it worked!

Here's the method (modified from the above link), in case the link goes dead:

  1. Open Chrome/the problematic browser
  2. Navigate to the favicon.ico file directly, e.g. http://localhost:3000/favicon.ico
  3. Refresh the favicon.ico URL by pressing F5 or the appropriate browser Refresh (Reload) button
  4. Close the browser and open your website - voila, your favicon has been updated!

What worked for me finally:

Look that the

app.use(express.favicon(__dirname + '/public/images/favicon.ico')); 

is at the beginning of the app configuration function. I had it before at the end. As the Express doc says: 'The order of which middleware are "defined" using app.use() is very important, they are invoked sequentially, thus this defines middleware precedence.'

I didn't need to set any maxAge.

To test it:

  • Restart the server with node app.js
  • Clear the browser cache
  • Refresh the Favicon with directly accessing it by using "localhost:3000/your_path_to_the favicon/favicon.ico" and reloading

The above answer is no longer valid.

If you use

app.use(express.favicon(__dirname + '/public/images/favicon.ico'));

You'll get this error:

Error: Most middleware (like favicon) is no longer bundled with Express and must be installed separately

What you're going to need to do is get serve-favicon.

run

npm install serve-favicon --save

then add this to your app

var express = require('express');
var favicon = require('serve-favicon');
var app = express();

app.use(favicon(__dirname + '/public/images/favicon.ico'));

What worked for me follows. Set express to serve your static resources as usual, for example

app.use(express.static('public'));

Put favicon inside your public folder; Then add a query string to you icon url, for example

<link rel="icon" type="image/x-icon" href="favicon.ico?v="+ Math.trunc(Math.random()*999)>

In this case, Chrome is the misbehaving Browser; IE. Firefox. Safari (all on Windows) worked fine, WITHOUT the above trick.


Simplest way I could come up with (valid only for local dev, of course) was to host the server on a different port

PORT=3001 npm run start


Have you tried clearing your browser's cache? Maybe the old favicon is still in the cache.