bjskistad bjskistad - 11 months ago 102
HTTP Question

Set favicon in HTTP server?

I'm using Node.js HTTP module to create a server, and I'm wondering, how do I set the favicon (shortcut icon) in a HTTP server? I searched this up, and I saw that Express can set the favicon, but I didn't find any HTTP solution.

How do I accomplish this? (Without migrating to Express)

Answer Source

It boils down to this:

  • If the requested path is that of your favicon, serve it.
  • Otherwise, do whatever you're doing with the requests.

Unless you change the path to your favicon in an HTML document, browsers will (usually) make a request to the /favicon.ico path in order to get the favicon of your server.

That means, serving your favicon at /favicon.ico is often enough.

Assuming your favicon is located at ./public/favicon.ico, and will be served at the /favicon.ico path in your server, you can do something like this:

var http = require('http');
var path = require('path');
var fs = require('fs');
var url = require('url');

var server = http.createServer();

// Location of your favicon in the filesystem.
var FAVICON = path.join(__dirname, 'public', 'favicon.ico');

var server = http.createServer(function(req, res) {
  var pathname = url.parse(req.url).pathname;

  // If this request is asking for our favicon, respond with it.
  if (req.method === 'GET' && pathname === '/favicon.ico') {
    // MIME type of your favicon.
    // .ico = 'image/x-icon' or 'image/'
    // .png = 'image/png'
    // .jpg = 'image/jpeg'
    // .jpeg = 'image/jpeg'
    res.setHeader('Content-Type', 'image/x-icon');

    // Serve your favicon and finish response.
    // You don't need to call `.end()` yourself because
    // `pipe` will do it automatically.


  // This request was not asking for our favicon,
  // so you can handle it like any other request.


// Listen on port 3000.
// This line is not relevant to this answer, but
// it would feel incomplete otherwise.