Skip to content

Commit

Permalink
Merge pull request #52 from pbojinov/fastify-support
Browse files Browse the repository at this point in the history
Add fastify support
  • Loading branch information
pbojinov authored Jun 1, 2022
2 parents 37f7aa3 + b4daaf4 commit 56ca5ae
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ The user ip is determined by the following order:
10. `req.socket.remoteAddress`
11. `req.connection.socket.remoteAddress`
12. `req.info.remoteAddress`
13. `request.raw` (Fastify)

If an IP address cannot be found, it will return `null`.

Expand Down
6 changes: 6 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,7 @@ function getClientIp(req) {
}

// Remote address checks.
// Deprecated
if (is.existy(req.connection)) {
if (is.ip(req.connection.remoteAddress)) {
return req.connection.remoteAddress;
Expand All @@ -141,6 +142,11 @@ function getClientIp(req) {
return req.requestContext.identity.sourceIp;
}

// Fastify https://www.fastify.io/docs/latest/Reference/Request/
if (is.existy(req.raw)) {
return getClientIp(req.raw);
}

return null;
}

Expand Down
20 changes: 20 additions & 0 deletions test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -544,3 +544,23 @@ test('request to Google Cloud App Engine (x-appengine-user-ip)', (t) => {
});
});
});

test('Fastify (request.raw) found', (t) => {
t.plan(1);
const found = requestIp.getClientIp({
raw: {
headers: {
forwarded: '91.203.163.199',
},
},
});
t.equal(found, '91.203.163.199');
});

test('Fastify (request.raw) not found', (t) => {
t.plan(1);
const found = requestIp.getClientIp({
raw: {},
});
t.equal(found, null);
});

0 comments on commit 56ca5ae

Please sign in to comment.