Categories
JavaScript Answers

How to do server-side browser detection with Node.js?

Spread the love

Sometimes, we want to do server-side browser detection with Node.js

In this article, we’ll look at how to do server-side browser detection with Node.js.

How to do server-side browser detection with Node.js?

To do server-side browser detection with Node.js, we can use the ua-parser-js package.

To install it, we run

npm i ua-parser-js

Then we use it by writing

const UAParser = require("ua-parser-js");
//...
const ensureLatestBrowser = (req, res, next) => {
  const parser = new UAParser();
  const ua = req.headers["user-agent"];
  const browserName = parser.setUA(ua).getBrowser().name;
  const fullBrowserVersion = parser.setUA(ua).getBrowser().version;
  //...
  return next();
};

app.all(/^(?!(\/update)).*$/, ensureLatestBrowser);

to create a new UAParser instance.

Then we get the user-agent request header value with req.headers["user-agent"].

Next, we call setUA with the ua user agent string to parse the user agent string.

And then we call getBrowser on the parsed user agent object to get various parts of the user agent string to get the browser name, version, etc.

Conclusion

To do server-side browser detection with Node.js, we can use the ua-parser-js package.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *