[javascript] How to set custom favicon in Express?

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?

This question is related to javascript node.js express favicon

The answer is


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.


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 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".


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.


No extra middlewares required. Just use:

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

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.


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.


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.


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


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.


Install express-favicon middleware:

npm install express-favicon --save

Use it like this:

const favicon = require('express-favicon');
app.use(favicon(__dirname + 'favicon.ico'));

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

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">

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to node.js

Hide Signs that Meteor.js was Used Querying date field in MongoDB with Mongoose SyntaxError: Cannot use import statement outside a module Server Discovery And Monitoring engine is deprecated How to fix ReferenceError: primordials is not defined in node UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block dyld: Library not loaded: /usr/local/opt/icu4c/lib/libicui18n.62.dylib error running php after installing node with brew on Mac internal/modules/cjs/loader.js:582 throw err DeprecationWarning: Buffer() is deprecated due to security and usability issues when I move my script to another server Please run `npm cache clean`

Examples related to express

UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block jwt check if token expired Avoid "current URL string parser is deprecated" warning by setting useNewUrlParser to true MongoNetworkError: failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017] npm notice created a lockfile as package-lock.json. You should commit this file Make Axios send cookies in its requests automatically What does body-parser do with express? SyntaxError: Unexpected token function - Async Await Nodejs Route.get() requires callback functions but got a "object Undefined" How to redirect to another page in node.js

Examples related to favicon

Add Favicon with React and Webpack What is the best practice for creating a favicon on a web site? HTML 5 Favicon - Support? How can I get a favicon to show up in my django app? How to set-up a favicon? Favicon not showing up in Google Chrome Add image in title bar How to set custom favicon in Express? Why does my favicon not show up? Correct MIME Type for favicon.ico?