how to determine a client operating system in Node.js

Viewed 2958

I'm trying to implement 2FA in my app during login process, and I wish to send them the operating system and name of device of which the login request is coming from, but I have tried searching around for a solution to determine this, the one I found was only for the backend(nodejs os module). Is there any npm module or way around for me to archive this.

2 Answers

Use Sniffr package to get information from the user-agent from headers in request...

enter image description here

I wish to send them a country of which the login request is coming from

IMO, this can/should be determined on the server-side (using something like node-geoip.)

As for detecting the client operating system, you need to parse the User-Agent request header. The module Tilak Putta suggested can also be used in the back-end.


Example:

const http = require('http');

const geoip = require('geoip-lite'); // npm install --save geoip-lite -- have a look at https://github.com/bluesmoon/node-geoip to know how to update the datafiles
const Sniffr = require("sniffr"); // npm install --save sniffr
const requestIp = require('request-ip'); // npm install --save request-ip

const HOST = process.env.HOST || '0.0.0.0';
const PORT = process.env.PORT || 1337;

const server = http.createServer((req, res) => {
  const userAgent = req.headers['user-agent'];
  const s = new Sniffr();
  s.sniff(userAgent);

  const clientIp = requestIp.getClientIp(req);
  const geo = geoip.lookup(clientIp); // will be set to null if server is accessed locally

  res.statusCode = 200;
  res.setHeader('Content-Type', 'application/json');
  res.end(JSON.stringify({
    ...s,
    clientIp,
    geo
  }, null, 2));
});

server.listen(PORT, HOST, () => {
    console.log(`Server is listening on http://${HOST}:${PORT}`);
});
Related