Geolocation
Add IP-based geolocation to track where your users log in from. This enables impossible travel detection, new-location MFA triggers, and login location analytics. nauth-toolkit integrates with MaxMind GeoIP2 for fast local lookups (sub-millisecond, no API calls).
Prerequisites
- A working auth setup (Quick Start)
- A free MaxMind account
Step 1: Install
yarn add @maxmind/geoip2-node
Step 2: Get MaxMind Credentials
- Sign up at MaxMind (free GeoLite2 account)
- Generate a license key from your account dashboard
- Note your account ID (found in account settings)
Step 3: Configure
{
geoLocation: {
maxMind: {
licenseKey: process.env.MAXMIND_LICENSE_KEY,
accountId: parseInt(process.env.MAXMIND_ACCOUNT_ID || '0', 10),
autoDownloadOnStartup: true,
},
},
}
For production, manage database files externally and skip downloads:
{
geoLocation: {
maxMind: {
dbPath: '/app/data/maxmind',
skipDownloads: true,
},
},
}
| Option | Type | Default | Description |
|---|---|---|---|
licenseKey | string | Required | MaxMind license key for downloading databases |
accountId | number | Required | MaxMind account ID for downloading databases |
dbPath | string | System temp | Directory where .mmdb files are stored |
autoDownloadOnStartup | boolean | false | Download databases on server startup |
editions | string[] | ['GeoLite2-City', 'GeoLite2-Country'] | Which MaxMind databases to download |
skipDownloads | boolean | false | Skip downloads, use existing files only |
Only enable autoDownloadOnStartup if you're using a distributed storage adapter (Redis/Database). Otherwise, multiple servers may try to download simultaneously.
Step 4: Enable Adaptive MFA (Optional)
Geolocation data powers Adaptive MFA, automatically requiring two-factor authentication for logins from new or suspicious locations:
{
mfa: {
enabled: true,
enforcement: 'ADAPTIVE',
adaptive: {
triggers: ['new_device', 'new_ip', 'new_country', 'impossible_travel'],
riskLevels: {
low: { maxScore: 20, action: 'allow', notifyUser: false },
medium: { maxScore: 50, action: 'require_mfa', notifyUser: true },
high: { maxScore: 100, action: 'require_mfa', notifyUser: true },
},
},
},
geoLocation: {
maxMind: {
licenseKey: process.env.MAXMIND_LICENSE_KEY,
accountId: parseInt(process.env.MAXMIND_ACCOUNT_ID || '0', 10),
},
},
}
Risk factors that use geolocation:
new_country--- Login from a country the user hasn't used beforeimpossible_travel--- Geographic distance/time anomaly detectednew_ip--- Login from a new IP address (uses country/city for context)
Updating the GeoIP Database
GeoLite2 databases are updated monthly. For production, use MaxMind's geoipupdate tool:
# Install
apt-get install geoipupdate # Debian/Ubuntu
brew install geoipupdate # macOS
# Configure (/etc/GeoIP.conf)
# AccountID YOUR_ACCOUNT_ID
# LicenseKey YOUR_LICENSE_KEY
# EditionIDs GeoLite2-City GeoLite2-Country
# Run
geoipupdate -d /app/data/maxmind
After external updates, reload databases without restarting:
import { Injectable } from '@nestjs/common';
import { Cron } from '@nestjs/schedule';
import { GeoLocationService } from '@nauth-toolkit/nestjs';
@Injectable()
export class GeoUpdateService {
constructor(private readonly geoLocationService: GeoLocationService) {}
@Cron('0 1 * * *') // Daily at 1 AM
async reloadDatabases(): Promise<void> {
await this.geoLocationService.reloadGeoLocationDatabaseFromDisk();
}
}
Use reloadGeoLocationDatabaseFromDisk() when files are managed externally. It reloads from disk without downloading, safe to call frequently even with skipDownloads: true.
What Data is Captured
When enabled, every session and authentication event includes:
{
country: 'US',
city: 'San Francisco',
latitude: 37.7749,
longitude: -122.4194,
}
This data is stored in session records, audit logs, and is available via ClientInfoService in request context.
IP addresses are personal data under GDPR. Disclose geolocation tracking in your privacy policy and consider letting users view their login locations.
Troubleshooting
Geolocation not working:
- Verify
@maxmind/geoip2-nodeis installed - Check that database files exist in
dbPath - Check logs for MaxMind initialization errors
- Verify license key and account ID are correct
Database download fails:
- Verify credentials are correct
- Check network connectivity to MaxMind servers
- Ensure
dbPathdirectory is writable
No location data in sessions:
- Verify geolocation is configured in auth config
- Check that database files are loaded (service logs)
What's Next
- MFA --- Use geolocation for adaptive MFA risk scoring
- Audit Logs --- Location data is captured in every audit record
- Configuration --- Complete geolocation configuration reference
- Rate Limiting --- Brute-force protection and throttling