IP Geolocation in Google Tag Manager

Anwar Ahmed
By Anwar Ahmed Software Engineer
Posted on May 7, 2026 | 11 min read
IP Geolocation in Google Tag Manager
Back to All Tutorials

IP geolocation data is not available in Google Tag Manager by default. GTM can fire tags, manage pixels, and push events into the data layer, but it has no built-in way to resolve a visitor's IP address to a country, city, or region.

That's a problem if you need to run geo-targeted ad tags, personalize content by location, filter internal traffic, or comply with region-specific consent rules. Adding geolocation tracking to GTM requires an external API, and this tutorial shows you how to set it up.

This tutorial walks through setting up the official IP Geolocation custom template in Google Tag Manager. The template connects to the IP Geolocation API, fetches location and IP data for each visitor, and pushes it into the data layer where you can use it for triggers, variables, and tag logic.


TL;DR

  • Install the IP Geolocation template from the GTM Community Template Gallery
  • Enter your API key (free tier: 1,000 credits/day) or leave it blank on paid plans with Request Origins configured
  • The template pushes a geoData object into the data layer with IP, country, city, coordinates, currency, timezone, and more
  • Create Data Layer Variables to access individual fields like geoData.location.country_name or geoData.ip
  • Use a Custom Event trigger on the geoLocate event to fire geo-dependent tags

The template handles the API call, caches results in session storage to save credits, and supports both free and paid plan features including security data, user agent parsing, and hostname resolution.


Get Your API Key

You need an API key from ipgeolocation.io to use the template. For a quick start, see the Getting Started with IPGeolocation API Guide.

Sign up for a free account. The free plan includes 1,000 credits per day with no credit card required. Each standard geolocation lookup costs 1 credit. For higher-volume sites, paid plans start at a few dollars per month and unlock additional data modules like security intelligence, company data, and abuse contact details.

IPGeolocation.io signup form with full name, email, password, and privacy policy fields. Sign in with Google and Sign in with GitHub options

After signing up, your API key is on the dashboard. Copy it. You'll paste it into the GTM template configuration in the next step.

IPGeolocation.io dashboard showing the API key location and copy button

Securing your API key on paid plans: On the free plan, the API key is included in browser-side requests, which means it's visible to anyone inspecting network traffic. On paid plans, you can leave the API key field empty in GTM and instead restrict access through Request Origins in your dashboard. Add your domain (e.g., www.example.com), and the API will only accept calls from that origin. This keeps the key out of client-side code entirely.


Open your GTM container and go to Templates in the left sidebar. Under Tag Templates, click Search Gallery.

Google Tag Manager Templates workspace page displaying the Tag Templates section with the Search Gallery button for browsing community tag templates.

In the gallery search bar, type IP Geolocation. Select the template by devjfreaks (this is the official ipgeolocation.io template, built for the v3 API).

Community Template Gallery in Google Tag Manager showing search results for the IP Geolocation tag template by devjfreaks.

Click Add to workspace to import the template into your container.

Google Tag Manager Template Details panel for the IP Geolocation tag template with option to add the template to the current workspace.

Now go to Tags in the left sidebar and click New to create a tag.

Google Tag Manager Tags workspace interface showing the New button used to create a new tag configuration.

Click Tag Configuration, and in the side panel that appears, select IP Geolocation from your custom templates.

Google Tag Manager tag type selection screen displaying the IP Geolocation custom tag template in the Community Template Gallery.

Configure the Tag


1. API Key and Session Storage

Paste your API key from the ipgeolocation.io dashboard into the API Key field.

Enable Session Storage to cache the geolocation response in the visitor's browser session. This prevents duplicate API calls on subsequent page views within the same session, which reduces credit usage and improves page load performance.

Google Tag Manager IP Geolocation tag configuration screen showing API Key input field and session storage cache option.

On paid plans with Request Origins configured, you can leave the API key field blank.


2. Subscription Plan

Use the dropdown to select your plan type:

Free returns core geolocation data: IP, country, city, state, latitude, longitude, timezone, currency, and country metadata. You can filter the response using the Fields to Include and Fields to Exclude options.

Paid unlocks additional data modules. When you select Paid, a new configuration section appears with these options:

Google Tag Manager IP Geolocation tag configuration with Subscription Plan dropdown menu displaying Free and Paid plan options.

Hostname Resolution controls how the IP's hostname is resolved. "None" skips the lookup entirely. "Hostname" resolves from a cached database (fast but may not reflect recent DNS changes). "Live Hostname" performs a real-time DNS lookup (most accurate, adds latency). "Hostname with Live Fallback" uses the cache first and falls back to live DNS if nothing is found.

Include User Agent Data parses the visitor's User-Agent header and returns structured browser and OS details.

Include Security Data returns threat intelligence flags: VPN detection, proxy detection, Tor exit node, bot classification, and crawler identification. Useful for fraud prevention and compliance workflows.

