Handling User-Agents in Node.js

User-Agent is the information in the form of a string. This string lets the servers identify the type of application, operating system, version, and vendor of the incoming request from the Web-Browser. The common structure for the User-Agent will be-
 

User-Agent: product / product-version comment

Here, the name of the web browser from which the request is sent will be written in product. The version of the product will be written in product-version and, comment is optional. It contains more information on the product. For example, if the Web-Browser is Firefox, then user-agent will be-
 

Mozilla/5.0 (system-information) 
    platform (platform-details) extensions

The User-Agent module provides web browser properties. It also provides the data needed for blocking automated Browsers. 
 

Setting up of User-Agent Module: To enable this module, first you need to initialize the application with package.json file and then install the user-agents module. So, let us firstly initialize our application with package.json file – 
 

npm init

Now, install the module using – 
 



npm install user-agents --save

To use this module in your application, simply write the following code –

const userAgent = require('user-agents');

Implementations: After installing the module, now let us look at some implementations of this module. The very basic implementation of this module is to generate random user agents. To generate a random user agent write the following code in the main.js file – 
 

filter_none

edit
close

play_arrow

link
brightness_4
code

const UserAgent = require('user-agents'); 
   
const userAgent = new UserAgent();
console.log(userAgent.toString());

chevron_right


Here, we are creating an instance of the User-Agent module with the help of new keyword. Then, we are logging the string format of the randomly generated user agent in the console. The output for the above code will be – 
 

Mozilla/5.0 (Windows NT 10.0; Win64; x64) 
AppleWebKit/537.36 (KHTML, like Gecko) 
Chrome/80.0.3987.132 Safari/537.36

Further, if we want to print the data in JSON format, write the following code – 
 

filter_none

edit
close

play_arrow

link
brightness_4
code

const UserAgent = require('user-agents'); 
   
const userAgent = new UserAgent();
console.log(JSON.stringify(userAgent.data, null, 1));

chevron_right


Here, stringify() function will convert the JavaScript value into JSON. It takes three parameters, first one will be the value to be converted into JSON, the second parameter will be the replace function that will transform the result, and the third parameter will be for adding indentation, line-break characters so that the converted JSON string is easily readable. 

The output for the above code will be –  

{
 "appName": "Netscape",
 "connection": {
  "downlink": 10,
  "effectiveType": "4g",
  "rtt": 100
 },
 "platform": "Win32",
 "pluginsLength": 3,
 "vendor": "Google Inc.",
 "userAgent": 
    "Mozilla/5.0 (Windows NT 6.1; Win64; x64) 
     AppleWebKit/537.36 (KHTML, like Gecko) 
     Chrome/80.0.3987.132 Safari/537.36",
 "viewportHeight": 790,
 "viewportWidth": 1580,
 "deviceCategory": "desktop",
 "screenHeight": 900,
 "screenWidth": 1600,
 "weight": 0.00007295599223907504
}

This module also provides the functionality to restrict the application to be used in only specified devices. For example – 
 

filter_none

edit
close

play_arrow

link
brightness_4
code

const UserAgent = require('user-agents'); 
  
const userAgent = new UserAgent({ deviceCategory: 'mobile' })

chevron_right


Here, we have restricted our application to be used in only mobile devices. Instead of mobile, we can also write desktop or tablet.
Further, If you want to create multiple user agents with the same configuration or property, then write the following code – 
 

filter_none

edit
close

play_arrow

link
brightness_4
code

const UserAgent = require('user-agents');
  
const userAgent = new UserAgent({ 
    platform: 'Win64'
    deviceCategory: 'desktop' 
});
  
const userAgents = Array(50).fill()
        .map(() => userAgent());

chevron_right


Here, we have created an instance of a user agent with the properties as platform and deviceCategory. We are restricting it to use the Windows 64 platform and run only on desktop. Then, we created an array of 50 more user agents with the same configurations.
We can also apply a filter to our application and the returning user agent will be matched to the applied filter. Therefore, to apply a filter, write the following code – 
 

filter_none

edit
close

play_arrow

link
brightness_4
code

const UserAgent = require('user-agents');
  
const userAgent = new UserAgent(/Chrome/);
console.log(userAgent.toString());

chevron_right


Here, we are passing the filter as /Chrome/. The returning user agent will contain Chrome sub-string. We can also combine the filters and an array of configurations that are to be applied to the returning user agent. 
For example – 
 

filter_none

edit
close

play_arrow

link
brightness_4
code

const UserAgent = require('user-agents');
  
const userAgent = new UserAgent([
    /Chrome/,
    {
      deviceCategory: 'tablet',
      platform: 'Win64'
    }
]);

chevron_right


Here, we applied the filter as Chrome along with the array of configurations on the returning user agent. 
 

Conclusion: In this article, we have learned about the User-Agent module of JavaScript and studied how to set up this module in a JavaScript file. We have also seen some of the implementations of this module.




My Personal Notes arrow_drop_up


If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.