How to set custom favicon in Express?
Asked Answered
G

15

168

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?

Griego answered 17/3, 2013 at 16:29 Comment(3)
Make sure to properly clear the browser's cache, else you might not see it changingApprehensive
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.icoOutbreak
You don't need any middlewares, just a line of code check this answer : Stack OverflowHaddix
C
76

No extra middlewares required. Just use:

app.use('/favicon.ico', express.static('images/favicon.ico'));
Corallite answered 16/7, 2015 at 16:16 Comment(6)
Yep, this should suffice and it's the correct answer because an additional middleware for this feels like overkill.Johny
@Johny 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: 1) memory caching 2) set proper ETag 3) set proper Content-TypeTithable
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 <link rel="shortcut icon" href="/img/favicon.ico"> in the <head> 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.Housemother
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"));.Housemother
be careful you should use the >require('serve-favicon')< module because it generates cache it prevents reading the file from storageMordant
I think cache should be handled by a CDNCorallite
P
278

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.
Peary answered 17/3, 2013 at 16:32 Comment(4)
Thanks! Would you mind opening an issue 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).Peary
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 ?Lindell
@Lindell 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 for why, but basically: logging, caching, ETag handling and correct Content-Type. You can see what it does here. Do you think there is merit in editing this into the answer?Peary
Thank you Benjamin for clearing out the features favicon provide. I would write that in the accepted answer although not strictly needed.Lindell
C
76

No extra middlewares required. Just use:

app.use('/favicon.ico', express.static('images/favicon.ico'));
Corallite answered 16/7, 2015 at 16:16 Comment(6)
Yep, this should suffice and it's the correct answer because an additional middleware for this feels like overkill.Johny
@Johny 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: 1) memory caching 2) set proper ETag 3) set proper Content-TypeTithable
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 <link rel="shortcut icon" href="/img/favicon.ico"> in the <head> 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.Housemother
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"));.Housemother
be careful you should use the >require('serve-favicon')< module because it generates cache it prevents reading the file from storageMordant
I think cache should be handled by a CDNCorallite
C
32

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">
Celestinacelestine answered 7/4, 2017 at 5:58 Comment(2)
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 <link rel="icon" href="/img/favicon.ico"> where favicon.ico was my filename of my favicon.Astern
For me I had to use ../public/favicon.ico as I was in a directory of a template engine.Madras
H
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.

Herl answered 11/10, 2015 at 7:1 Comment(3)
Like this approach the best. I just used a file to serve instead of base64: fs.createReadStream("./public/favicon.ico").pipe(res);Celestinacelestine
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.Billiebilling
You don't need any code to put favicon. Just put it as file in static files directory.Herl
R
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.

Rendition answered 5/8, 2013 at 22:25 Comment(2)
try app.use(express.favicon('./public/images/favicon.ico'));Boiler
@AlexisDiel as below: why?Carniola
R
4

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

Reglet answered 27/5, 2014 at 16:6 Comment(1)
Why should we go for serve-favicon?Tessitura
F
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.

Famed answered 16/3, 2018 at 14:26 Comment(1)
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.Maccarone
F
3

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"));
});
Footwork answered 14/11, 2021 at 7:29 Comment(0)
H
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
Hodeida answered 10/3, 2019 at 14:13 Comment(0)
W
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.

Wallacewallach answered 25/7, 2020 at 3:57 Comment(0)
A
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'));
Actinolite answered 2/6, 2019 at 18:27 Comment(0)
C
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.

Cotemporary answered 19/7, 2019 at 15:22 Comment(0)
P
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.

Presbyterate answered 17/3, 2016 at 20:0 Comment(1)
I get some error saying express middleware is no longer includedLocalism
V
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.

Volsci answered 30/7, 2018 at 8:20 Comment(0)
X
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".

Xerosere answered 7/11, 2020 at 16:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.