164

I recently started working in Node.js and in the app.js file there is this line:

app.use(express.favicon());

Now, how do I set up my own custom favicon.ico?

Michał Perłakowski
  • 88,409
  • 26
  • 156
  • 177
Ilya Karnaukhov
  • 3,838
  • 7
  • 31
  • 53
  • 5
    Make sure to properly clear the browser's cache, else you might not see it changing – vsync May 08 '13 at 08:42
  • Using `app.use(express.favicon())` on Express 4 gives: **Most middleware (like favicon) is no longer bundled with Express and must be installed separately. Please see github.com/senchalabs/connect#middleware**. Alternatively, you can supply no favicon with: `app.get('/favicon.ico', (req, res) => res.status(200))` [Express js prevent GET /favicon.ico](https://stackoverflow.com/questions/35408729/express-js-prevent-get-favicon-ico) – Evandro Coan Apr 18 '20 at 21:12
  • You don't need any middlewares, just a line of code check this answer : [Stack Overflow](https://stackoverflow.com/a/31459493/8342999) – 27px Dec 26 '20 at 03:29

15 Answers15

275

In Express 4

Install the favicon middleware and then do:

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

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

Or better, using the path module:

app.use(favicon(path.join(__dirname,'public','images','favicon.ico')));

(note that this solution will work in express 3 apps as well)

In Express 3

According to the API, .favicon accepts a location parameter:

app.use(express.favicon("public/images/favicon.ico")); 

Most of the time, you might want this (as vsync suggested):

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

Or better yet, use the path module (as Druska suggested):

app.use(express.favicon(path.join(__dirname, 'public','images','favicon.ico'))); 

Why favicon is better than static

According to the package description:

  1. This module caches the icon in memory to improve performance by skipping disk access.
  2. This module provides an ETag based on the contents of the icon, rather than file system properties.
  3. This module will serve with the most compatible Content-Type.
Community
  • 1
  • 1
Benjamin Gruenbaum
  • 270,886
  • 87
  • 504
  • 504
  • 1
    Thanks! Would you mind [opening an issue](https://github.com/nodejs/node/issues/new) so I can take a look there? Hopefully just the path stuff and namely that `path.join(__dirname, "public")` results in the strings concatenated without a separator? The smaller the sample the quicker we can fix this (so if you can please just the join part). – Benjamin Gruenbaum Aug 01 '16 at 12:56
  • What's the benefit to use yet another middleware (maintained by someone who might not actually maintain it in the future) instead of the more semplicistic way [explained by Eduardo](https://stackoverflow.com/a/31459493/1412157) ? – LucaM Sep 28 '18 at 11:04
  • 4
    @LucaM first of all - good question! serve-favicon is maintained by us (the Node.js foundation) and Doug (who maintains express) - that is, it is by the same people who write and maintain express itself. You can see the [readme](https://github.com/expressjs/serve-favicon#readme) for why, but basically: logging, caching, ETag handling and correct `Content-Type`. You can see what it does [here](https://github.com/expressjs/serve-favicon/blob/master/index.js). Do you think there is merit in editing this into the answer? – Benjamin Gruenbaum Sep 28 '18 at 16:19
  • 1
    Thank you Benjamin for clearing out the features _favicon_ provide. I would write that in the accepted answer although not strictly needed. – LucaM Oct 01 '18 at 07:41
74

No extra middlewares required. Just use:

app.use('/favicon.ico', express.static('images/favicon.ico'));
Eduardo
  • 5,645
  • 4
  • 49
  • 57
  • 3
    Yep, this should suffice and it's the correct answer because an additional middleware for this feels like overkill. – jlstr Jan 27 '19 at 02:08
  • 1
    @jlstr it is like 20 lines of code, what kind of _overkill_ do you mean)) And it is a server side, sot the number of small dependencies doesn't matter. And the [mentioned middleware provides](https://expressjs.com/en/resources/middleware/serve-favicon.html): 1) memory caching 2) set proper ETag 3) set proper `Content-Type` – maxkoryukov Aug 29 '19 at 21:47
  • I already have `app.use(express.static("dist"));` which serves all js, img and css files referenced like `/img/some_image.png` or `/js/my_file.js` from the `dist` folder, and `` in the `` but still getting 404 failure in a Node/MongoDB app on Azure, the failed request is `GET /favicon.ico`. Is this the solution: `app.use(express.static("dist"));` followed by `app.use('/favicon.ico', express.static('/img/favicon.ico'));`? Edit: I tried this in local environment, and `http://localhost:3000/favicon.ico` returns `Cannot GET /favicon.ico`. – user1063287 Sep 20 '20 at 03:23
  • Answer to my comment question, this seemed to work for me: `app.use('/favicon.ico', express.static('dist/img/favicon.ico'));`, *above* my existing `app.use(express.static("dist"));`. – user1063287 Sep 20 '20 at 03:51
  • be careful you should use the >require('serve-favicon')< module because it generates cache it prevents reading the file from storage – Daniel Aug 14 '22 at 05:30
  • I think cache should be handled by a CDN – Eduardo Aug 14 '22 at 12:51
31

No need for custom middleware?! In express:

 //you probably have something like this already    
app.use("/public", express.static('public')); 

Then put your favicon in public and add the following line in your html's head:

<link rel="icon" href="/public/favicon.ico">
DaafVader
  • 1,735
  • 1
  • 14
  • 14
  • 4
    That's DaafVader. This worked. My setting was: app.use(express.static('public')). I saved my favicon in folder img thats inside public folder. In my html file in head section, I used where favicon.ico was my filename of my favicon. – Nhon Ha Nov 26 '19 at 12:13
  • For me I had to use ```../public/favicon.ico``` as I was in a directory of a template engine. – Oliver Dixon Jul 28 '21 at 08:07
18

smiley favicon to prevent error:

 //const fs = require('fs'); 
 //const favicon = fs.readFileSync(__dirname+'/public/favicon.ico'); // read file
 const favicon = new Buffer.from('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 (https://inkscape.org/) 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 favicon a high quality icons for link for the website.

then maybe enhance the image in photoshop. like vibrance, bevel effect, round mask, anything.

then upload this image to one of the websites that generate favicons. there are also programs for windows for editing icons like https://sourceforge.net/projects/variicons/ .

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

Shimon Doodkin
  • 4,310
  • 34
  • 37
  • 1
    Like this approach the best. I just used a file to serve instead of base64: fs.createReadStream("./public/favicon.ico").pipe(res); – DaafVader Mar 15 '17 at 12:30
  • 2
    Why not just use express.favicon since your already using express?? Why create an entire route if you can just as well use a static folder? Besides that, that magic string (your smiley) is not making your case any better. – SubliemeSiem Sep 03 '17 at 10:21
  • 1
    You don't need any code to put favicon. Just put it as file in static files directory. – Shimon Doodkin Sep 04 '17 at 11:16
8
app.use(express.favicon(__dirname + '/public/images/favicon.ico')); 

I had it working locally without the __dirname + but couldn't get it working on my deployed server.

rene
  • 41,474
  • 78
  • 114
  • 152
ThomasReggi
  • 55,053
  • 85
  • 237
  • 424
4

If you are using Express > 4.0, you could go for serve-favicon

Anastasios Andronidis
  • 6,310
  • 4
  • 30
  • 53
3

If you have you static path set, then just use the <link rel="icon" href="/images/favicon.ico" type="image/x-icon"> in your views. No need for anything else. Please make sure that you have your images folder inside the public folder.

Mohsin Khan
  • 156
  • 1
  • 1
  • 5
  • 2
    Just make sure you are using `127.0.0.1` instead of `localhost` in Google Chrome while you develop, for some reason that fixed it for me. – cprcrack Jun 15 '18 at 09:45
2

In app.js:

app.use(express.static(path.join(__dirname, 'public')));

Assuming the icon resides in "/public/images/favicon.ico" add next link in html's head:

<link rel='icon' href='/images/favicon.ico' class='js-favicon'>

This worked fine in a project auto-generated with the command:

express my-project
Nikolas H
  • 41
  • 4
2

If you want a solution that does not involve external files, and does not use express.static (for example, a super-light one file webserver and site) you can use serve-favicon and encode your favicon.ico file as Base64. Like this:

const favicon = require('serve-favicon');
const imgBuffer = new Buffer.from('IMAGE_AS_BASE64_STRING_GOES_HERE', 'base64');
// assuming app is already defined
app.use(favicon(imgBuffer));

Replace IMAGE_AS_BASE64_STRING_GOES_HERE with the result of encoding your favicon file as Base64. There are lots of sites that can do that online, have a search.

Note you may need to restart the server and/or browser to see it working on localhost, and a hard refresh/clear browser cache to see it working on the web.

jpw
  • 343
  • 2
  • 9
2

If neither of the above work , you can try out this !
Make sure that your favicon.ico file is in public/icons or change accordingly.
If path is not imported ,

const path = require('path') ; 

then ,

app.get("/favicon.ico", (req, res) => {
  return res.sendFile(path.join(__dirname + "/public/icons/favicon.ico"));
});
Abk
  • 74
  • 3
1

Install express-favicon middleware:

npm install express-favicon --save

Use it like this:

const favicon = require('express-favicon');
app.use(favicon(__dirname + 'favicon.ico'));
elig
  • 2,635
  • 3
  • 14
  • 24
1

You must install middleware to serve the favicon.

I tried this just now:

app.use(express.favicon(path.join(__dirname, 'public','images','favicon.ico'))); 

and got this error message back:

Error: Most middleware (like favicon) is no longer bundled with Express and must be installed separately. Please see https://github.com/senchalabs/connect#middleware.

I think we can take that as being definitive.

amunnelly
  • 1,144
  • 13
  • 22
0

The code listed below works:

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

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

Just make sure to refresh your browser or clear your cache.

Community
  • 1
  • 1
blakeface
  • 131
  • 2
  • 7
0

step 0: add below code to app.js or index.js

app.use("/favicon.ico", express.static('public/favicon.ico'));

step 1: download icon from here https://icons8.com/ or create your own
step 2: go to https://www.favicongenerator.com/
step 3: upload the downloaded icon.png file > set 16px > create favicon > download
step 4: go to downloads folder, you'll find [.ico file], rename it as favicon.ico
step 5: copy favicon.ico in public directory you created
step 6: add below code to your .pug file under head tag, below title tag

<link rel="shortcut icon" type="image/x-icon" href="/favicon.ico">

step 7: save > restart server > close browser > reopen browser > favicon appears

NOTE: you can use name other than favicon,
            but make sure you change the name in code and in the public folder.

Mehran Ahemad
  • 61
  • 1
  • 3
0

If you are using Express.static to serve a folder, just put the favicon.ico file in the root of that folder and it will be served when the browser requests it. There's no need to add a link tag to your html or a special middleware route in the application code.

If you're behind a reverse proxy, you may need to specify the media/mime type for the file (here's how in IIS) but if you navigate directly to your app it "just works".

user1944491
  • 559
  • 1
  • 8
  • 24