Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node Js - Identify if the request is coming from mobile or non-mobile device

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.

like image 784
H.Mustafa Avatar asked May 12 '20 17:05

H.Mustafa


People also ask

What is the best way to detect a mobile device?

In summary, we recommend looking for the string “Mobi” anywhere in the User Agent to detect a mobile device. Like this: if (/Mobi/. test(navigator.

How do I know if I have mobile JavaScript?

To detect if the user is using a mobile device in JavaScript, we can use the userAgent property. This property is part of the navigator object and sent by the browser in HTTP headers. It contains information about the name, version, and platform of the browser.

Is node JS mobile code?

Node. js for Mobile Apps is a Node. js runtime that runs on Android and iOS, using the V8 JavaScript engine. It is very similar to a Linux build of Node, but with a few platform-specific tweaks and fixes.


2 Answers

@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.

like image 183
Melvin Abraham Avatar answered Sep 22 '22 16:09

Melvin Abraham


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);
like image 25
João Pimentel Ferreira Avatar answered Sep 20 '22 16:09

João Pimentel Ferreira