Categories
JavaScript Answers

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

Spread the love

To do server-side browser detection with Node.js, we get the user-agent request header.

For instance, we write

const ua = request.headers["user-agent"];
let browser;
if (/firefox/i.test(ua)) {
  browser = "firefox";
} else if (/chrome/i.test(ua)) {
  browser = "chrome";
} else if (/safari/i.test(ua)) {
  browser = "safari";
} else if (/msie/i.test(ua)) {
  browser = "msie";
} else {
  browser = "unknown";
}

to call test with various regex to check the user agent string.

We get the user-agent request header with request.headers["user-agent"].

We use the i flag to check each string in a case insensitive manner.

By John Au-Yeung

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

Leave a Reply

Your email address will not be published.