What is the use of serve favicon from Node.js server ?
Last Updated :
13 Jul, 2021
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?
- User agents request frequently and indiscriminately for favicon. Use this middleware before your logger middleware to exclude these request from logs.
- favicon.ico is small size file, this module caches the favicon in memory to give better performance by skipping dick access.
- This module provides an ETag for the icon.
- This module provides compatible Content-Type for the icon.
Project Setup and Module Installation:
-
Step 1: Create a NodeJS application and name it Project using the following command.
mkdir Project && cd Project
npm init -y
-
Step 2: Install the dependency modules using the following command.
npm install express serve-favicon
-
Step 3: Generate a favicon from here or download the GFG favicon and place it in your root directory. Then create index.html and server.js in your Project directory.
Project Directory: It will look like this.
Project directory
Example:
index.html
<!DOCTYPE html>
< html >
< head >
< title >GeeksForGeeks</ title >
</ head >
< body >
< h1 style = "color: green;" >
GeeksForGeeks
</ h1 >
</ body >
</ html >
|
server.js
const favicon = require( 'serve-favicon' );
const express = require( 'express' )
const app = express()
app.use(favicon(__dirname + '/favicon.ico' ));
app.get( '/' , (_, res)=> res.sendFile(__dirname + '/index.html' ))
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.
Share your thoughts in the comments
Please Login to comment...