Include Abuse Contact Data returns the abuse contact (name, email, address) for the IP's network, which is relevant for security teams investigating suspicious traffic.

Include DMA Code (US only) returns the Nielsen Designated Market Area code for US-based IPs. Useful for ad targeting aligned with broadcast media markets.

Include Geolocation Accuracy Radius returns an estimated accuracy radius in kilometers for the IP's coordinates.

Response Language translates location names (country, city, state) into your preferred language. Available languages include German, French, Spanish, Japanese, Chinese, Russian, Italian, Korean, Portuguese, Czech, and Persian. Defaults to English.

Google Tag Manager IP Geolocation tag settings page showing Paid Plan Options including hostname resolution, security data, user agent data, and geolocation accuracy settings.

4. Data Layer Settings

Two fields control how the geolocation data is pushed into the data layer:

Data Layer Variable Name defaults to dataLayer. If your site uses a custom data layer name (e.g., myDataLayer), change it here.

Custom Event Name defaults to geoLocate. This is the event name you'll use in Custom Event triggers to fire geo-dependent tags.

Google Tag Manager IP Geolocation tag configuration with Data Layer Settings enabled using the dataLayer variable and custom event name geoLocate.

If you change the data layer name, you also need to update it in the template permissions. Go to Templates > IP Geolocation the Template Editor will be opened, open Permissions > Accesses global variables, and replace dataLayer with your custom name. If these values don't match, the tag will fail silently.

Google Tag Manager Template Editor Permissions tab showing global variable access permissions for the dataLayer object.

5. Filter the API Response

You don't always need the full response. Two fields let you control which data comes back:

Fields to Include limits the response to specific fields. For example, entering location returns only the location object. Entering location.country_name returns just the country name. The IP address is always included automatically.

Fields to Exclude removes fields you don't need. For example, entering currency strips the currency object from the response.

Google Tag Manager IP Geolocation tag configuration with Filter Response Fields settings for including or excluding API response fields.

Filtering is worth doing. Smaller responses mean less data pushed into the data layer and marginally faster processing. If you only need country and city for ad targeting, exclude everything else.

For the full list of filterable fields, see the API filtering documentation.


6. Set the Trigger

Choose when the tag should fire. All Pages is the recommended default for most setups. With session storage enabled, the API is only called once per session regardless of how many pages the visitor loads.

If you want to defer the call, use a Window Loaded trigger instead. For single-page applications or specific landing pages, create a custom trigger that matches your requirements.


Using IP Geolocation Data in GTM

Once the tag fires, it pushes geolocation data into the data layer as a geoData object, using the event name you configured (default: geoLocate). From here, you can use the data in triggers, variables, and other tags.


1. Create Data Layer Variables

To access specific fields from the geoData object, create Data Layer Variables in GTM.

Country: Set the variable name to geoData.location.country_code2.

Google Tag Manager Variables configuration page showing a Data Layer Variable named geoData.location.country_code2.

Vpn: Set the variable name to geoData.security.is_vpn.

Google Tag Manager Variables configuration page showing a Data Layer Variable named geoData.security.is_vpn with boolean true/false conversion enabled.

Other commonly used variables include geoData.location.country_namegeoData.location.citygeoData.location.country_code2, and geoData.currency.code.


2. Create a Custom Event Trigger

To fire tags only after geolocation data is available, create a Custom Event trigger with the event name geoLocate.

Google Tag Manager Trigger Configuration page showing a Custom Event trigger named geoLocate with a condition matching country code value US.

Any tag that depends on geolocation data (remarketing pixels, consent banners, analytics events) should use this trigger instead of All Pages. This guarantees the geo data exists in the data layer before your tag tries to read it.


3. Practical Use Cases

