Detect Browser / User-Agent in Express.js (Node.js)

Spread the love

Browser / User-Agent detection in Node.js

In Express.js the details of the HTTP User-Agent making the request to a URL is available in the req.headers object’s user-agent property.

req.headers['user-agent']

Node.js will not be able to detect the browser if it doesn’t have access to the req object, so the detection process should be done in a route handler or through one (pass the req object). In this example, the User-Agent is detected when a request is made to the homepage of the website.

app.get('/', function(req, res) {
    console.log('User-Agent: ' + req.headers['user-agent']);
});

If you are not in the mood to get into the finer details of User-Agent detection, there is a Node.js module called ua-parser which is a port to node.js of Browserscope‘s User-Agent parser, check it out.

Join Geezgo for free. Use Geezgo\’s end-to-end encrypted Chat with your Closenets (friends, relatives, colleague etc) in personalized ways.>>

 879 

Leave a Reply