Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

expressjs node.js serve different data to google/etc bot and human traffic

I want to determine if incoming requests are from a bot (eg google, bing), or a human, and serve different data to each, for example, json data for client javascript to construct the site or preprocessed html.

Using expressjs, is there an easy way to do this? Thanks.

like image 869
Harry Avatar asked Sep 22 '11 02:09

Harry


2 Answers

You can check the req.header('User-Agent') for 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html'. If it's that you know it's Google and can send it different data.

http://www.google.com/support/webmasters/bin/answer.py?answer=1061943

How to get headers http://expressjs.com/4x/api.html#req.get

like image 119
Ryan Doherty Avatar answered Nov 02 '22 22:11

Ryan Doherty


I recommend you to response according to the requested MIME type (which is present in the "Accept" header). You can do this with Express this way:

app.get('/route', function (req, res) {
    if (req.is('json')) res.json(data);
    else if (req.is('html')) res.render('view', {});
    else ...
});
like image 22
Rubén Norte Avatar answered Nov 03 '22 00:11

Rubén Norte