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

To geolocate a request in Rails, read the candidate client address 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 GeoIP database or hosted service. Treat the result as approximate country or regional context—not a person’s address or proof of where they are.

How does IP geolocation work in Rails?

There are two separate steps. First, Rails determines a request IP from the connection and forwarded headers, taking configured trusted proxies into account. Then a geolocation database or service maps that IP to available fields such as country, subdivision, city, time zone, or coordinates. The lookup does not reveal a reliable street address or identify a household.

  1. Obtain the candidate client IP from request.remote_ip.
  2. Check that the value is a public IP address suitable for lookup; local and private-network addresses will not provide ordinary visitor geolocation.
  3. Pass it to a local GeoIP reader or a hosted geolocation client.
  4. Handle missing records and lookup errors, and use only the location fields that are present.
  5. Present the result as approximate context.

Rails documents ActionDispatch::Request#remote_ip as the request-level client IP accessor. It is generally provided by ActionDispatch::RemoteIp; it is not a guarantee that every deployment’s proxy chain is configured correctly.

How do I get a user’s location from their IP address in Rails?

Use a local GeoIP database

MaxMind’s maxmind-geoip2 Ruby library supports reading a local database. A local lookup avoids making a network request for each visitor, but the application must have the database file available and keep it updated. The following is a compact service-object pattern; set the database path to the database edition and location you actually install.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
require "maxmind/geoip2"

class IpGeolocation
  def initialize(database_path: Rails.root.join("db", "GeoLite2-City.mmdb"))
    @reader = MaxMind::GeoIP2::Reader.new(database_path.to_s)
  end

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

    record = @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
  end
end

Create and reuse the reader rather than reopening the database for every request; the library documentation recommends reusing it. In a Rails app, initialize the service in an appropriate lifecycle-managed place and ensure the database file is present in each runtime environment. Check the installed gem’s documentation for exact class and method details for the version you use.

A controller can call the service after obtaining the Rails IP:

def show
  @visitor_location = IpGeolocationService.lookup(request.remote_ip)
end

Keep lookup out of views and avoid treating a missing record as an exceptional user-facing failure. If an address is absent from the selected database, return no location or a country-only fallback that your application can safely support.

Use MaxMind’s hosted web service

The MaxMind Ruby client also supports hosted GeoIP2 and GeoLite web-service requests. It accepts an account ID and license key; reuse the client and handle its structured exceptions. A hosted lookup avoids managing the local database file, but requires network access and credentials, and puts the queried IP into a third-party request. Consult the official Ruby library documentation for current construction and lookup syntax, and the web-service documentation for the selected service’s current request details and terms.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #2
Sale
HTML and CSS: Design and Build Websites
  • HTML CSS Design and Build Web Sites
  • Comes with secure packaging
  • It can be a gift option

Choose a hosted call when you prefer the provider to manage the lookup infrastructure; choose a local reader when you need the lookup to run from a database file under your deployment’s control. Those are operational trade-offs, not evidence of a universal latency, cost, or accuracy winner.

How should Rails handle proxies and forwarded IP headers?

When a request passes through a load balancer, CDN, or reverse proxy, the TCP peer Rails sees may be that intermediary rather than the visitor. Proxies may add forwarding headers, and Rails uses its trusted-proxy configuration to select an address from the chain. Configure that trust list for the actual infrastructure in front of the app.

  • Use request.remote_ip as Rails’ candidate address rather than reading X-Forwarded-For directly.
  • Do not treat request.ip or an arbitrary request header as universally authoritative.
  • Do not trust forwarded values from every source. If an untrusted client can supply a header Rails accepts, the apparent client IP can be spoofed.
  • Check the proxy chain and trusted-proxy settings for your Rails release and hosting platform.

The Rails 7.1 middleware documentation specifically warns that trusting forwarded headers without the expected proxy configuration can make client IP values spoofable. Refer to the Rails 7.1 RemoteIp documentation for that version’s details, and use documentation matching your deployed Rails version.

Which lookup mode should I choose?

Consideration Local database Hosted web service
Where lookup runs In your Rails process using a database file. At the provider, reached over the network.
Operational need Manage the file and its updates. Maintain network access and account credentials.
Failure cases Missing address record or invalid database file. Network and provider errors, reported through the client’s structured exceptions.
Privacy consideration Lookup can remain within your application environment, subject to your database and deployment handling. The queried IP is sent to the provider; review its current privacy policy and terms.
Performance, price, accuracy winner Not established as a general winner by the cited documentation. Not established as a general winner by the cited documentation.

