Ad blockers and privacy extensions drop requests to third-party telemetry hosts, so some of your users’ data never arrives. With a tunnel, the SDK sends to a URL on your own site, and your server forwards each request to EZGH:
init({ token: "ezgh_ct_…", release: import.meta.env.VITE_RELEASE, tunnel: "/_ezgh" });The SDK then sends POST /_ezgh?path=/v1/logs&ct=…&enc=gzip&sv=… (or path=/v1/traces) to your
own origin. Requests to the tunnel are never tracked as spans themselves.
What a handler does
- Accepts
POSTonly, withpathset to/v1/tracesor/v1/logs; anything else is404. Browsers send no metrics. - Refuses bodies over 1 MiB with
413. - Forwards the body and the whole query unchanged to
https://obs-browser.ezghcloud.com<path>(EZGH ignorespathin the query). - Forwards
Content-Typeand the browser’sOrigin, and appends the browser’s address toX-Forwarded-For, as any proxy does. - Never forwards
CookieorAuthorization.sendBeaconalways sends your site’s cookies to the tunnel, and EZGH refuses a request with anAuthorizationheader (400). The handlers below build the upstream request’s headers from scratch, so nothing else goes through. - Passes back the status, the body,
Content-TypeandRetry-After, so the SDK can wait when it’s asked to.
Tunnel addresses
Without tunnel addresses, a tunnel works, but every user looks like your tunnel server: they
share its location and the per-address rate limit. Add your tunnel’s outbound IP ranges to the
client token’s tunnel addresses (up to 20 CIDRs), and EZGH uses each user’s own address, from
the X-Forwarded-For your handler appended, for location and rate limiting:
ezgh obs browser-apps tokens update "storefront production" \
--tunnel-address 203.0.113.0/24 --tunnel-address 2001:db8:4::/48In the console, edit the token on the app’s Tokens tab. If you don’t know your tunnel’s outbound ranges, leave them empty: data still arrives.
Handlers
Each handler reads its upstream from EZGH_RUM_UPSTREAM when set, and uses
https://obs-browser.ezghcloud.com otherwise.
Route https://shop.example.com/_ezgh* to the Worker. The browser’s address comes from
CF-Connecting-IP.
// cloudflare-worker.ts — route https://shop.example.com/_ezgh* to this Worker, then init({ tunnel: "/_ezgh" }).
// It forwards POST /_ezgh?path=/v1/{traces,logs}&… to obs-browser with the query and body unchanged,
// and never forwards Cookie or Authorization (sendBeacon carries the site's cookies).
const PATHS = new Set(["/v1/traces", "/v1/logs"])
export default {
async fetch(req: Request, env: { EZGH_RUM_UPSTREAM?: string }): Promise<Response> {
const url = new URL(req.url)
const path = url.searchParams.get("path") ?? ""
if (req.method !== "POST" || !PATHS.has(path)) return new Response(null, { status: 404 })
const body = await req.arrayBuffer()
if (body.byteLength > 1 << 20) return new Response(null, { status: 413 })
const headers = new Headers({ "Content-Type": req.headers.get("Content-Type") ?? "text/plain;charset=UTF-8" })
const origin = req.headers.get("Origin")
if (origin) headers.set("Origin", origin)
const client = req.headers.get("CF-Connecting-IP")
if (client) headers.set("X-Forwarded-For", [req.headers.get("X-Forwarded-For"), client].filter(Boolean).join(", "))
const up = await fetch(`${env.EZGH_RUM_UPSTREAM ?? "https://obs-browser.ezghcloud.com"}${path}${url.search}`, { method: "POST", headers, body })
const out = new Headers()
for (const h of ["Content-Type", "Retry-After"]) {
const v = up.headers.get(h)
if (v) out.set(h, v)
}
return new Response(up.body, { status: up.status, headers: out })
},
}Mount it with app.use("/_ezgh", ezghTunnel()). Behind a load balancer, set
app.set("trust proxy", …) so req.ip is the browser’s address.
// express.ts — app.use("/_ezgh", ezghTunnel()), then init({ tunnel: "/_ezgh" }). Set
// app.set("trust proxy", …) for your load balancer so req.ip is the browser's address.
// It never forwards Cookie or Authorization (sendBeacon carries the site's cookies).
import express, { type NextFunction, type Request, type Response, type Router } from "express"
const PATHS = new Set(["/v1/traces", "/v1/logs"])
export function ezghTunnel(upstream = process.env.EZGH_RUM_UPSTREAM ?? "https://obs-browser.ezghcloud.com"): Router {
const r = express.Router()
r.post("/", express.raw({ type: () => true, limit: "1mb" }), async (req: Request, res: Response) => {
const path = typeof req.query.path === "string" ? req.query.path : ""
if (!PATHS.has(path)) {
res.sendStatus(404)
return
}
const xff = [req.get("X-Forwarded-For"), req.ip].filter(Boolean).join(", ")
const headers: Record<string, string> = { "Content-Type": req.get("Content-Type") ?? "text/plain;charset=UTF-8", "X-Forwarded-For": xff }
const origin = req.get("Origin")
if (origin) headers.Origin = origin
const query = req.originalUrl.slice(req.originalUrl.indexOf("?"))
try {
const up = await fetch(`${upstream}${path}${query}`, { method: "POST", headers, body: req.body as Uint8Array<ArrayBuffer> })
for (const h of ["Content-Type", "Retry-After"]) {
const v = up.headers.get(h)
if (v) res.setHeader(h, v) // setHeader relays it as is (res.set adds a charset)
}
res.status(up.status).end(Buffer.from(await up.arrayBuffer()))
}
catch {
res.sendStatus(502)
}
})
// express.raw answers a body over the limit with a 413 error; send just the status.
r.use((err: { status?: number }, _req: Request, res: Response, next: NextFunction) => {
if (err.status === 413) res.sendStatus(413)
else next(err)
})
r.all("/", (_req: Request, res: Response) => {
res.sendStatus(404) // only POST
})
return r
}Save it as app/%5Fezgh/route.ts: the URL is /_ezgh, because App Router folders starting with
_ are private. Your platform’s proxy has already put the browser’s address in
X-Forwarded-For, so it’s passed through.
// nextjs-route.ts — save as app/%5Fezgh/route.ts: "%5F" makes the URL /_ezgh, because folders
// starting with "_" are private in the App Router. The platform's proxy has already put the
// browser's address in X-Forwarded-For, so it's passed through as is. Cookie and Authorization
// are never forwarded (sendBeacon carries the site's cookies).
const PATHS = new Set(["/v1/traces", "/v1/logs"])
const UPSTREAM = process.env.EZGH_RUM_UPSTREAM ?? "https://obs-browser.ezghcloud.com"
export async function POST(req: Request): Promise<Response> {
const url = new URL(req.url)
const path = url.searchParams.get("path") ?? ""
if (!PATHS.has(path)) return new Response(null, { status: 404 })
const body = await req.arrayBuffer()
if (body.byteLength > 1 << 20) return new Response(null, { status: 413 })
const headers = new Headers({ "Content-Type": req.headers.get("Content-Type") ?? "text/plain;charset=UTF-8" })
for (const h of ["Origin", "X-Forwarded-For"]) {
const v = req.headers.get(h)
if (v) headers.set(h, v)
}
const up = await fetch(`${UPSTREAM}${path}${url.search}`, { method: "POST", headers, body })
const out = new Headers()
for (const h of ["Content-Type", "Retry-After"]) {
const v = up.headers.get(h)
if (v) out.set(h, v)
}
return new Response(up.body, { status: up.status, headers: out })
}Mount it with mux.Handle("/_ezgh", ezghtunnel.Handler("")). Behind a load balancer, put the
browser’s address in r.RemoteAddr first, for example with a trusted-proxy middleware.
// Package ezghtunnel forwards @ezghcloud/rum's tunnel requests to obs-browser.
//
// tunnel.go — mux.Handle("/_ezgh", ezghtunnel.Handler("")), then init({ tunnel: "/_ezgh" }).
// Behind a load balancer, put the browser's address in r.RemoteAddr first (for example with a
// trusted-proxy middleware). It never forwards Cookie or Authorization (sendBeacon carries the
// site's cookies).
package ezghtunnel
import (
"bytes"
"errors"
"io"
"net"
"net/http"
"strings"
)
// DefaultUpstream is the browser ingest host.
const DefaultUpstream = "https://obs-browser.ezghcloud.com"
var paths = map[string]bool{"/v1/traces": true, "/v1/logs": true}
// Handler forwards POST <mount>?path=/v1/{traces,logs}&… to upstream (DefaultUpstream when
// empty), with the whole query and the body unchanged.
func Handler(upstream string) http.Handler {
if upstream == "" {
upstream = DefaultUpstream
}
client := &http.Client{}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
path := r.URL.Query().Get("path")
if r.Method != http.MethodPost || !paths[path] {
http.NotFound(w, r)
return
}
body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 1<<20))
if err != nil {
var tooLarge *http.MaxBytesError
if errors.As(err, &tooLarge) {
http.Error(w, "request body too large", http.StatusRequestEntityTooLarge)
} else {
http.Error(w, "bad request", http.StatusBadRequest)
}
return
}
req, err := http.NewRequestWithContext(r.Context(), http.MethodPost, upstream+path+"?"+r.URL.RawQuery, bytes.NewReader(body))
if err != nil {
http.Error(w, "bad request", http.StatusBadRequest)
return
}
ct := r.Header.Get("Content-Type")
if ct == "" {
ct = "text/plain;charset=UTF-8"
}
req.Header.Set("Content-Type", ct)
if o := r.Header.Get("Origin"); o != "" {
req.Header.Set("Origin", o)
}
// The client's chain (every X-Forwarded-For line), then the browser's address. A trusted-proxy
// middleware may leave RemoteAddr as a bare IP, without a port.
host, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
host = r.RemoteAddr
}
chain := r.Header.Values("X-Forwarded-For")
if net.ParseIP(host) != nil {
chain = append(chain, host)
}
if len(chain) > 0 {
req.Header.Set("X-Forwarded-For", strings.Join(chain, ", "))
}
resp, err := client.Do(req)
if err != nil {
http.Error(w, "upstream unavailable", http.StatusBadGateway)
return
}
defer resp.Body.Close()
for _, h := range []string{"Content-Type", "Retry-After"} {
if v := resp.Header.Get(h); v != "" {
w.Header().Set(h, v)
}
}
w.WriteHeader(resp.StatusCode)
_, _ = io.Copy(w, resp.Body)
})
}Check a tunnel
Open a page that sends through the tunnel, and in the browser’s network panel, the requests to
/_ezgh answer 200. Then:
curl -X POST 'https://shop.example.com/_ezgh?path=/v1/metrics'answers404;curl -X POST 'https://shop.example.com/_ezgh?path=/v1/logs&ct=x'answers EZGH’s401for a token that isn’t one, which shows the handler passes statuses back;- page loads appear on the Performance page, or with
ezgh obs traces search --dataset production --name documentLoad.