Geo-targeted remarketing: Fire a Meta or Google Ads remarketing tag only for visitors from specific countries. Add a condition to your trigger: fire when geoData.location.country_code2 equals US (or whichever market you're targeting).

Region-specific consent logic: Use the country code variable to load different consent banners for EU vs. non-EU visitors. This lets you apply stricter consent flows where GDPR applies without burdening visitors in regions with lighter requirements.

Internal traffic filtering: If your team connects through a known IP range, compare geoData.ip against your office IPs using a Custom JavaScript variable. Flag matching visitors as internal traffic and exclude them from analytics or ad tags. Here's an example Custom JavaScript variable that returns true for internal IPs:

function() {
  var ip = {{DLV - geoData.ip}};
  if (!ip) {
    return false;
  }

  // Replace with your actual office IP addresses
  var internalIPs = [
    '203.0.113.10',
    '203.0.113.11',
    '198.51.100.25'
  ];

  return internalIPs.indexOf(ip) !== -1;
}

Name this variable something like "CJS - Is Internal Traffic" and use it as an exception condition on your analytics and ad tags.

GA4 events with location context: Fire a GA4 event tag on the geoLocate trigger and pass geoData.location.country_name and geoData.location.city as event parameters. This gives you location data tied to specific user actions, independent of GA4's built-in geo reporting.

Currency and language detection: Use geoData.currency.code and geoData.location.languages to auto-select a default currency or language on e-commerce sites, then pass the value to your storefront via a data layer push or custom JavaScript.


4. Security Use Cases (Paid Plans)

When you enable Include Security Data in the template configuration, the geoData.security object opens up a separate set of use cases around fraud prevention and traffic quality. These require a paid plan and cost 2 additional credits per lookup.

VPN and proxy detection for form protection: Check geoData.security.is_vpn or geoData.security.is_proxy before submitting lead forms. If the visitor is behind a VPN or proxy, you can suppress the form submission tag, fire a different tag that routes the lead to a manual review queue, or add a CAPTCHA step. This reduces junk leads from automated scrapers and fraudulent signups without blocking all anonymous traffic outright.

Threat-score-based tag gating: Use geoData.security.threat_score to control which tags fire based on IP risk. Create a Custom JavaScript variable that reads the score and returns a risk tier:

function() {
  var score = {{DLV - geoData.security.threat_score}};
  if (typeof score !== 'number') {
    return 'unknown';
  }

  if (score >= 80) {
    return 'high';
  }
  if (score >= 45) {
    return 'elevated';
  }
  if (score >= 20) {
    return 'medium';
  }
  return 'low';
}

Name this variable "CJS - Threat Risk Tier" and use it in trigger conditions. For example, block your checkout conversion tag from firing when the tier is high, or fire a fraud-logging tag when the tier is elevated or above.

Bot filtering for analytics accuracy: If geoData.security.is_bot is true, block your GA4 or other analytics tags from firing. This removes bot traffic from your analytics data at the source, before it pollutes your pageview counts, conversion rates, and funnel metrics. Create a trigger exception where geoData.security.is_bot equals true and apply it to your analytics tags.

Flagging anonymous or Tor traffic: Combine geoData.security.is_tor and geoData.security.is_anonymous to identify visitors using Tor or other anonymization tools. Depending on your risk tolerance, you can log these sessions for review, suppress personalization tags, or block specific flows like account creation and checkout.


A Note on Accuracy and Privacy

IP-based location tracking is not GPS-level precision. It resolves location from the IP address assigned by the visitor's ISP, which means accuracy varies. City-level resolution is typical for fixed broadband connections. Mobile IPs and VPN users will often resolve to a different city or region entirely.

For this reason, don't tie critical UX decisions (like hard redirects or price changes) solely to IP geolocation. Use it for targeting, reporting, default selections, and compliance checks where approximate location is good enough.

On the privacy side, IP addresses are considered personal data under GDPR and similar regulations. If your site serves EU visitors, make sure your cookie consent and privacy policy account for the fact that a third-party API (ipgeolocation.io) is receiving the visitor's IP address. The template fires a client-side API call, so standard consent mechanisms in GTM (like blocking tags until consent is granted) apply here the same way they would for any other third-party tag.

FAQ

Yes. The template pushes data into the GTM data layer, which is independent of your analytics platform. Create Data Layer Variables for the fields you need, then reference those variables in your GA4 event tags as event parameters or user properties.

On the free plan, yes. The API call runs client-side, so the key is visible in browser network tools. On paid plans, you can secure it by configuring Request Origins in your ipgeolocation.io dashboard and leaving the API key field blank in GTM.

With session storage enabled (recommended), one API call per session. The geolocation response is cached in the browser's session storage after the first page view. Subsequent pages within the same session reuse the cached data without making another API request, which keeps credit usage low on multi-page visits.

This template is designed for web (client-side) GTM containers. For server-side GTM, you would call the IP Geolocation API directly from a custom client or tag in your server container. Server-side has the advantage of keeping the API key completely hidden from the browser.

Related Tutorials

How to Secure Your API Key Before Production
How to Secure Your API Key Before Production

Your API key works in development, but shipping it as-is to production is a security risk. This tutorial covers environment variables, backend proxies, CORS-based auth, and usage monitoring for the IPGeolocation.io API.

Posted onMay14, 2026
Read More
How to Use the IPGeolocation.io Astronomy API
How to Use the IPGeolocation.io Astronomy API

Learn how to use the IPGeolocation.io Astronomy API to get sunrise, sunset, moon phase, golden hour, and 50+ other data fields from a single API call.

Posted onMay6, 2026
Read More
Getting Started with IP Geolocation API
Getting Started with IP Geolocation API

The fastest path from zero to your first IP geolocation API call. Create an account, grab your API key, and make a working request with curl, Python, or JavaScript.

Posted onApril30, 2026
Read More

Subscribe to Our Newsletter

Get the latest in geolocation tech, straight to your inbox.