Test Website Geolocation with Playwright and Proxies
A country test has two halves that fail for different reasons: what the browser says about itself (language, time zone, GPS position) and where the network traffic comes from (the exit IP). This guide gives you a small fixture site and a Playwright test matrix that checks both halves separately, so a red test tells you which half is wrong.
Quick Answer
Create one Playwright project per country with locale, timezoneId, geolocation and permissions, and assert the redirect, currency and time zone your site renders. These options never change the exit IP. For logic your server runs on the visitor's IP, add a separate project that routes through a proxy in that country and asserts the exit country first.
- →Browser-side checks: emulation alone, no proxy, runs on localhost
- →IP-side checks: need traffic that exits in the target country
- →Tested here with @playwright/test 1.64.1 and Chromium headless shell 156
This page assumes you can already open a Playwright browser context through an authenticated proxy. If not, start with our Playwright proxy configuration guide, which covers credentials, context scope and connection errors. Here we only add the parts that guide leaves out: country contexts, assertions that prove something, and a clear rule for when a test needs a different exit IP. If you are testing how AI models answer by region rather than how a website renders, the regional LLM testing guide is the better fit.
1. Browser location and IP location are separate inputs
The Playwright emulation guide lists geolocation, locale and timezone as context options you can set for all tests or a single test. Each one changes something the browser reports:
- •locale affects
navigator.language, theAccept-Languagerequest header and number and date formatting, per the Playwright test options reference. - •timezoneId changes the time zone of the context, using IDs such as
Europe/London. - •geolocation sets the coordinates the Geolocation API returns, and only works when the context also has the
geolocationpermission.
None of these touch the network path. A server that looks up the connecting IP in a geolocation database still sees your office or CI runner. We checked this directly: in the same Playwright session, a context with nl-NL, Amsterdam time and Amsterdam coordinates reported the same public IP to an echo service as a context with no emulation at all.
The IP half comes from the proxy. The Playwright network docs show that a proxy can be set for the whole browser or per context, over HTTP(S) or SOCKSv5. With a dedicated mobile proxy port, that exit is one physical 4G/5G modem with its own SIM on a carrier network, and the carrier assigns the public address.
2. Build a fixture site you control
Testing against someone else's storefront makes failures ambiguous: their rules change and you cannot see them. A 50-line Node server removes that problem. It redirects / by the first Accept-Language tag, then renders a price in the market's currency, the browser language, the time zone and a button that calls the Geolocation API. It uses only Node built-ins.
fixture/server.mjs
// Demo site you own: redirects by Accept-Language, renders a price and the browser's own signals.
import http from "node:http";
const MARKETS = {
us: { lang: "en-US", currency: "USD" },
uk: { lang: "en-GB", currency: "GBP" },
nl: { lang: "nl-NL", currency: "EUR" },
};
function pickMarket(acceptLanguage = "") {
const first = acceptLanguage.split(",")[0].trim().toLowerCase();
if (first.startsWith("nl")) return "nl";
if (first === "en-gb") return "uk";
if (first === "en-us") return "us";
return null;
}
const page = (key) => `<!doctype html>
<html lang="${MARKETS[key].lang}"><head><meta charset="utf-8"><title>Demo ${key}</title></head>
<body>
<p>Price: <output id="price"></output></p>
<p>Language: <output id="lang"></output></p>
<p>Time zone: <output id="tz"></output></p>
<button id="locate">Use my location</button> <output id="coords"></output>
<script>
const currency = ${JSON.stringify(MARKETS[key].currency)};
price.textContent = new Intl.NumberFormat(navigator.language, { style: "currency", currency }).format(19.99);
lang.textContent = navigator.language;
tz.textContent = Intl.DateTimeFormat().resolvedOptions().timeZone;
locate.onclick = () => navigator.geolocation.getCurrentPosition(
(p) => { coords.textContent = p.coords.latitude.toFixed(2) + "," + p.coords.longitude.toFixed(2); },
(e) => { coords.textContent = "error:" + e.code; });
</script>
</body></html>`;
http.createServer((req, res) => {
const key = req.url.split("/")[1];
if (req.url === "/") {
const market = pickMarket(req.headers["accept-language"]);
res.writeHead(302, { Location: market ? `/${market}/` : "/intl/" });
return res.end();
}
if (MARKETS[key]) {
res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
return res.end(page(key));
}
res.writeHead(200, { "Content-Type": "text/plain; charset=utf-8" });
res.end(key === "intl" ? "International page" : "Not found");
}).listen(4173, "127.0.0.1");Replace pickMarket with your real routing rules when you point the same tests at your own site. Keep the fixture in the repository anyway: it is a quick way to confirm the test harness still works after a Playwright upgrade.
3. Define one context per country
Put every market in one typed list so the config and the assertions read the same values. The markets below match the countries we rent ports in. The coordinates are test inputs for San Francisco, Cardiff in Wales and Amsterdam; a mobile carrier does not send GPS data, so they are not a property of any port.
tests/markets.ts
export type Market = {
name: string;
locale: string;
timezoneId: string;
geolocation: { latitude: number; longitude: number };
expectPath: string;
expectPrice: RegExp;
expectCoords: string;
exitCountry: string; // ISO code expected from an IP-echo service, network runs only
};
export const markets: Market[] = [
{ name: "us", locale: "en-US", timezoneId: "America/Los_Angeles",
geolocation: { latitude: 37.77, longitude: -122.42 },
expectPath: "/us/", expectPrice: /^\$19\.99$/, expectCoords: "37.77,-122.42", exitCountry: "US" },
{ name: "uk", locale: "en-GB", timezoneId: "Europe/London",
geolocation: { latitude: 51.48, longitude: -3.18 },
expectPath: "/uk/", expectPrice: /^£19\.99$/, expectCoords: "51.48,-3.18", exitCountry: "GB" },
{ name: "nl", locale: "nl-NL", timezoneId: "Europe/Amsterdam",
geolocation: { latitude: 52.37, longitude: 4.90 },
expectPath: "/nl/", expectPrice: /^€\s19,99$/, expectCoords: "52.37,4.90", exitCountry: "NL" },
];The config turns each market into a Playwright project. Emulation projects only run tests tagged @emulation. The network project reads proxy settings from environment variables and only runs tests tagged @network. The webServer block starts the fixture before the tests and reuses it if it is already running.
playwright.config.ts
import { defineConfig } from "@playwright/test";
import { markets } from "./tests/markets";
const proxy = process.env.MP_PROXY_SERVER
? { server: process.env.MP_PROXY_SERVER,
username: process.env.MP_PROXY_USERNAME,
password: process.env.MP_PROXY_PASSWORD }
: undefined;
export default defineConfig({
testDir: "./tests",
webServer: { command: "node fixture/server.mjs", url: "http://127.0.0.1:4173/intl/", reuseExistingServer: true },
use: {
baseURL: "http://127.0.0.1:4173",
screenshot: "only-on-failure",
trace: "retain-on-failure",
},
projects: [
...markets.map((m) => ({
name: m.name,
grep: /@emulation/,
use: { locale: m.locale, timezoneId: m.timezoneId,
geolocation: m.geolocation, permissions: ["geolocation"] },
})),
{ name: "network", grep: /@network/, use: { proxy } },
],
});4. Assert redirect, currency, time zone and GPS
The emulation test checks five things in order: the redirect target, the formatted price, the language, the time zone and the coordinates returned after a click. Web-first assertions such as toHaveURL and toHaveText retry until they pass or time out, so the asynchronous geolocation callback does not need a manual wait. The network test asserts only the exit country and attaches that single field as JSON.
tests/geo.spec.ts
import { test, expect } from "@playwright/test";
import { markets } from "./markets";
const marketFor = (project: string) => markets.find((m) => m.name === project);
test("redirect, currency, timezone and GPS follow the context @emulation", async ({ page }, testInfo) => {
const m = marketFor(testInfo.project.name)!;
await page.goto("/");
await expect(page).toHaveURL(m.expectPath);
await expect(page.locator("#price")).toHaveText(m.expectPrice);
await expect(page.locator("#lang")).toHaveText(m.locale);
await expect(page.locator("#tz")).toHaveText(m.timezoneId);
await page.locator("#locate").click();
await expect(page.locator("#coords")).toHaveText(m.expectCoords);
});
test("exit IP country matches the market under test @network", async ({ page }) => {
test.skip(!process.env.MP_PROXY_SERVER, "Set MP_PROXY_* variables to run network checks");
const expected = process.env.EXPECT_EXIT_COUNTRY;
test.skip(!expected, "Set EXPECT_EXIT_COUNTRY, for example GB");
const response = await page.goto("https://ipinfo.io/json");
const body = await response!.json();
// Attach only the fields you need. Never attach credentials or the full proxy URL.
await test.info().attach("exit-country.json", {
body: JSON.stringify({ country: body.country }),
contentType: "application/json",
});
expect(body.country).toBe(expected);
});Run it like this:
# Pinned version used for the run described on this page
npm i -D @playwright/test@1.64.1
npx playwright install chromium
# Emulation rows: no proxy needed
npx playwright test --project=us --project=uk --project=nl
# Network row: MP_PROXY_SERVER, MP_PROXY_USERNAME and MP_PROXY_PASSWORD
# must already be set from your secret store, never from the repository
EXPECT_EXIT_COUNTRY=GB npx playwright test --project=network5. The test matrix: emulation or exit IP?
Use this table to decide where each geo check belongs before you write it. The rule behind it is short: if the browser decides, emulate; if the server or a third party decides from the connecting IP, you need a different exit IP.
| Behavior under test | Driven by | Runs with | How the fixture proves it |
|---|---|---|---|
| Server redirect by Accept-Language | locale | Emulation | nl project run with en-US locale landed on /us/ instead of /nl/ |
| navigator.language on the page | locale | Emulation | Opening /nl/ directly under en-US: language read en-US, not nl-NL |
| Currency and number format | locale (Intl formatting) | Emulation | Same direct /nl/ visit rendered €19.99, so the € 19,99 pattern fails |
| Displayed time zone | timezoneId | Emulation | uk project run with Asia/Tokyo received Asia/Tokyo, expected Europe/London |
| Store finder or map using the Geolocation API | geolocation + permissions | Emulation | Wrong coordinates received 1.00,1.00; missing permission received error:1 |
| Server redirect, price or block by IP country | Exit IP | Needs a different exit IP | Not provable on localhost; deploy a copy to a public host you own |
| Which country an IP database reports | Exit IP and the database | Needs a different exit IP | The @network test asserts the country an echo service returns |
| Mismatch rules (IP country vs language or time zone) | Exit IP + emulation | Needs both | Not in the fixture; add the market's emulation settings to the network project |
The localhost fixture can only prove the emulation rows. A remote proxy port cannot reach 127.0.0.1 on your machine, so for the IP rows deploy the fixture, or a staging copy of your site, to a public host you own and set baseURL to it for the network project.
6. Checks that need a different exit IP
Assert the exit country before any IP-dependent assertion. If the echo service reports the wrong country, the failure is in the network path, and checking your page would only produce a confusing second error. The example uses ipinfo.io, whose JSON includes a two-letter country field (the United Kingdom is GB). If your site uses a different database, assert against that one, because databases can disagree about the same address. When they do, work through a proxy showing the wrong country before you change the test.
A few facts about mobile exits affect how you write these tests:
- •The carrier assigns the address, and a carrier may share one public IP between subscribers behind carrier-grade NAT. Do not assert a specific IP; assert the country and the page behavior.
- •If you request a new IP between runs (from the dashboard, or with
POST /api/v1/proxies/{slotId}/switch), the carrier still assigns the address, so a new IP is not certain, and the endpoint allows one switch per port every 5 minutes, answering 429 with a Retry-After header when you are early. Switch before a run, never during one. - •Match the emulation to the exit. Pair a UK exit with the uk market's locale, timezoneId and geolocation by copying them into the network project's use block, so a site that compares IP country with language or time zone sees a consistent visitor.
For background on why a carrier address can be shared or change on its own, see CGNAT and mobile proxies and why a mobile proxy IP changes.
7. Keep failure artifacts useful and redacted
The config sets screenshot: "only-on-failure" and trace: "retain-on-failure", so a passing run keeps no screenshot or trace and a failing run keeps both. When we broke the nl locale, the screenshot showed the US page, which made the cause obvious without opening the trace.
- •Attach the smallest useful fact with
testInfo.attach, as the network test does with the country code. Never attach environment variables or a full proxy URL. - •When a page shows account or payment details, take your own screenshot with the
maskoption, which covers the given locators with a solid box. - •Treat traces as private. The trace viewer lists the network requests made during the test, so keep traces out of public CI artifacts and issue trackers.
Keep TLS verification on. If a proxied run throws a certificate error, fix the endpoint or trust configuration rather than ignoring HTTPS errors in the context.
Frequently asked questions
Does Playwright geolocation emulation change my IP address?
No. The geolocation option only changes what the browser's Geolocation API reports to the page. The network exit IP stays the same. In our run, a context with Dutch locale, Amsterdam time zone and Amsterdam coordinates reported the same public IP as a plain context. To change the IP a server sees, route the context through a proxy.
Which Playwright options control locale and time zone?
Set locale (for example en-GB) and timezoneId (for example Europe/London) in the use block of a project or in browser.newContext. According to the Playwright docs, locale affects navigator.language, the Accept-Language request header and number and date formatting. timezoneId changes the context's time zone.
Which geo tests need a proxy and which can use emulation alone?
Anything the browser decides, such as language, currency formatting, displayed time zone and Geolocation API results, can be tested with emulation alone. Anything the server or a third party decides from the connecting IP, such as an IP-country redirect, a regional price or a geo-block, needs traffic that exits from an IP in that country.
Why does my geolocation test return error code 1?
Code 1 is PERMISSION_DENIED in the Geolocation API. Setting geolocation coordinates is not enough: the context also needs permissions set to include geolocation. In the fixture, removing that permission made the coordinates output read error:1 and the assertion failed.
Can I run the localhost fixture through a mobile proxy?
Not usefully. A remote proxy port cannot reach 127.0.0.1 on your machine, so the localhost copy only proves the emulation rows. To test IP-based behavior, deploy the same fixture or a staging copy of your site to a public host you own, then run the network project against it.
Sources & tools referenced
- • Playwright: Emulation (locale, timezone, geolocation, permissions)
- • Playwright: Network (HTTP proxy, per-browser and per-context)
- • Playwright: TestOptions (locale, timezoneId, proxy, screenshot, trace)
- • Playwright: Test use options (recording options)
- • Playwright: Assertions (auto-retrying assertions)
- • Playwright: Web server
- • Playwright: TestInfo (attach)
- • Playwright: Page (screenshot mask option)
- • Playwright: Trace viewer (network requests in traces)
- • MDN: GeolocationPositionError.code (1 is PERMISSION_DENIED)
- • ipinfo.io: Developer docs (country field)
Related guides
Tutorial
Playwright Proxy Configuration
Credentials, context scope and errors
Use case
Geo Testing
Regional QA with carrier exits
Technical
Regional LLM Testing
Compare AI answers by region
Tutorial
How to Test a Proxy
Exit IP, ASN and leak checks
Technical
WebRTC Leaks
Keep the browser from exposing another IP
Integration
Mobile Proxy for Playwright MCP
Route an agent-driven browser
Run the fixture, then repeat it with a real exit
The emulation rows run today with no proxy. For the network row, rent a dedicated port in the United States, the United Kingdom or the Netherlands. The EUR 5 plan gives you 10 hours on one port, does not auto-renew, and supports HTTP and SOCKS5.