Browserslist Useragent Regexp

4.1.4 · active · verified Sun Apr 19

browserslist-useragent-regexp is a utility that compiles a `browserslist` query into a JavaScript regular expression, enabling client-side user agent detection. This allows developers to determine if a browser supports a given `browserslist` configuration directly in the browser, without server-side checks. It is currently at version 4.1.4 and receives active maintenance, with frequent bug fixes and minor feature releases. Key differentiators include its direct integration with `browserslist` for consistent browser targeting across toolchains and its ability to generate optimized regex patterns. Since version 4.0.0, it is an ESM-only package and requires Node.js >= 14. This library is particularly useful for conditional loading of polyfills or different JavaScript bundles based on client-side browser capabilities.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates the common pattern of using the CLI to generate a JavaScript file containing the compiled RegExp, which is then imported and used to test a user agent string. It includes setup for the `.browserslistrc` and a `package.json` script, along with example runtime usage.

/* .browserslistrc */
// last 2 versions
// not dead

/* package.json */
// {
//   "scripts": {
//     "generate-regex": "echo \"export default $(browserslist-useragent-regexp --allowHigherVersions);\" > supportedBrowsers.js"
//   }
// }

// Run in your terminal once:
// npm run generate-regex

// --- supportedBrowsers.js (generated) ---
// export default /Edge?\/(10[5-9]|1[1-9]\d|[2-9]\d\d|...)/; /* (actual regex will vary) */

// --- your-app.js ---
import supportedBrowsersRegex from './supportedBrowsers.js';

function checkBrowserSupport() {
  const userAgent = typeof navigator !== 'undefined' ? navigator.userAgent : process.env.USER_AGENT ?? '';
  if (userAgent === '') {
    console.warn('User-Agent string is empty. Cannot perform check.');
    return;
  }

  if (supportedBrowsersRegex.test(userAgent)) {
    console.log(`User agent '${userAgent}' is supported.`);
  } else {
    console.warn(`User agent '${userAgent}' is NOT supported.`);
  }
}

// Example usage (replace with actual user agent for testing)
process.env.USER_AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36';
checkBrowserSupport();

process.env.USER_AGENT = 'Mozilla/5.0 (Windows NT 6.1; Trident/7.0; rv:11.0) like Gecko'; // IE 11 (likely unsupported)
checkBrowserSupport();

view raw JSON →