How to handle user-agent in nodejs environment?

My optimal solution for Express...lightweight/fast! https://www.npmjs.com/package/express-useragent

  app.use(require('express-useragent').express())

Your middleware...

app.use(function(req, res, next) {
  req.session.useragent = {
     browser: req.useragent.browser,
     version: req.useragent.version,
     os: req.useragent.os,
     platform: req.useragent.platform
  }
  console.log(JSON.stringify(req.session.useragent, null ,4))
  next()
}

Have you looked at:

  • https://github.com/biggora/express-useragent

Or, write your own middleware:

app.use(function(req, res, next) {
  res.locals.ua = req.get('User-Agent');
  next();
});

Reference: get user agent from inside jade


There are two general situations, where you just need simple matching, and you don't need a module for this, you can just use regex in Node.

var isIpad = !!req.headers['user-agent'].match(/iPad/);
var isAndroid = !!req.headers['user-agent'].match(/Android/);

==> true, false

The other, if you need a nice clean output of browser type, this worked best for me. https://www.npmjs.org/package/useragent