Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

In Rails, start with request.remote_ip, verify that Rails trusts only the proxies actually in front of your app, then look up that public IP in a local geolocation database or with a hosted service. Treat the result as approximate location context—not a person’s address or proof of where they are.

How IP geolocation works in a Rails request

There are two separate steps. First, Rails selects a candidate client IP from the request and the proxy chain. Second, a geolocation database or service maps that IP to available attributes such as country, subdivision, city, coordinates, or time zone. A successful lookup may return only some of those fields.

The result describes an IP network as represented by the provider’s data. It does not identify the person using the connection, and it should not be presented as an exact physical location. A visitor’s country can be useful for choosing a default locale or offering region-specific content; a city result is not a reliable basis for treating someone as present at a particular street address.

Get the candidate client IP safely

Use Rails’ request accessor

In a controller or other request-aware code, begin with request.remote_ip. Rails documents ActionDispatch::Request#remote_ip as the client IP address, generally provided through ActionDispatch::RemoteIp. It is a Rails-selected value, not a guarantee that every deployment has correctly configured its proxy chain.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Sale
Air Tags for Android,Air Tags-4 Pack Android,Air Tracker Tags with 4 Case,2 Year Battery Life,Google & Apple Find Trackers for Google'S Find Hub App & Apple Find My,IP65 Waterproof Luggage Tracker
  • 📱 Global Cloud Positioning – Works with both Google's Find Hub and Apple Find My (Not for GPS & Huawei)
  • 📢 Loud Alert Sound – Built-in speaker with up to 105dB for quick locating
  • 🔋 Far Superior Battery Life – Up to 2 years battery life on Android and ios
  • 💧 IP65 Waterproof – It provides protection against rainwaterand splashes
  • 🔊 Visualize Distance – Visualize distance using UWB technology within Bluetooth range, allowing you to immediately see the distance
class LocationsController < ApplicationController
  def show
    @client_ip = request.remote_ip
  end
end

Do not substitute a raw X-Forwarded-For value as though it were inherently trustworthy. Forwarded headers can contain multiple addresses, and a client may be able to supply header values unless the trusted proxy arrangement is configured correctly. Likewise, do not assume that request.ip and request.remote_ip mean the same thing for your deployment.

Check the actual proxy chain

Identify every component that can forward traffic to Rails: for example, a load balancer, reverse proxy, or hosting platform. Configure Rails’ trusted proxy list for that real chain, following documentation for the Rails release you run. Rails 7.1 documentation specifically warns that trusting forwarded headers without the expected proxy setup can make client IP values spoofable. The current request API and versioned middleware documentation are not interchangeable; consult the version matching your app.

Test this in the deployed topology, not only on localhost. A direct local request may expose a loopback or development address, while production requests pass through one or more proxies. If the value is your load balancer’s address, examine which headers the proxy sends and whether Rails recognizes that proxy as trusted; do not fix it by trusting every forwarded address.

Choose a local database or hosted lookup

Approach Where lookup runs What you operate When it can fit
Local database Inside your Rails process using a downloaded database file Store and update the database file; reuse a reader object When you want lookups without making a network request to a geolocation provider for each lookup
Hosted web service At the provider, called over the network by your app Network access, credentials, and error handling; reuse the client When you prefer the provider’s web-service integration over managing a local database file

This is an operational comparison, not a general performance or total-cost verdict. The available documentation does not establish a universal latency, cost, or accuracy winner. Product fields and service terms vary, so compare the specific offering and check current provider documentation before choosing.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #2
Sale
Apple AirTag (2nd Generation) - 4 Pack: Tracker for Keychain, Wallet, and More; Locator with Sound; Simple One-Tap Setup with iPhone or iPad; Key Finder with up to 1.5X Precision Finding Range*
  • FIND YOUR ITEMS ON FIND MY — AirTag (2nd generation) helps you keep track of what matters. Attach one to an item you want to keep track of using the Find My app.*
  • EXPANDED PRECISION FINDING ON IPHONE AND APPLE WATCH — Get step-by-step directions to your lost item on iPhone and, now, Apple Watch.*
  • ENHANCED SPEAKER — With a 50% louder speaker and a new, distinctive chime, it’s easier than ever to hear and find AirTag.*
  • PING FROM FAR AND WIDE — Upgraded Ultra Wideband and Bluetooth chips allow you to find your items from even farther away than ever before.*
  • SHARE ITEM LOCATION — Share AirTag location access temporarily and securely with trusted contacts, third parties, or over 50 airline partners if you lose something important.

Use a local MaxMind database in Ruby

MaxMind’s maxmind-geoip2 Ruby library supports local database reads as well as hosted requests. For a database lookup, construct a MaxMind::GeoIP2::Reader with the path to the database file and reuse that reader rather than rebuilding it for each request. The example below shows the shape of the lookup; provide a database file you are entitled to use and keep it updated according to your data source’s process.

require "maxmind/geoip2"

GEOIP_READER = MaxMind::GeoIP2::Reader.new(
  "path/to/your/GeoIP2-City.mmdb"
)

