Skip to content

Commit

Permalink
fix: get appropriate client ip from nginx proxy using headers
Browse files Browse the repository at this point in the history
  • Loading branch information
Lim-Changi committed Sep 8, 2024
1 parent 3ea266a commit fb8e955
Showing 1 changed file with 5 additions and 2 deletions.
7 changes: 5 additions & 2 deletions src/visitor/service/visitor.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,12 @@ export class VisitorService {
const result: VisitorCountUpResponseDto = { Status: 'fail' };
try {
const ip = req.ip;
const realIp = req.headers['x-real-ip'] as string;
const forwardedFor = req.headers['x-forwarded-for'] as string;

const clientIp = realIp || forwardedFor || ip;
const userAgent = req.get('user-agent');
const uniqueUserInfo = `visitor-${userAgent}${ip}`;
const uniqueUserInfo = `visitor-${userAgent}${clientIp}`;

await this.cacheManager.set(uniqueUserInfo, 'visited', 24 * 60 * 60);

Expand All @@ -41,7 +45,6 @@ export class VisitorService {
const allVisitors = allKeys.filter((key: string) =>
key.includes('visitor-'),
);
console.log(allVisitors);

result.Count = allVisitors.length;
} catch (err) {
Expand Down

0 comments on commit fb8e955

Please sign in to comment.