Unable to Change Favicon with Express.js
Asked Answered
J

8

58

This is a really basic question, but I'm trying to change the favicon of my node.js/Express app with

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

and I'm still getting the default favicon. This is in my app.configure function, and yes, I've verified that there is a favicon.ico in the /public/images/favicon.ico.There's nothing about a favicon.ico in the console, either, which leads me to believe that this line of code is being ignored. Everything else in the function (setting port, setting views directory, setting template engine. etc.) seems to be working fine, so why would this line of code not be executing?

What I tried

  • Emptying browser cache
  • Restarting Terminal and running node app.js again
  • Adding { maxAge: 2592000000 }, as described here

Thanks in advance.

Update: I got it to work. See my answer below for more information.

Janus answered 25/7, 2012 at 20:25 Comment(0)
J
89

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!
Janus answered 25/7, 2012 at 21:48 Comment(6)
I cannot believe this is not in the documentation for module serve-favicon. Seems pretty darn important, especially given that this answer has 41 upvotes. Thank you for linking to these resources!Dropsical
+1 for this. Works like a Charm! Been hustling an entire week. Whatever form of browser cache clearance would not work.Cavalry
The "method described here" link is dead for me.. how about describing the method itself? I added an answer as to what worked for me below.Kaleena
@Kaleena Link still works on my end. However, I updated the answer with the method itself.Janus
Closing the browser can be heavy handed. First try opening an Incognito window to your server, then refreshing the original window.Merriweather
Since the answer included the closing of the browser I literally copied the answer's link to upvote it later.Karleen
I
35

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
Inductor answered 6/1, 2013 at 6:24 Comment(4)
With a brand new app without any modifications use this: app.use(express.favicon('public/images/favicon.ico'));Davison
If you are starting from a template, make sure you replace any previous instances of app.use(express.favicon());. I found when it was duplicated it didn't work properly.Jew
express.favicon is not used anymore with express 4, see error Error: Most middleware (like favicon) is no longer bundled with Express and must be installed separately. You need github.com/expressjs/serve-faviconKishakishinev
Your answer was out-of-date. It should be done actually. The right explanation can be found here. https://mcmap.net/q/143545/-how-to-set-custom-favicon-in-expressDemetricedemetris
G
19

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'));
Gasbag answered 20/10, 2014 at 12:51 Comment(1)
This should be the accepted answer! "--save" means to include dependencies, see here: #19579296Kishakishinev
J
2

smiley favicon to prevent error:

 var favicon = new Buffer('AAABAAEAEBAQAAAAAAAoAQAAFgAAACgAAAAQAAAAIAAAAAEABAAAAAAAgAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAA/4QAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEREQAAAAAAEAAAEAAAAAEAAAABAAAAEAAAAAAQAAAQAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAEAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//wAA//8AAP//AAD8HwAA++8AAPf3AADv+wAA7/sAAP//AAD//wAA+98AAP//AAD//wAA//8AAP//AAD//wAA', 'base64'); 
 app.get("/favicon.ico", function(req, res) {
  res.statusCode = 200;
  res.setHeader('Content-Length', favicon.length);
  res.setHeader('Content-Type', 'image/x-icon');
  res.setHeader("Cache-Control", "public, max-age=2592000");                // expiers after a month
  res.setHeader("Expires", new Date(Date.now() + 2592000000).toUTCString());
  res.end(favicon);
 });

to change icon in code above

make an icon maybe here: http://www.favicon.cc/ or here :http://favicon-generator.org

convert it to base64 maybe here: http://base64converter.com/

then replace the icon base 64 value

general information how to create a personalized fav icon

icons are made using photoshop or inkscape, maybe inkscape then photoshop for vibrance and color correction (in image->adjustments menu).

for quick icon goto http://www.clker.com/ and pick some Vector Clip Arts, and download as svg. then bring it to inkscape and change colors or delete parts, maybe add something from another vector clipart image, then to export select the parts to export and click file>export, pick size like 16x16 for favicon or 32x32, for further edit 128x128 or 256x256. ico package can have several icon sizes inside. it can have along with 16x16 pixel fav icon a high quality icons for link for the website.

then maybe enhance the imaage in photoshop. like vibrance bivel round mask , anything.

then upload this image to one of the websites that generate favicons. there are also programs for windows for editing icons(search like "windows icon editor opensource", figure our how to create two images of different size inside a single icon).

to add the favicon to website. just put the favicon.ico as a file in your root domain files folder. for example in nodejs in public folder that contans the static files. it doesn't have to be anything special like code above just a simple file.

Jedidiah answered 5/9, 2015 at 22:12 Comment(0)
K
2

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.

Kaleena answered 18/1, 2017 at 0:59 Comment(0)
E
2

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

Erlindaerline answered 13/7, 2018 at 20:39 Comment(0)
H
1

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

Hutchison answered 25/7, 2012 at 20:42 Comment(0)
S
0

How to do this without express:

if (req.method == "GET") {
     if (/favicon\.ico/.test(req.url)) {
        fs.readFile("home/usr/path/favicon.ico", function(err, data) {
            if (err) {
                console.log(err);
            } else {
                res.setHeader("Content-Type","image/x-icon");
                res.end(data);
            }
     });
}
Salientian answered 16/7, 2014 at 15:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.