user-agents

repository·main·Indexed 22 days ago

https://github.com/intoli/user-agents

A JavaScript library for generating realistic, random user agents and browser fingerprints based on daily-updated market share data. It provides the UserAgent class to generate strings and detailed fingerprint data, with support for filtering by device category, regular expressions, custom functions, and browser lists. Version 2.1.140 is rewritten in TypeScript with native ESM and CJS support.

Tokens
3.9K
Snippets
17
Records
20
Agent score
79%

What's inside user-agents

  1. Understand the UserAgent data distribution

    main

    The dataset is built from a snapshot of the last 24 hours of real-world browser traffic and is refreshed daily.

    Key characteristics:

    • Real-world weighting: User agents are not selected with uniform probability. Each profile is weighted according to its real-world usage frequency. For example, Chrome on Windows will appear much more often than niche configurations.
    • Dynamic updates: Because the data is refreshed daily, older browser versions naturally phase out as they disappear from real-world traffic.
  2. Upgrade from v1 to v2

    main

    The project is transitioning from v1 (UMD bundle) to v2 (Native ESM/CJS).

    Key changes in v2:

    • Rewritten in TypeScript with exported types for UserAgentData and Filter.
    • Built with tsup for native ESM and CJS support.
    • Removed Function class inheritance to resolve Content Security Policy (CSP) errors in browser extensions.

    Migration: Both versions share an identical API surface and receive the same daily data, so upgrading should be straightforward. To install the v2 version, use the @next tag:

    npm install user-agents@next
  3. Define filters for UserAgent generation

    main

    The Filter type allows you to restrict the pool of user agents used for generation. You can provide filters in several formats:

    • String: Exact match for a property value.
    • RegExp: Matches against the userAgent string.
    • Function: A predicate function (parentObject: T) => boolean for custom logic.
    • Array: An array of filters that must all be satisfied (logical AND).
    • Object: A mapping of property names to Filter objects (logical AND). This supports nested properties.

    If a filter is applied to an object, it can traverse into nested properties like connection.

    import { UserAgent } from 'user-agents';
    
    // 1. String filter
    const ua1 = new UserAgent({ platform: 'iPhone' });
    
    // 2. RegExp filter (matches against the userAgent string)
    const ua2 = new UserAgent(/Chrome/);
    
    // 3. Object filter (supports nested properties)
    const ua3 = new UserAgent({
      platform: 'Linux x86_64',
      connection: { effectiveType: '4g' }
    });
    
    // 4. Array filter (logical AND)
    const ua4 = new UserAgent(['Win32', /Apple/]);
    
    // 5. Custom function filter
    const ua5 = new UserAgent((data) => data.screenHeight > 1000);
  4. Generate multiple User Agents with the same filters

    main

    To efficiently generate many user agents with the same configuration, initialize one UserAgent instance with your filters and then call that instance as a function (or use .random()) to produce new random instances using the same filter set.

    import UserAgent from 'user-agents';
    
    const userAgent = new UserAgent({ platform: 'Win32' });
    const userAgents = Array(1000).fill().map(() => userAgent());
  5. Generate a random User Agent

    main

    To generate a random user agent and its associated browser fingerprint, instantiate the UserAgent class. You can retrieve the raw user agent string using .toString() or access the detailed fingerprint data via the .data property.

    import UserAgent from 'user-agents';
    
    const userAgent = new UserAgent();
    console.log(userAgent.toString());
    console.log(JSON.stringify(userAgent.data, null, 2));
  6. Filter for modern browsers using browserslist

    main

    To restrict generation to modern browsers, combine user-agents with browserslist and browserslist-useragent. Use a browserslist query to define your criteria and a custom filter function to validate the userAgent.data.userAgent string.

    import browserslist from 'browserslist';
    import { matchesUA } from 'browserslist-useragent';
    import UserAgent from 'user-agents';
    
    const browsers = browserslist('last 2 versions and not dead');
    
    function isModernBrowser(data) {
      return matchesUA(data.userAgent, { browsers, allowHigherVersions: true });
    }
    
    const userAgent = new UserAgent(isModernBrowser);
  7. Combine multiple filters with arrays

    main

    You can pass an array to the UserAgent constructor to apply multiple filters simultaneously. This array can contain objects, regular expressions, or functions.

    import UserAgent from 'user-agents';
    
    const userAgent = new UserAgent([
      /Safari/,
      {
        connection: {
          type: 'wifi',
        },
        platform: 'MacIntel',
      },
    ]);
  8. Filter User Agents with Regular Expressions

    main

    You can pass a RegExp to the UserAgent constructor to ensure the generated user agent string matches the specified pattern.

    import UserAgent from 'user-agents';
    
    const userAgent = new UserAgent(/Safari/);
  9. Restrict User Agents by device category

    main

    Pass an object to the UserAgent constructor to restrict the generated user agent to a specific deviceCategory. Supported values include 'desktop', 'mobile', and 'tablet'.

    import UserAgent from 'user-agents';
    
    const userAgent = new UserAgent({ deviceCategory: 'mobile' });
  10. Filter User Agents with custom functions

    main

    For complex logic, pass a function to the UserAgent constructor. The function receives the userAgent.data object as an argument and must return true for the user agent to be accepted.

    import UserAgent from 'user-agents';
    import { parse } from 'useragent';
    
    const userAgent = new UserAgent((data) => {
      const os = parse(data.userAgent).os;
      return os.family === 'iOS' && parseInt(os.major, 10) > 11;
    });
  11. Generate new random UserAgents efficiently

    main

    To generate new user agents, you can use either the instance method .random() or the static method UserAgent.random(filters).

    Performance Tip: Use the instance method .random() when you want to generate multiple user agents using the same filters. The instance method reuses the filter processing and data preparation, making subsequent generations up to 100x faster than the initial construction.

    Behavioral Difference:

    • userAgent.random() returns a new UserAgent instance.
    • UserAgent.random(filters) (static) returns a new UserAgent instance, but returns null instead of throwing an error if the filters match no user agents.
    // Efficiently reuse filter processing
    const generator = new UserAgent({ deviceCategory: 'desktop' });
    const agent1 = generator.random();
    const agent2 = generator.random();
    
    // Or use the static method (returns null if no match found)
    const agent3 = UserAgent.random({ deviceCategory: 'tablet' });