def location_for(ip)
  record = GEOIP_READER.city(ip)

  {
    country: record.country.name,
    country_iso_code: record.country.iso_code,
    subdivision: record.subdivisions.first&.name,
    city: record.city.name,
    latitude: record.location.latitude,
    longitude: record.location.longitude,
    accuracy_radius_km: record.location.accuracy_radius
  }
rescue MaxMind::GeoIP2::AddressNotFoundError
  nil
rescue MaxMind::GeoIP2::InvalidDatabaseError => e
  Rails.logger.error("GeoIP database is invalid: #{e.message}")
  nil
end

Exact class and field availability should be checked against the version of the gem and database you install. A city-oriented record can lack a city, subdivision, coordinate, or other geographic value for a particular address. Avoid assuming every nested field exists simply because it exists in an example.

Handle an address-not-found result as an ordinary missing-data case, not as a reason to break the request. An invalid-database error is an operational fault: log it, verify the database path and file integrity, and restore or update the file through your normal deployment process. Do not turn either condition into a fabricated location.

Use a hosted MaxMind web service

MaxMind’s Ruby client can make web-service requests using an account ID and license key. Its documentation recommends reusing the client and describes structured exceptions for errors. Keep credentials out of source control, load them from your application’s secret-management mechanism, and define a fallback when the provider cannot be reached.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
Sale
LandAirSea 54 GPS Tracker - Made in the USA from Domestic & Imported Parts. Long Battery, Magnetic, Waterproof, Global Tracking. Subscription Required
  • Premium GPS Tracker — The LandAirSea 54 GPS tracker provides accurate global location, real-time alerts, and geofencing. Easily attaches to vehicles, ATVs, golf carts, or other critical assets.
  • Track Movements in Real-Time — Track and map (with Google Maps) in real-time on web-based software or our SilverCloud App. Location updates as fast as every 3 seconds with historical playback for up to 1 year.
  • Powerful & Discreet — The motion-activated GPS tracker will sleep when not in motion for extended periods, preserving the battery life. The ultra-compact design and internal magnet create the ultimate discreet tracker.
  • Lifetime Warranty — This GPS tracker is built to last. LandAirSea, a USA-based company and pioneer in GPS tracking offers a unconditional lifetime warranty that covers any manufacturing defects in the device encountered during normal use.
  • Subscription Required — Affordable subscription plans are required for each device. Fees start as low as $9.95 a month for annual plans and $19.95 for monthly plans. No contracts, cancel anytime for a hassle-free experience.
require "maxmind/geoip2"

GEOIP_CLIENT = MaxMind::GeoIP2::Client.new(
  account_id: ENV.fetch("MAXMIND_ACCOUNT_ID"),
  license_key: ENV.fetch("MAXMIND_LICENSE_KEY")
)

def hosted_location_for(ip)
  record = GEOIP_CLIENT.city(ip)

  {
    country: record.country.name,
    country_iso_code: record.country.iso_code,
    city: record.city.name,
    latitude: record.location.latitude,
    longitude: record.location.longitude
  }
rescue MaxMind::GeoIP2::AddressNotFoundError
  nil
rescue MaxMind::GeoIP2::Error => e
  Rails.logger.warn("GeoIP lookup failed: #{e.class}: #{e.message}")
  nil
end

Use the official library’s current API documentation for the exact constructor, lookup method, exception classes, and product-specific response fields for the gem version you select. MaxMind also documents a REST interface, but its Ruby client is the documented Ruby integration. GeoLite is MaxMind’s free geolocation offering in downloadable-database and web-service formats; verify the current eligibility, terms, and available products directly with MaxMind.

Return useful data without making a request fragile

Geolocation is usually enrichment, not a prerequisite for serving a page. A database miss, absent city field, or temporary web-service error should normally produce a neutral fallback rather than a failed page. Keep the lookup boundary small so the rest of the application can work with either a result or no result.

def country_code_for(ip)
  return nil if ip.blank?

  location_for(ip)&.fetch(:country_iso_code, nil)
end

Use only the fields the feature needs. Country-level behavior can often work without coordinates or a city. If you use a hosted service, consider the effect of making a network request during a page request and decide how the application should behave when that request is slow or unavailable. The available sources do not establish a universal timeout value or performance guarantee; choose limits appropriate to your own request budget and provider terms.

Accuracy, coverage, and responsible use

City-level data is not a pin on a map

