7

I'm still new with node js. Is there any workaround or methods on how to identify the request from client-side is from mobile or non-mobile devices using node js? Because what i'm doing now is i want to restrict the access on certain API based on the device type (mobile / desktop). I'm using restify for the server-side. Thanks.

DMDJ
  • 357
  • 1
  • 6
  • 13

2 Answers2

7

@H.Mustafa, a basic way to detect if a client is using a mobile device is by matching a particular set of strings in the userAgent.

function detectMob() {
    const toMatch = [
        /Android/i,
        /webOS/i,
        /iPhone/i,
        /iPad/i,
        /iPod/i,
        /BlackBerry/i,
        /Windows Phone/i
    ];

    return toMatch.some((toMatchItem) => {
        return navigator.userAgent.match(toMatchItem);
    });
}

(Reference: Detecting a mobile browser)

Run this snippet of code in client's device. If the returned result is true, you know it's a mobile device else a desktop/laptop. Hope this helps.

Melvin Abraham
  • 2,870
  • 5
  • 19
  • 33
7

The method I'd suggest is to use the npm package express-useragent since is more reliable over the long term.

var http = require('http')
  , useragent = require('express-useragent');
 
var srv = http.createServer(function (req, res) {
  var source = req.headers['user-agent']
  var ua = useragent.parse(source);
  
  // a Boolean that tells you if the request 
  // is from a mobile device
  var isMobile = ua.isMobile

  // do something more
});
 
srv.listen(3000);

It also works with expressJS:

var express = require('express');
var app = express();
var useragent = require('express-useragent');
 
app.use(useragent.express());
app.get('/', function(req, res){
    res.send(req.useragent.isMobile);
});
app.listen(3000);
João Pimentel Ferreira
  • 14,289
  • 10
  • 80
  • 109
  • If using Typescript, make sure to import `@types/express-useragent` in your package so that `Request` type is correctly extended – Gibolt Jul 14 '21 at 23:27
  • 2
    It seems that `ua-parser-js` is the standard library for parsing user-agent strings now. `express-useragent` hasn't been updated in 3 years at this point. https://www.npmjs.com/package/ua-parser-js – SamB Apr 07 '23 at 20:34