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.
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.
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.
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.
@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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With