How to detect if user using tor in Node - Javascript

How to identify if the request is coming from tor browser/agent?

wonder

As you know tor uses multiple nodes(IPs), fortunately, we have a list of mostly known exit nodes of Tor, so we can check and find if it is a Tor browser/agent.

First, you need to identify what the IP address request is coming from

example with express:

const express = require('express');
const app = express();

app.get('/', (req, res) => {
  const clientIp = req.ip; // or req.ips[0] for the first IP in the chain
  console.log(clientIp);
  res.send('Hello from the server!');
});

app.listen(3000, () => {
  console.log('Server listening on port 3000');
});

Here is the list of nodes used by tor:

[
  "176.10.99.200",
  "109.70.100.28",
  "51.75.64.23",
  "82.221.128.191",
  "199.249.230.182",
  "199.249.230.173",
  "199.249.230.165",
  "199.249.230.176",
  "199.249.230.117",
  "185.220.101.155",
  "185.220.101.145",
  "185.220.101.140",
  "185.220.101.166",
  "185.220.101.171",
  "185.220.101.160",
  "185.220.101.168",
  "185.220.101.170",
  "185.220.101.172",
  "185.220.101.161",
  "185.220.101.167",
  "185.220.101.173",
  "185.220.101.162",
  "185.220.101.169",
  "185.220.101.163",
  "185.220.101.153",
  "185.220.101.165",
  "185.220.101.164",
  "185.220.101.174",
  "185.220.101.176",
  "185.220.101.184",
  "185.220.101.187",
  "185.220.101.188",
  "185.220.101.181",
  "185.220.101.154",
  "185.220.101.191",
  "185.220.101.183",
  "185.220.101.186",
  "185.220.101.180",
  "185.220.101.132",
  "185.220.101.179"
]

Full list here 

 So, if the request comes from any of these IPs, then it's a Tor agent/browser.

To check the IP, you can use this code

//typescript

function isTor(ip : string): boolean {
    
        if (isIP(ip)) {
            if (fileData.indexOf(ip.toString()) !== -1) {
                return true;
            } else {
                return false;
            }   
        } else {
            console.log("invalid");
        }
  
};

function isIP(ip: string): boolean {
  const ipv4Regex = /^(\d{1,3}\.){3}\d{1,3}$/;
  return ipv4Regex.test(ip);
}

or you can use this library : is-tor