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 cu
If you are using Express > 4.0, you could go for serve-favicon
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.
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.
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.
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)
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')));
According to the package description:
ETag
based on the contents of the icon, rather than file system properties.Content-Type
.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.