MaxMind offers GeoLite in downloadable database and web-service formats. Its coverage notes that its databases cover public IPv4 and IPv6 addresses in use worldwide, while coverage and accuracy vary. Almost all IP addresses have at least a country association, but some have no region or city data, and many have no postal data. See the GeoLite documentation and coverage information for the product and current details.

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

What location information can you trust?

MaxMind states that IP geolocation is inherently imprecise. It warns that a location should not be used to identify a particular address or household. A city-level record may include an accuracy radius, and it may omit city, subdivision, postal, or other fields altogether. Read and store only fields your chosen product actually returns.

MaxMind’s support page gives a location at 42.1293, -72.7522 with a 100 km accuracy radius as an example. That is an illustrative vendor example, not a universal error bound or a statistic for all lookups. The vendor says precision can range from 5 km to hundreds of kilometers and cautions against assuming that a coordinate is the center of the actual area. See MaxMind’s accuracy explanation.

Results may reflect where end users are known to be located, or in some cases the country where an IP network is registered. VPNs, shared networks, mobile routing, and other network arrangements can make network location differ from a user’s physical location. Use IP location for broad personalization, analytics, or as one input to a workflow—not as sole evidence for a consequential decision or physical-presence claim.

MaxMind’s customer-use restriction says its products and services may not be used to attempt to identify a specific household, individual, or street address, or to encourage others to do so. See its restrictions on IP geolocation. Review the applicable provider’s current terms before using location data.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #4
Sale
Web Design with HTML, CSS, JavaScript and jQuery Set
  • Brand: Wiley
  • Set of 2 Volumes
  • A handy two-book set that uniquely combines related technologies Highly visual format and accessible language makes these books highly effective learning tools Perfect for beginning web designers and front-end developers

What should you consider for privacy?

A hosted geolocation request exposes the queried IP to the 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 MaxMind privacy policy and the terms for the specific product before sending request data. Your own retention, disclosure, and consent obligations depend on your application and applicable law; do not infer them from the lookup library alone.

Or skip the browser setup

If your workflow also needs a screenshot of a page, ScreenshotNeo is a website screenshot API and MCP server for developers. It is separate from IP geolocation: it captures a URL as an image or PDF rather than mapping an IP to a location.

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 docs for the API and available options. It removes cookie and consent banners, newsletter popups, and chat widgets before capture; bot checks, blank pages, failed loads, timeouts, and cache hits are not billed. Its MCP server provides take_screenshot, get_page_info, and capture_pdf for AI agents and MCP clients. The free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000. Sign up free for 1,000 screenshots a month, with no card.

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

Troubleshooting common failures

request.remote_ip returns the proxy address

Inspect the actual forwarding chain from your load balancer or reverse proxy, then configure Rails to trust the proxies that really sit in front of the app. Do not fix this by accepting arbitrary client-supplied forwarding headers; that can permit spoofing. Confirm the behavior against documentation for your Rails version and hosting configuration.

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

The lookup returns no record or no city

The address may not be represented in the selected database, or the product may not provide city-level data for it. Treat absent fields as normal, preserve a country-only result where available, and do not substitute a guessed city.

The local reader rejects the database

An invalid-database error indicates that the reader could not use the supplied file. Confirm that the path points to a valid database compatible with the reader, that deployment includes the file, and that the process can read it. Replace or update the file using the provider’s documented process.

A hosted request raises an exception

Check account ID and license key configuration, network connectivity, and the provider’s error details. Handle service exceptions so an unavailable lookup does not break the main request path; use a fallback appropriate to the feature, such as no location or a previously safe result. Avoid logging credentials or retaining IPs longer than your application needs.

Local development produces no useful location

Requests from localhost or private network addresses do not represent a public visitor IP for ordinary geolocation. Test with a public IP in a controlled environment, and ensure test data cannot be mistaken for a real visitor location.

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 home address?

No. IP location is approximate and should not be used to identify a person, household, or street address.

Does every IP address have a city result?

No. City and subdivision fields can be missing even when a country association is available.

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.