MaxMind says IP geolocation is inherently imprecise and warns that a location should not be used to identify a particular address or household. Its support documentation gives one example coordinate with a 100 km accuracy radius; that is an illustrative record, not a universal error bound or a statistic for all lookups. MaxMind says precision can range from 5 km to hundreds of kilometers and warns that the reported location should not be assumed to sit at the center of the area.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #4
RGIMF GPS Tracker for Vehicles No Subscription, iOS & Android Dual System
  • 【Dual-System Compatibility】Our car tracker tags work seamlessly with both iOS and Android systems, covering mainstream devices. This Bluetooth tracking device pairs effortlessly with Apple's “Find My” or Google's “Find Hub” app without subscription fees. (Note: Cannot pair with iOS and Android devices simultaneously.)
  • 【Real-time Undetectable GPS tracker】Our small vehicle tracker GPS allows global tracking and location. When there are a large number of iOS & Android devices nearby, location updates are very accurate and happen in real time, recording the location of your item at any time.
  • 【Car Tracker No Subscription】The GPS trackers no subscription required or monthly fees. You can use it for a long time with just a one - time purchase. Our smart item finders locator also suitable for tracking pets, vehicles, keys, the elderly and children.
  • 【High-Volume Alert】Close-Range Search—The app displays the distance to lost items to narrow your search area. Trigger an 80-100 decibel alert from the built-in speaker via Google Find Hub or Apple's Find My app—ideal for locating items in cluttered spaces like sofa crevices or drawers. Even if the item is out of sight, a single button press activates the item finders' alert.
  • 【Simple Setup】This location tracker for Android or iOS pairs effortlessly with Android or iOS devices in seconds, automatically adapting to your chosen platform (connects to only one platform at a time). An instruction manual is included. If you're concerned about understanding it, you can watch the video tutorial on our page.

The vendor says location may represent where end users are known to be, or in some cases the country where an IP network is registered. VPNs, mobile routing, shared connections, and other network arrangements can also make a network’s apparent location differ from a user’s actual location; do not treat the result as proof of presence.

Some records have less detail than others

MaxMind says almost all IP addresses have at least a country association, while some lack region or city data and many lack postal data. Its coverage information describes public IPv4 and IPv6 addresses in use worldwide, while noting that coverage and accuracy vary. City and subdivision names or coordinates are therefore optional data, not guaranteed properties of every lookup. Country-only products also provide a different level of detail from city-level products.

Depending on the product, records may include country, subdivision, city, confidence, area, time zone, EU, and Anycast fields. Check the selected product’s schema and handle absent values; do not infer a missing city or postal code from a country result.

Do not use a lookup to identify a household

MaxMind explicitly prohibits its customers from using its products or services to attempt to identify a specific household, individual, or street address, or encouraging others to do so. More broadly, IP geolocation is not a substitute for a user-provided address or a verified location signal. For any consequential decision, use an appropriate method and provide a fair fallback when location data is missing or uncertain.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Best Value
Bouncie GPS Tracker for Vehicles with Real-Time Location
  • Real-Time GPS Tracker Device for Vehicles — Ideal for personal use or fleet management, this car GPS tracker provides up-to-the-minute location updates. Our car tracking device also provides unlimited trip history, including a detailed route history
  • Driving Insights — Our OBD tracker for cars monitors speed, acceleration, hard braking, idle time, and more. This versatile family and fleet GPS tracker for cars also helps improve road safety by sending alerts in response to unsafe driving practices
  • Vehicle Health — Unlike other vehicle tracking devices, our car tracker device continuously monitors diagnostic engine data, alerting you to potential maintenance issues, so you can avoid downtime and keep fleet and family vehicles in peak condition
  • Geo-Fencing & Accident Detection — Set up geo-fences to receive notifications when your vehicle enters or exits designated areas; Equipped with advanced sensors and software, this vehicle tracker device instantly detects impacts and sends SMS alerts
  • Easy To Install & Low Monthly Subscription — Our OBD GPS tracker for vehicles plugs directly into OBD2 ports and works on most vehicles 1996 and newer; $9.65 monthly subscription required - no hidden activation or return fees - cancel anytime

Consider data handling before sending an IP to a provider

MaxMind’s privacy policy says IP addresses submitted to GeoIP2 and GeoLite web services may be used to improve some of its services, including GeoIP products and minFraud. Review the provider’s current privacy policy and service terms before sending request data, and consider whether your own privacy disclosures and retention practices need to account for the lookup.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Why does request.remote_ip return my proxy IP?

Rails is selecting from the request and proxy information it sees. If the proxy chain is not represented correctly in trusted-proxy configuration, Rails may select an intermediary address rather than the originating client address. Confirm which proxy forwards the request, which headers it sets, and how the Rails version in use evaluates trusted proxies. A raw forwarded header is not a safe shortcut: trusting unverified client-supplied values can allow spoofing.

Or skip the browser setup

ScreenshotNeo is a website screenshot API and MCP server, not an IP geolocation service; it does not replace the Rails IP lookup above. It can be useful alongside a Rails project when you also need website screenshots. One GET request captures a URL as an image or PDF. For example, the cURL call below saves a WebP screenshot:

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

See the ScreenshotNeo API documentation for the API details. ScreenshotNeo removes cookie banners, newsletter popups, and chat widgets before capture; bot checks, blank pages, and failed loads are not billed. Its MCP server lets AI agents take screenshots. The Free plan includes 1,000 screenshots per month with no card, and paid plans start at $5 for 3,000 shots. Learn about ScreenshotNeo, then sign up for 1,000 free screenshots a month with no card.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Frequently Asked Questions

Can IP geolocation identify a visitor’s exact address?

No. A lookup provides approximate network-location context, not a reliable street address or household identity.

Does every GeoLite result include a city?

No. City, subdivision, postal, and coordinate fields are not available for every IP record.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.