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.
Asked
Active
Viewed 1.3k times
5
-
You could use an `npm` package to grab detailed information for each device that visits your website - https://www.npmjs.com/package/bowser – goto May 12 '20 at 17:33
-
Check this link https://stackoverflow.com/a/22286027/8159775, it should help! – Alex K - JESUS first Feb 26 '21 at 12:06
2 Answers
5
@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,464
- 3
- 16
- 32
5
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
- 11,565
- 7
- 67
- 91
-
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