Enhance visitor country handling by prioritizing forwarded header on revalidation requests

This commit is contained in:
Nicolas Dorseuil
2026-10-07 09:35:49 +02:00
parent 4880e26924
commit f58783c260
3 changed files with 37 additions and 2 deletions
+1 -1
View File
@@ -2,4 +2,4 @@
"gitbook": patch
---
Send the visitor country to resolvePublishedContentByUrl on dev, preview, staging and selected sites.
Send the visitor country to resolvePublishedContentByUrl on dev, preview, staging and selected sites, using the forwarded `x-gitbook-country` header on revalidation requests.
+32
View File
@@ -628,6 +628,38 @@ describe('getVisitorCountry', () => {
it('should return undefined when no country header is present', () => {
expect(getVisitorCountry(requestWith({}))).toBeUndefined();
});
it('should prefer the forwarded country header on revalidation requests', () => {
expect(
getVisitorCountry(
requestWith({
'user-agent': 'gitbook-open-revalidation-worker',
'x-gitbook-country': 'DE',
'x-open-next-country': 'FR',
})
)
).toBe('DE');
});
it('should ignore the forwarded country header outside revalidation requests', () => {
expect(
getVisitorCountry(
requestWith({ 'x-gitbook-country': 'DE', 'x-open-next-country': 'FR' })
)
).toBe('FR');
expect(getVisitorCountry(requestWith({ 'x-gitbook-country': 'DE' }))).toBeUndefined();
});
it('should fall back to geolocation headers on revalidation requests without a forwarded country', () => {
expect(
getVisitorCountry(
requestWith({
'user-agent': 'gitbook-open-revalidation-worker',
'x-open-next-country': 'FR',
})
)
).toBe('FR');
});
});
describe('shouldSendVisitorCountry', () => {
+4 -1
View File
@@ -124,10 +124,13 @@ export function shouldSendVisitorCountry(
}
/**
* Get the ISO 3166-1 alpha-2 country code of the visitor from the geolocation headers.
* Get the ISO 3166-1 alpha-2 country code of the visitor from the geolocation headers,
* or from `x-gitbook-country` when the request comes from the revalidation worker.
*/
export function getVisitorCountry(request: { headers: Headers }): string | undefined {
// The revalidation worker forwards the original visitor country; only trust it from there.
const country = (
(isRevalidationRequest(request.headers) && request.headers.get('x-gitbook-country')) ||
request.headers.get('x-open-next-country') ||
request.headers.get('x-vercel-ip-country') ||
''