Getting Request's Public Ip4 Address (Express)

Issue

I am trying to make sure that the user who tries to access my api has a certain network pr ip4 ip address

const express = require('express');
const app = express();
const router = express.Router();

router.get('/api/v1/password/:passwordslug', (req,res) => {
  const ip = req.headers['x-forwarded-for'] || req.socket.remoteAddress;
    if(ip !== 'someip') {
        return res.json({ error:`You do not have access to this data` })
    } else {
        //res.json data
    }

});

app.use('/', router);
app.listen(5000);

I have this code right now, but ip keeps returning

::1

How do I get the user’s or request’s network IP address so I can whitelist it on my side (the same way mongodb cloud does)

I am looking for their machine’s ip4 address.

How should I get this?

Solution

It looks like you are connecting to your node from localhost – both client and server are on the same server. Try to run your nodejs on remote server, it should start returning real ip

Answered By – Paul D Martini

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published