Retrieve client ip in custom middleware , enabled context variable but still didn't get the ip address

i am trying to retrieve the ip address from request using a custom middleware , but i am not able to retrieve it as there is no header coming like remote address through the request, please help me to fix this as i am new to tyk, i will share the middleware details below

var myMiddleware = new TykJS.TykMiddleware.NewMiddleware({});

myMiddleware.NewProcessRequest(function (request) {
var thisIP = request.remote_addr ? request.remote_addr : “unknown”;
// Set auth header
request.SetHeaders[“x-tyk-authorization”] = thisIP;

var keyDetails = {
allowance: 333,
rate: 6,
per: 60,
expires: 0,
quota_max: 1000,
quota_renewal_rate: 2592000,
access_rights: {
“node-api-unauth”: {
api_name: “Mainnet API (Unauthorized)”,
api_id: “node-api-unauth”,
versions: [“Default”],
},
},
org_id: “default”,
};

TykSetKeyData(thisIP, JSON.stringify(keyDetails), 1);

return myMiddleware.ReturnData(request);
});

// Ensure init with a post-declaration log message
log(“IP rate limiter JS initialised”);

Welcome to Tyk Community @Athira_CA and thank you for posting your question.

In order to get the IP address of your client, you need to use context variable remote_addr into your request header

Then retrieve this request header in your custom middleware. You can use request.Headers["X-Remote-Addr"] in Javascript Middleware or you can refer to this other community post to use it in Python middleware.

Note:
- Make sure you set enable_context_vars to true in your API definition.
- Context Variables can only be used in 3 Middleware plugins : URL Rewriter, Modify Headers and Body Transforms.

if i use traefik then should i able to get the ip address in the middleware without using this context variable?

If traefik can help retrieve it in the header. then yes. You can use that. An alternative is to use a front-end proxy like nginx.

You can refer to our knowledge base article about the same ask

Hello, you can also use the X-Forwarded-For header to identify the client’s IP address. This is only valid if Nginx or another load balancer/firewall ensures that the IP address is overwritten with the client’s IP.

1 Like