TechSetupGuides
IntermediateUAParser.jsJavaScriptUser-AgentBrowser DetectionDevice DetectionNode.jsClient HintsBot Detection

UAParser.js: User-Agent Detection for Web Applications

Complete setup guide for UAParser.js - the comprehensive JavaScript library to detect browser, OS, CPU, and device type/model from User-Agent strings. Supports both client-side browser and server-side Node.js environments. Features bot detection, Client Hints support, and 5000+ detection patterns.

  1. Step 1

    What is UAParser.js?

    UAParser.js is the most comprehensive and widely-used JavaScript library for User-Agent parsing, with over 10,000 GitHub stars. It detects browsers, operating systems, CPU architectures, device types and models, rendering engines, bots, AI crawlers, and more. The library works seamlessly in both browser (client-side) and Node.js (server-side) environments, making it versatile for any web application. Version 2.0 introduces support for the modern User-Agent Client Hints API, bot detection, and additional extensions.

    # Key Features:
    # - Detects Browser, OS, CPU, Device, Engine
    # - Bot and AI crawler detection (v2.x)
    # - Client Hints API support (v2.x)
    # - Runs in browser or Node.js
    # - 5000+ detection patterns
    # - MIT (v1.x) and AGPL (v2.x) licenses
    # - Over 10K GitHub stars, trusted by major companies
  2. Step 2

    Installation via Package Managers

    UAParser.js is available on npm and can be installed using npm, yarn, or pnpm. You can also use CDN links for browser-based projects without package management. For production use, prefer the latest stable version to get modern features like Client Hints support and bot detection.

    # npm (latest v2.x - AGPL license)
    npm install ua-parser-js
    
    # yarn
    yarn add ua-parser-js
    
    # pnpm
    pnpm add ua-parser-js
    
    # For v1.x (MIT license, less features)
    npm install ua-parser-js@1
  3. Step 3

    Basic Usage in Node.js

    In Node.js environments, import UAParser and parse the User-Agent string. By default, it parses the process User-Agent, but you can pass custom User-Agent strings for parsing. The parser returns an object containing browser, OS, CPU, device, and engine information.

    // Import UAParser
    const UAParser = require('ua-parser-js');
    
    // Parse default User-Agent (current process)
    const parser = new UAParser();
    const result = parser.getResult();
    
    console.log(result);
    // Output:
    // {
    //   browser: { name: 'Firefox', version: '122.0', major: '122' },
    //   device: { model: undefined, type: undefined, vendor: undefined },
    //   engine: { name: 'Gecko', version: '122.0' },
    //   os: { name: 'Windows', version: '11' },
    //   cpu: { architecture: 'amd64' }
    // }
    
    // Parse specific User-Agent string
    const customParser = new UAParser('Mozilla/5.0 (iPhone; CPU iPhone OS 16_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.6 Mobile/15E148 Safari/604.1');
    const customResult = customParser.getResult();
    console.log(customResult.device.model); // 'iPhone'
  4. Step 4

    Basic Usage in Browser

    In browser environments, UAParser automatically detects the current browser's User-Agent string when included via script tag or imported as an ES module. You can also pass custom User-Agent strings for analysis, useful for debugging or analyzing stored data.

    <!DOCTYPE html>
    <html>
    <head>
        <title>UAParser Demo</title>
        <script src="https://unpkg.com/ua-parser-js@latest/dist/ua-parser.min.js"></script>
    </head>
    <body>
        <h1>My Browser Info</h1>
        <div id="browser"></div>
        <div id="device"></div>
        <div id="os"></div>
    
        <script>
            // Parse current browser User-Agent
            var parser = new UAParser();
            var result = parser.getResult();
            
            document.getElementById('browser').innerHTML = 
                'Browser: ' + result.browser.name + ' ' + result.browser.version;
            
            document.getElementById('device').innerHTML = 
                'Device: ' + (result.device.model || 'Desktop');
            
            document.getElementById('os').innerHTML = 
                'OS: ' + result.os.name + ' ' + result.os.version;
        </script>
    </body>
    </html>
  5. Step 5

    ES Module Usage (Version 2.x)

    UAParser.js v2.x supports ES modules natively, allowing modern import syntax. This is recommended for newer projects using module-based bundlers like Webpack, Rollup, or Vite. The library also exports sub-modules for specific use cases like bot detection or browser detection individually.

    // Full library import
    import { UAParser } from 'ua-parser-js';
    
    const result = new UAParser().getResult();
    
    // Individual module imports (v2.x only)
    import { botDetect } from 'ua-parser-js/bot-detection';
    import { browserDetection } from 'ua-parser-js/browser-detection';
    import { deviceDetection } from 'ua-parser-js/device-detection';
    import { uaParserEnums as enums } from 'ua-parser-js/enums';
    import { uaParserHelper as helpers } from 'ua-parser-js/helpers';
    
    // Use specific detection
    const botResult = await botDetect('Googlebot User-Agent...');
    console.log(botResult.name); // 'Googlebot'
    ⚠ Heads up: ES module support is only available in version 2.x. Version 1.x uses CommonJS only and does not support named exports.
  6. Step 6

    Browser-Specific Detection Methods

    UAParser provides convenience methods to access specific detection results directly without calling getResult(). Each method returns a detailed object with name, version, major (first version digit), and other relevant properties. These methods are useful when you need quick access to specific information.

    const UAParser = require('ua-parser-js');
    
    const parser = new UAParser();
    
    // Get browser info
    const browser = parser.getBrowser();
    console.log(browser.name);    // 'Chrome'
    console.log(browser.version); // '131.0'
    console.log(browser.major);   // '131'
    console.log(browser.type);    // 'browser'
    
    // Get OS info
    const os = parser.getOS();
    console.log(os.name);    // 'macOS'
    console.log(os.version); // '14.6'
    console.log(os.description); // 'macOS 14.6'
    
    // Get device info
    const device = parser.getDevice();
    console.log(device.vendor); // 'Apple'
    console.log(device.model);  // 'iPhone'
    console.log(device.type);   // 'mobile'
    
    // Get engine info
    const engine = parser.getEngine();
    console.log(engine.name);    // 'Blink'
    console.log(engine.version); // '131.0'
  7. Step 7

    Device Type Detection

    UAParser detects device types including mobile phones, tablets, smart TVs, wearables, consoles, XR (VR/AR) devices, and embedded systems. This is useful for responsive design, device-specific features, and analytics. The type detection is automatic based on User-Agent patterns.

    const UAParser = require('ua-parser-js');
    
    // Mobile phone example
    const phoneUA = 'Mozilla/5.0 (iPhone; CPU iPhone OS 16_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148';
    const phone = new UAParser(phoneUA);
    console.log(phone.getDevice().type);  // 'mobile'
    console.log(phone.getDevice().model); // 'iPhone'
    
    // Tablet example
    const tabletUA = 'Mozilla/5.0 (iPad; CPU OS 16_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.6 Mobile/15E148 Safari/604.1';
    const tablet = new UAParser(tabletUA);
    console.log(tablet.getDevice().type);  // 'tablet'
    console.log(tablet.getDevice().model); // 'iPad'
    
    // Smart TV example
    const tvUA = 'Mozilla/5.0 (SMART-TV; Linux; Tizen 2.3) AppleWebKit/537.36';
    const tv = new UAParser(tvUA);
    console.log(tv.getDevice().type);  // 'smarttv'
    console.log(tv.getDevice().model); // 'Samsung Smart TV' or TV model
  8. Step 8

    Bot Detection (Version 2.x)

    Version 2.x introduces comprehensive bot and AI crawler detection as a separate module. This detects search engine bots, social media bots, news aggregators, AI crawlers, and more. Bot detection is essential for web security, analytics accuracy, and SEO optimization.

    // Import bot detection module (v2.x)
    import { botDetect } from 'ua-parser-js/bot-detection';
    
    // Detect Googlebot
    const googlebot = await botDetect('Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)');
    console.log(googlebot.name); // 'Googlebot'
    console.log(googlebot.version); // '2.1'
    console.log(googlebot.category); // 'fetcher'
    console.log(googlebot.vendor); // 'Google'
    
    // Detect AI crawler (Perplexity)
    const perplexity = await botDetect('Perplexity/0.1 (+https://www.perplexity.ai/)');
    console.log(perplexity.name); // 'Perplexity'
    console.log(perplexity.category); // 'fetcher'
    
    // Detect social media bot
    const facebook = await botDetect('facebookexternalhit/1.1 (+http://www.facebook.com/externalhit_uishr.php)');
    console.log(facebook.name); // 'FacebookExternalHit'
    console.log(facebook.category); // 'fetcher'
    console.log(facebook.vendor); // 'Facebook'
    
    // Check if it's a bot
    function isBot(ua) {
        const result = await botDetect(ua);
        return result.name !== '?';
    }
    
    if (await isBot(userAgent)) {
        console.log('Bot traffic detected');
    }
    ⚠ Heads up: Bot detection requires v2.x. Version 1.x does not include bot detection capabilities. Always validate User-Agent strings as they can be easily spoofed.
  9. Step 9

    Client Hints Support (Version 2.x)

    Modern browsers expose User-Agent Client Hints as a more privacy-friendly alternative to the traditional User-Agent string. UAParser v2.x supports parsing Client Hints headers including Sec-CH-UA, Sec-CH-UA-Mobile, Sec-CH-UA-Model, etc. This provides more accurate and future-proof detection.

    // Parse with Client Hints (v2.x)
    const UAParser = require('ua-parser-js');
    
    // Parse User-Agent with Client Hints
    const parser = new UAParser('Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36');
    parser.setClientHints({
        brands: [
            { brand: 'Chromium', version: '131' },
            { brand: 'Google Chrome', version: '131' }
        ],
        platform: 'Windows',
        fullVersionList: ['Chromium/131.0.0.0', 'Google Chrome/131.0.0.0'],
        model: 'Samsung Galaxy S24',
        mobile: false,
        architecture: 'x86',
        bitness: '64',
        formFactors: ['Laptop']
    });
    
    const result = parser.getResult();
    console.log(result.brand); // Populated with client hints data
    
    // Or use navigator.userAgentData in modern browsers (client-side)
    if (navigator.userAgentData) {
        const parser = new UAParser();
        parser.setClientHints(navigator.userAgentData);
        const browserInfo = parser.getBrowser();
    }
    ⚠ Heads up: Client Hints support is only available in v2.x and requires modern browsers that support the User-Agent Client Hints API. Firefox and Safari have limited support.
  10. Step 10

    Using Extensions to Add Custom Patterns

    UAParser allows extending detection by adding custom regex patterns. This is useful for detecting custom internal applications, testing environments, or detecting emerging User-Agent patterns not yet in the default database. Extensions take precedence over default patterns.

    const UAParser = require('ua-parser-js');
    
    // Define custom detection patterns
    const myParser = new UAParser(undefined, {
        browser: [
            [/MyInternalApp\/([\w\.]+)/, ['name', 'version']],
            [/CustomBrowser\/([\d\.]+)/, ['name', 'version']]
        ],
        device: [
            [/CustomDevice-Model([^\s]+)/, ['vendor', 'model']]
        ]
    });
    
    // Test with custom User-Agent
    myParser.setUA('MyInternalApp/2.5.1');
    
    const result = myParser.getResult();
    console.log(result.browser.name);  // 'MyInternalApp'
    console.log(result.browser.version); // '2.5.1'
    
    // Extensions from v2.x
    const extensions = require('ua-parser-js/extensions');
    
    const parserWithExtensions = new UAParser('Mozilla/5.0', extensions);
    // Now includes app, crawler, and other extended detections
  11. Step 11

    Working with TypeScript

    UAParser.js comes with TypeScript definitions for better IDE support and type safety. The types define the structure of result objects and method signatures for compile-time error checking. This is especially useful in large codebases where type safety helps prevent runtime errors.

    import { UAParser } from 'ua-parser-js';
    
    const parser = new UAParser();
    const result = parser.getResult();
    
    // Typed access to properties
    const browserName: string = result.browser.name;
    const browserVersion: string | undefined = result.browser.version;
    const browserType: string | undefined = result.browser.type;
    
    // Device with optional chaining
    const deviceModel = result.device?.model ?? 'Unknown';
    console.log(`Browser: ${browserName}, Device: ${deviceModel}`);
    
    // TypeScript enums
    import { uaParserEnums } from 'ua-parser-js/enums';
    const deviceType = uaParserEnums.DEVICE_TYPE_MOBILE;
  12. Step 12

    Common Use Cases

    UAParser.js enables various practical use cases from responsive design to analytics. You can implement device-specific features, track user demographics, block bots, optimize content delivery, enforce access restrictions, and create better user experiences based on detected capabilities.

    const UAParser = require('ua-parser-js');
    
    // 1. Mobile detection for responsive features
    function isMobileRequest(req) {
        const parser = new UAParser(req.headers['user-agent']);
        return parser.getDevice().type === 'mobile';
    }
    
    // 2. Browser-specific workarounds
    function applyBrowserWorkarounds(req) {
        const parser = new UAParser(req.headers['user-agent']);
        const browser = parser.getBrowser();
        
        if (browser.name === 'Internet Explorer') {
            loadLegacyPolyfills();
        } else if (browser.name === 'Safari' && browser.major === '14') {
            enableWorkaroundForSafari14();
        }
    }
    
    // 3. Block known bad bots
    function shouldBlockBot(req) {
        const parser = new UAParser(req.headers['user-agent']);
        const bot = parser.getBot();
        const badBots = ['bad-bot', 'spider-bot'];
        return badBots.includes(bot.name);
    }
    
    // 4. Analytics tracking
    function trackUserAgentMetrics(req) {
        const parser = new UAParser(req.headers['user-agent']);
        return {
            browser: parser.getBrowser().name,
            os: parser.getOS().name,
            deviceType: parser.getDevice().type,
            mobile: parser.getDevice().type === 'mobile'
        };
    }
  13. Step 13

    Server-Side Rendering with Next.js

    UAParser works well with server-side rendering frameworks like Next.js. You can parse User-Agent on the server to make dynamic content decisions, implement server-side redirects, or optimize SSR based on detected device and browser capabilities.

    // Next.js getServerSideProps example
    const UAParser = require('ua-parser-js');
    
    export async function getServerSideProps(context) {
        const userAgent = context.req.headers['user-agent'];
        const parser = new UAParser(userAgent);
        
        const browser = parser.getBrowser();
        const device = parser.getDevice();
        const os = parser.getOS();
        
        return {
            props: {
                browserName: browser.name,
                browserVersion: browser.version,
                isMobile: device.type === 'mobile',
                isTablet: device.type === 'tablet',
                deviceModel: device.model || 'Unknown',
                osName: os.name,
                osVersion: os.version
            }
        };
    }
    
    // Next.js redirect example
    export async function getServerSideProps(context) {
        const parser = new UAParser(context.req.headers['user-agent']);
        
        if (parser.getDevice().type === 'mobile') {
            return {
                redirect: {
                    destination: '/mobile',
                    permanent: false
                }
            };
        }
        
        return { props: {} };
    }
  14. Step 14

    Security Considerations

    While UAParser is powerful, User-Agent strings are user-controlled and can be easily spoofed. Never use User-Agent detection for security-critical decisions like authentication or authorization. Use it for UI optimization, analytics, and feature detection only.

    // BAD: Don't use for security
    function authorizeUser(req) {
        const parser = new UAParser(req.headers['user-agent']);
        if (parser.getBrowser().name === 'Chrome') {
            // Vulnerable! User-Agent can be spoofed
            return true;
        }
        return false;
    }
    
    // GOOD: Use for analytics and optimization
    function optimizeDelivery(req) {
        const parser = new UAParser(req.headers['user-agent']);
        
        // Safe use case: feature detection
        if (parser.getDevice().type === 'mobile') {
            return { compression: true, imageQuality: 'low' };
        }
        return { compression: false, imageQuality: 'high' };
    }
    
    // BEST: Combine with other signals for bot detection
    function detectBotTraffic(userAgent, ip, behavior) {
        const parser = new UAParser(userAgent);
        const botInfo = parser.getBot();
        
        // Check multiple signals
        const isKnownBot = botInfo.name !== '?';
        const isFromKnownIP = checkIPAgainstKnownBotRanges(ip);
        const hasBotBehavior = analyzeBehaviorPatterns(behavior);
        
        return { isBot: isKnownBot || isFromKnownIP || hasBotBehavior };
    }
    ⚠ Heads up: User-Agent detection should NEVER be used for: authentication, authorization, rate limiting decisions, or security-critical features. It can be spoofed easily. Use it only for UI optimization, analytics, and user experience improvements.
  15. Step 15

    Performance Optimization

    For high-traffic applications, optimize UAParser usage by caching parsed results, reusing parser instances, minimizing parsing on every request, and considering server-side caching. This is especially important in Node.js where you may process hundreds of requests per second.

    // Cache parsed results in memory
    const userAgentCache = new Map();
    
    function getCachedUserAgentInfo(userAgent) {
        if (userAgentCache.has(userAgent)) {
            return userAgentCache.get(userAgent);
        }
        
        const parser = new UAParser(userAgent);
        const info = {
            browser: parser.getBrowser(),
            device: parser.getDevice(),
            os: parser.getOS()
        };
        
        // Cache for 1 minute (60000ms)
        userAgentCache.set(userAgent, info);
        
        // Clean old entries periodically
        setTimeout(() => userAgentCache.delete(userAgent), 60000);
        
        return info;
    }
    
    // Middleware with caching (Express)
    const cachedUserAgent = new Map();
    
    function userAgentMiddleware(req, res, next) {
        const ua = req.headers['user-agent'];
        
        if (!cachedUserAgent.has(ua)) {
            const parser = new UAParser(ua);
            cachedUserAgent.set(ua, parser.getResult());
        }
        
        req.userAgentData = cachedUserAgent.get(ua);
        next();
    }
  16. Step 16

    License Information

    UAParser.js has different license options depending on the version. Version 1.x uses the permissive MIT license, allowing commercial use without contributing back. Version 2.x uses AGPL-3.0, which requires any derivative works to be open-sourced under the same license. For commercial products where you cannot comply with AGPL, consider using v1.x or contacting the maintainer for commercial licensing.

    # Version 1.x - MIT License (permissive)
    npm install ua-parser-js@1
    # License: MIT - Commercial use allowed without obligations
    
    # Version 2.x - AGPL-3.0 (copyleft)
    npm install ua-parser-js
    # License: AGPL-3.0-OR-LATER
    # Required to release derivative code under AGPL
    
    # Check installed version
    npm list ua-parser-js
    
    # For commercial licensing inquiries:
    # Contact: https://github.com/faisalman
    # Website: https://uaparser.dev
    ⚠ Heads up: If you cannot comply with AGPL requirements (open sourcing your code), use version 1.x with MIT license or contact the maintainer for commercial licensing options. Check your organization's licensing policies before upgrading to v2.x.
  17. Step 17

    Resources and Community

    UAParser.js has an active community and extensive documentation online. The project is maintained by Faisal Salman with contributions from thousands of developers. Additional resources include the official documentation, CHANGELOG for version updates, demo site, support channels, and the OpenCollective sponsorship page.

    # Official Resources
    # Homepage: https://uaparser.dev
    # GitHub: https://github.com/faisalman/ua-parser-js
    # Docs (v1.x): https://docs.uaparser.dev/v1
    # Docs (v2.x): https://docs.uaparser.dev
    # Live Demo: https://uaparser.dev
    
    # Community Support
    # Issues: https://github.com/faisalman/ua-parser-js/issues
    # Discussions: https://github.com/faisalman/ua-parser-js/discussions
    
    # Sponsor the Project
    # OpenCollective: https://opencollective.com/ua-parser-js
    # GitHub Sponsors: https://github.com/sponsors/faisalman
    
    # Contributing:
    # Guidelines: https://github.com/faisalman/ua-parser-js/blob/master/CONTRIBUTING.md

Feature requests

Sign in to suggest features or vote on existing ones.

No feature requests yet.

Discussion

0 people marked this as worked·Sign in to mark your own.

Sign in to join the discussion.

No comments yet.