Open In App

What is the use of serve favicon from Node.js server ?

When the browser loads a website for the first time, it will automatically request /favicon.ico (GET) to load favicon. A favicon is a small size file as known as website icon, tab icon, URL icon or bookmark icon. The serve-favicon module is used to serve favicon from the NodeJS server.

Why to use this module?



Project Setup and Module Installation:

Project Directory: It will look like this.

Project directory

Example:




<!DOCTYPE html>
<html>
  
<head>
    <title>GeeksForGeeks</title>
</head>
  
<body>
    <h1 style="color: green;">
        GeeksForGeeks
    </h1>
</body>
  
</html>




// Import modules
const favicon = require('serve-favicon');
const express = require('express')
const app = express()
  
// Returns a middleware to serve favicon
app.use(favicon(__dirname + '/favicon.ico'));
  
// API endpoint to serve index 
app.get('/', (_, res)=> res.sendFile(__dirname + '/index.html'))
  
// Start the server
app.listen(8080);

Step to run the application: Run the server.js using the following command

node server.js

Output: Open the browser and go to http://localhost:8080/, we will see the following output on screen.

Note: Remember, serve-favicon is only serving default, implicit favicon, which is GET /favicon.ico. Use serve-static for vendor-specific icons that require HTML markup. 


Article Tags :