:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
import { POSTHOG_EU_BASE_URL, POSTHOG_US_BASE_URL, type Region, baseUrlForRegion } from './constants'
/**
* Proxy a request to a specific region's PostHog server.
* Rewrites the URL path onto the regional base URL and forwards the request.
*/
export async function proxyToRegion(request: Request, region: Region, path: string): Promise<Response> {
const baseUrl = baseUrlForRegion(region)
const url = new URL(path, baseUrl)
const headers = new Headers(request.headers)
headers.delete('host')
return fetch(url.toString(), {
method: request.method,
headers,
body: request.body,
})
}
/**
* Proxy a form-encoded or JSON POST body to a region, optionally rewriting the client_id.
*/
export async function proxyPostWithClientId(
request: Request,
region: Region,
path: string,
proxyClientId: string,
regionalClientId: string,
redirectUriRewrite?: { from: string; to: string },
clientSecretRewrite?: { from: string; to: string }
): Promise<Response> {
const contentType = request.headers.get('content-type') || ''
let body: string
if (contentType.includes('application/json')) {
const json = await request.json<Record<string, unknown>>()
if (json.client_id === proxyClientId) {
json.client_id = regionalClientId
}
if (redirectUriRewrite && json.redirect_uri === redirectUriRewrite.from) {
json.redirect_uri = redirectUriRewrite.to
}
if (clientSecretRewrite && json.client_secret === clientSecretRewrite.from) {
json.client_secret = clientSecretRewrite.to
}
body = JSON.stringify(json)
} else {
// form-urlencoded
const text = await request.text()
const params = new URLSearchParams(text)
if (params.get('client_id') === proxyClientId) {
params.set('client_id', regionalClientId)
}
if (redirectUriRewrite && params.get('redirect_uri') === redirectUriRewrite.from) {
params.set('redirect_uri', redirectUriRewrite.to)
}
if (clientSecretRewrite && params.get('client_secret') === clientSecretRewrite.from) {
params.set('client_secret', clientSecretRewrite.to)
}
body = params.toString()
}
const baseUrl = baseUrlForRegion(region)
const url = new URL(path, baseUrl)
const headers = new Headers(request.headers)
headers.delete('host')
// Body was rewritten so the original content-length is wrong
headers.delete('content-length')
return fetch(url.toString(), {
method: 'POST',
headers,
body,
})
}
/**
* Try a POST request against US first, then EU if US fails.
* Used for token exchange fallback when region is unknown.
*/
export async function tryBothRegions(
request: Request,
path: string
): Promise<{ response: Response; region: Region | null }> {
const body = await request.text()
const headers = new Headers(request.headers)
headers.delete('host')
const usUrl = new URL(path, POSTHOG_US_BASE_URL)
const usResponse = await fetch(usUrl.toString(), {
method: 'POST',
headers,
body,
})
if (usResponse.ok) {
console.info(JSON.stringify({ fn: 'tryBothRegions', path, resolved: 'us', us_status: usResponse.status }))
return { response: usResponse, region: 'us' }
}
const euHeaders = new Headers(request.headers)
euHeaders.delete('host')
const euUrl = new URL(path, POSTHOG_EU_BASE_URL)
const euResponse = await fetch(euUrl.toString(), {
method: 'POST',
headers: euHeaders,
body,
})
if (euResponse.ok) {
console.info(
JSON.stringify({
fn: 'tryBothRegions',
path,
resolved: 'eu',
us_status: usResponse.status,
eu_status: euResponse.status,
})
)
return { response: euResponse, region: 'eu' }
}
const forwarded = preferClientError(usResponse, euResponse)
console.error(
JSON.stringify({
fn: 'tryBothRegions',
path,
resolved: 'none',
us_status: usResponse.status,
eu_status: euResponse.status,
forwarded_from: forwarded === usResponse ? 'us' : 'eu',
})
)
return { response: forwarded, region: null }
}
/**
* Pick which of two rejections to forward to the client.
*
* A 4xx carries the OAuth error code the client acts on: `invalid_grant` tells it
* to discard the token and re-authorize. A 5xx only says one region was unhealthy,
* which must not be reported as a dead grant.
*/
export function preferClientError(first: Response, second: Response): Response {
if (isClientError(first)) {
return first
}
return isClientError(second) ? second : first
}
function isClientError(response: Response): boolean {
return response.status >= 400 && response.status < 500
}