Skip to content

Instantly share code, notes, and snippets.

@kentbrew
Created January 3, 2011 19:32
Show Gist options
  • Star 99 You must be signed in to star a gist
  • Fork 26 You must be signed in to fork a gist
  • Save kentbrew/763822 to your computer and use it in GitHub Desktop.
Save kentbrew/763822 to your computer and use it in GitHub Desktop.
How to short-circuit those annoying favicon requests in node.js
// early experiments with node had mysterious double requests
// turned out these were for the stoopid favicon
// here's how to short-circuit those requests
// and stop seeing 404 errors in your client console
var http = require('http');
http.createServer(function (q, r) {
// control for favicon
if (q.url === '/favicon.ico') {
r.writeHead(200, {'Content-Type': 'image/x-icon'} );
r.end();
console.log('favicon requested');
return;
}
// not the favicon? say hai
console.log('hello');
r.writeHead(200, {'Content-Type': 'text/plain'} );
r.write('Hello, world!');
r.end();
}).listen(8000);
console.log('Server running at http://127.0.0.1:8000/');
@vikkrantxx7
Copy link

Thanks so much .. I was wondering why my page's visitor count was increasing twice on a single request.

@varun-manjunath
Copy link

I read up on StackOverFlow that 204 (No Content) is a better response status than 200 (Success) for silencing the favicon problem! Just saying. good solution, I just like the semantics implied by status 204. :)

@woody180
Copy link

Great approach. Thank you

@Michael-Yimam
Copy link

Thank You.

@lucierabahi
Copy link

πŸ‘ Thanks!

@rhernandog
Copy link

Still useful, thanks good Sir!!! πŸ‘ πŸ‘

@skirankumar7
Copy link

Thanks much πŸ‘ πŸ‘ πŸ‘

@leomiranda
Copy link

Great man, thank you!

@Alik64
Copy link

Alik64 commented May 2, 2022

Exactly what i was looking for! Thanks ! πŸ‘

@souli2020
Copy link

souli2020 commented Feb 20, 2023

I think the solution above don't avoid the favico requests @ least in my case! the solution that i came up with is adding an else statement in the end of my code to avoid all urls that i don't want

const http = require('http');

const server = http.createServer((req, res) => {
    console.log(req.url)
    console.log('user hit the server')
    if (req.url === '/') {


        res.writeHead(200,
            {
                'content-type': 'text/html',

            })
        
        res.write(`<h1>home page</h1>`)
         res.end()
    }
    else {
        res.writeHead(
                404,
            { 'Content-Type': 'text/html' }
        )
        res.write('<h2>Page not found!</h2>');
        res.end()
    }

})
server.listen(5000)`

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment