# First-party proxy

`createVisiblingProxy` from `@visibling/sdk/cloudflare` mounts Visibling behind your own origin at `/_v/e`:

- The browser posts every batch to `https://<your-app>/_v/e`, so ad-blockers and third-party-cookie protections never see a Visibling URL.
- The Worker resolves the signed-in user server-side, strips client-asserted identity, attaches edge metadata, and forwards with a `vis_srv_` key.
- The browser receives `202 Accepted` immediately. Forwarding runs in `ctx.waitUntil` and any upstream failure is swallowed, so analytics never takes the host app down.

Create the key under **Project settings → Keys** and keep it a Worker secret:

```sh
wrangler secret put VISIBLING_SERVER_KEY
```

## TanStack Start

TanStack Start route handlers receive `{ request }`, not the Worker `ExecutionContext`. Stash both in `AsyncLocalStorage` at the Worker entry and read them from the route. `nodejs_compat` is required:

```jsonc
// wrangler.jsonc
{
  "compatibility_flags": ["nodejs_compat"]
}
```

```ts
// src/lib/request-context.ts
import { AsyncLocalStorage } from "node:async_hooks";
import type { Env } from "./visibling-proxy";

interface RequestContext {
  env: Env;
  ctx: ExecutionContext;
}

const storage = new AsyncLocalStorage<RequestContext>();

export function setRequestContext<T>(
  env: Env,
  ctx: ExecutionContext,
  callback: () => T | Promise<T>,
): Promise<T> {
  return Promise.resolve(storage.run({ env, ctx }, callback));
}

export function getEnv(): Env {
  const context = storage.getStore();
  if (!context) throw new Error("Env is only available inside a request.");
  return context.env;
}

export function getExecutionContext(): ExecutionContext | undefined {
  return storage.getStore()?.ctx;
}
```

```ts
// src/server.ts
import { createStartHandler, defaultStreamHandler } from "@tanstack/react-start/server";
import { setRequestContext } from "./lib/request-context";
import type { Env } from "./lib/visibling-proxy";

const handler = createStartHandler(defaultStreamHandler);

export default {
  async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
    return setRequestContext(env, ctx, () => handler(request));
  },
};
```

```ts
// src/lib/visibling-proxy.ts
import type { VisiblingIdentity } from "@visibling/sdk/cloudflare";
import { createVisiblingProxy } from "@visibling/sdk/cloudflare";
import { getEnv } from "./request-context";
import { getSession } from "./auth-session"; // your own session lookup

interface Env {
  VISIBLING_SERVER_KEY: string;
  APP_RELEASE?: string;
  APP_ENVIRONMENT?: string;
}

async function getIdentity(request: Request): Promise<VisiblingIdentity | null> {
  const session = await getSession(request);
  if (!session?.user) return null;
  return {
    distinctId: session.user.id,
    email: session.user.email,
    userName: session.user.name,
    externalOrgId: session.orgId,
    plan: session.plan,
  };
}

export function visiblingProxy() {
  const env = getEnv();
  return createVisiblingProxy({
    serverKey: env.VISIBLING_SERVER_KEY,
    getIdentity,
    release: env.APP_RELEASE,
    environment: env.APP_ENVIRONMENT,
  });
}
```

```ts
// src/routes.ts
import { index, rootRoute, route } from "@tanstack/virtual-file-routes";

export const routes = rootRoute("__root.tsx", [
  index("index.tsx"),
  route("/_v/e", "_v/e.tsx"),
]);
```

```tsx
// src/routes/_v/e.tsx
import { createFileRoute } from "@tanstack/react-router";
import { getExecutionContext } from "../../lib/request-context";
import { visiblingProxy } from "../../lib/visibling-proxy";

export const Route = createFileRoute("/_v/e")({
  server: {
    handlers: {
      POST: ({ request }) => visiblingProxy()(request, getExecutionContext()),
    },
  },
});
```

With physical file routes, TanStack treats a leading `_` segment as a pathless layout. Escape it as `src/routes/[_]v/e.tsx` so the URL stays `/_v/e`.

## Plain Cloudflare Worker

The proxy is a plain `(request, ctx) => Response` function, so a fetch handler can mount it directly:

```ts
// src/index.ts
import type { VisiblingIdentity } from "@visibling/sdk/cloudflare";
import { createVisiblingProxy } from "@visibling/sdk/cloudflare";

interface Env {
  VISIBLING_SERVER_KEY: string;
  APP_RELEASE?: string;
  APP_ENVIRONMENT?: string;
}

async function getIdentity(request: Request): Promise<VisiblingIdentity | null> {
  const session = await getSession(request); // your own session lookup
  if (!session?.user) return null;
  return {
    distinctId: session.user.id,
    email: session.user.email,
    userName: session.user.name,
    externalOrgId: session.orgId,
    plan: session.plan,
  };
}

export default {
  async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
    const url = new URL(request.url);

    if (url.pathname === "/_v/e") {
      const proxy = createVisiblingProxy({
        serverKey: env.VISIBLING_SERVER_KEY,
        getIdentity,
        release: env.APP_RELEASE,
        environment: env.APP_ENVIRONMENT,
      });
      return proxy(request, ctx);
    }

    return new Response("Not found", { status: 404 });
  },
};
```

The helper answers `202` for a valid batch, `405` for a non-`POST` request, `413` for a body over 64 KB, and `400` for malformed JSON or a missing `items` array. It never throws into your fetch handler.

## Same-account Service Binding

When Visibling and the host app share a Cloudflare account, bind Visibling's `VisiblingIngestEntrypoint` and skip the HTTPS hop entirely. The binding calls the same ingest service in-process.

```jsonc
// host app wrangler.jsonc
{
  "services": [
    {
      "binding": "VISIBLING",
      "service": "visibling-web",
      "entrypoint": "VisiblingIngestEntrypoint"
    }
  ]
}
```

```ts
// src/lib/visibling-proxy.ts
import type {
  VisiblingIdentity,
  VisiblingServiceBinding,
} from "@visibling/sdk/cloudflare";
import { createVisiblingProxy } from "@visibling/sdk/cloudflare";

interface Env {
  VISIBLING_SERVER_KEY: string;
  VISIBLING?: VisiblingServiceBinding;
}

export function visiblingProxy(env: Env, getIdentity: (request: Request) => Promise<VisiblingIdentity | null>) {
  return createVisiblingProxy({
    serverKey: env.VISIBLING_SERVER_KEY,
    serviceBinding: env.VISIBLING,
    getIdentity,
  });
}
```

Use the service name of your deployment: the default Wrangler `name` is `visibling-web`; a self-hosted install usually renames it. The entrypoint calls `ingestBatch(serverKey, { items }, meta)` where `meta` carries the original `cfRay`, `country`, and `userAgent`.

Without a binding, `createVisiblingProxy` POSTs to `ingestUrl` (default `https://visibling.com/api/v1/ingest`) with `x-visibling-key`, the original `user-agent`, and proxy-marked `x-visibling-proxy-cf-ray` / `x-visibling-proxy-country` headers. The ingest route trusts those proxy headers only for a server key. Set `ingestUrl` when self-hosting.

## Security model

The proxy forwards with a **server** key, which Visibling trusts, so trust stops at `getIdentity`:

- Client-supplied `distinctId`, `email`, `userName`, `plan`, and `externalOrgId` are removed from every item, and the four identity traits are removed from `traits`. `plan` and `externalOrgId` are also removed from `props`. `anonId` is preserved because the browser owns it.
- Identity is stamped only when `getIdentity` returns it. A signed-out visitor's batch carries no user identity, so a browser cannot impersonate another end user. A thrown identity lookup is treated as signed out.
- `cfRay` and `country` from the incoming request override browser values.
- `release` and `environment` configured on the proxy override browser values; a blank configured value is ignored rather than stamping an empty string.
- `createVisiblingProxy` throws when `serverKey` does not start with `vis_srv_`, so a public key cannot silently degrade the proxy.

The server key never leaves the Worker. Do not expose it through a `VITE_` variable or the browser bundle.
