Skip to content

AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.

feat(frontend): route browser PostHog traffic through our own domain (#15213)

Krzysztof Czerwinski20bf545481cb
diff --git a/autogpt_platform/frontend/next.config.mjs b/autogpt_platform/frontend/next.config.mjs
index 0adf197943..905941905f 100644
--- a/autogpt_platform/frontend/next.config.mjs
+++ b/autogpt_platform/frontend/next.config.mjs
@@ -19,6 +19,10 @@ const nextConfig = {
},
// Suppress the "X-Powered-By: Next.js" header (framework fingerprinting).
poweredByHeader: false,
+ // PostHog's endpoints end in a slash (`/e/`, `/flags/`), so requests on the
+ // PostHog proxy path must reach middleware untouched. Middleware redoes the
+ // trailing-slash redirect for every other path (see src/middleware.ts).
+ skipTrailingSlashRedirect: true,
async rewrites() {
return [
{
diff --git a/autogpt_platform/frontend/src/__tests__/middleware.test.ts b/autogpt_platform/frontend/src/__tests__/middleware.test.ts
index 6d60e5dc7d..a4999a765d 100644
--- a/autogpt_platform/frontend/src/__tests__/middleware.test.ts
+++ b/autogpt_platform/frontend/src/__tests__/middleware.test.ts
@@ -1,5 +1,8 @@
-import { describe, expect, it, vi } from "vitest";
+// @vitest-environment node
+// happy-dom hides a request's cookie header, so a cookie test can't fail there.
+import { unstable_doesMiddlewareMatch } from "next/experimental/testing/server";
import { NextRequest } from "next/server";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
const authMiddlewareMock = vi.fn();
@@ -7,7 +10,11 @@ vi.mock("@/lib/auth/middleware", () => ({
authMiddleware: (...args: unknown[]) => authMiddlewareMock(...args),
}));
-import { middleware } from "../middleware";
+import { config, middleware } from "../middleware";
+
+beforeEach(() => {
+ authMiddlewareMock.mockReset();
+});
describe("middleware www→non-www redirect", () => {
it("redirects www host to non-www with 308", async () => {
@@ -45,3 +52,183 @@ describe("middleware www→non-www redirect", () => {
expect(response).toBe(passthrough);
});
});
+
+describe("middleware trailing-slash redirect", () => {
+ it("strips a trailing slash from page paths with 308", async () => {
+ const response = await middleware(
+ new NextRequest("https://example.com/marketplace/?q=1"),
+ );
+
+ expect(response.status).toBe(308);
+ expect(response.headers.get("location")).toBe(
+ "https://example.com/marketplace?q=1",
+ );
+ expect(authMiddlewareMock).not.toHaveBeenCalled();
+ });
+
+ it("fixes www and the trailing slash in one redirect", async () => {
+ const response = await middleware(
+ new NextRequest("https://www.example.com/copilot/"),
+ );
+
+ expect(response.status).toBe(308);
+ expect(response.headers.get("location")).toBe(
+ "https://example.com/copilot",
+ );
+ });
+
+ it("leaves the root path alone", async () => {
+ authMiddlewareMock.mockResolvedValueOnce(new Response("ok"));
+
+ await middleware(new NextRequest("https://example.com/"));
+
+ expect(authMiddlewareMock).toHaveBeenCalledTimes(1);
+ });
+});
+
+describe("middleware PostHog proxy", () => {
+ beforeEach(() => {
+ vi.stubEnv("NEXT_PUBLIC_POSTHOG_KEY", "phc_test");
+ vi.stubEnv("NEXT_PUBLIC_POSTHOG_HOST", "https://eu.i.posthog.com");
+ });
+
+ afterEach(() => {
+ vi.unstubAllEnvs();
+ });
+
+ const RELAY = "https://platform.agpt.co/relay/pnosthog";
+
+ function proxiedRequest(
+ url: string,
+ extraHeaders: Record<string, string> = {},
+ ) {
+ return new NextRequest(url, {
+ method: "POST",
+ headers: {
+ cookie: "better-auth.session_token=secret; sb-proj-auth-token=legacy",
+ authorization: "Bearer secret",
+ "content-type": "application/json",
+ ...extraHeaders,
+ },
+ });
+ }
+
+ function forwardedHeaders(response: Response) {
+ return (response.headers.get("x-middleware-override-headers") ?? "")
+ .split(",")
+ .sort();
+ }
+
+ it("runs middleware on the proxy path", () => {
+ expect(
+ unstable_doesMiddlewareMatch({ config, url: `${RELAY}/i/v0/e/` }),
+ ).toBe(true);
+ });
+
+ it.each(["/e/", "/i/v0/e/", "/s/", "/flags/", "/api/surveys/"])(
+ "forwards %s to PostHog with its trailing slash and query intact",
+ async (path) => {
+ const response = await middleware(
+ proxiedRequest(`${RELAY}${path}?ip=0&_=1`),
+ );
+
+ expect(response.headers.get("x-middleware-rewrite")).toBe(
+ `https://eu.i.posthog.com${path}?ip=0&_=1`,
+ );
+ expect(response.headers.get("location")).toBeNull();
+ expect(authMiddlewareMock).not.toHaveBeenCalled();
+ },
+ );
+
+ it("serves PostHog's scripts and our remote config from its assets host", async () => {
+ const asset = await middleware(
+ new NextRequest(`${RELAY}/static/recorder.js?v=1`),
+ );
+ const remoteConfig = await middleware(
+ new NextRequest(`${RELAY}/array/phc_test/config`),
+ );
+
+ expect(asset.headers.get("x-middleware-rewrite")).toBe(
+ "https://eu-assets.i.posthog.com/static/recorder.js?v=1",
+ );
+ expect(remoteConfig.headers.get("x-middleware-rewrite")).toBe(
+ "https://eu-assets.i.posthog.com/array/phc_test/config",
+ );
+ });
+
+ it("never hands our cookies or auth header to PostHog", async () => {
+ const response = await middleware(proxiedRequest(`${RELAY}/flags/?v=2`));
+
+ expect(forwardedHeaders(response)).toEqual(["content-type", "host"]);
+ expect(response.headers.get("x-middleware-request-host")).toBe(
+ "eu.i.posthog.com",
+ );
+ });
+
+ it("forwards no header outside its allowlist", async () => {
+ const response = await middleware(
+ proxiedRequest(`${RELAY}/e/`, {
+ "x-custom-token": "secret",
+ "user-agent": "probe",
+ "x-forwarded-for": "203.0.113.7",
+ }),
+ );
+
+ expect(forwardedHeaders(response)).toEqual([
+ "content-type",
+ "host",
+ "user-agent",
+ "x-forwarded-for",
+ ]);
+ });
+
+ it.each([
+ "/api/projects/1/",
+ "/array/phc_other/config.js",
+ "/decide/",
+ "//evil.example/x",
+ "",
+ ])("refuses %s without contacting PostHog", async (path) => {
+ const response = await middleware(proxiedRequest(`${RELAY}${path}`));
+
+ expect(response.status).toBe(404);
+ expect(response.headers.get("x-middleware-rewrite")).toBeNull();
+ expect(authMiddlewareMock).not.toHaveBeenCalled();
+ });
+
+ it("skips the www redirect and auth checks on the proxy path", async () => {
+ const response = await middleware(
+ proxiedRequest("https://www.platform.agpt.co/relay/pnosthog/e/"),
+ );
+
+ expect(response.status).not.toBe(308);
+ expect(response.headers.get("x-middleware-rewrite")).toBe(
+ "https://eu.i.posthog.com/e/",
+ );
+ expect(authMiddlewareMock).not.toHaveBeenCalled();
+ });
+
+ it("passes the path through untouched when PostHog Cloud isn't configured", async () => {
+ vi.stubEnv("NEXT_PUBLIC_POSTHOG_HOST", "https://posthog.example.com");
+
+ const response = await middleware(proxiedRequest(`${RELAY}/e/`));
+
+ expect(response.headers.get("x-middleware-rewrite")).toBeNull();
+ expect(response.headers.get("x-middleware-next")).toBe("1");
+ expect(authMiddlewareMock).not.toHaveBeenCalled();
+ });
+
+ it.each(["/relay/pnosthogx/e", "/relay/other/e", "/relay"])(
+ "leaves %s to the rest of the middleware",
+ async (path) => {
+ authMiddlewareMock.mockResolvedValueOnce(new Response("ok"));
+
+ const response = await middleware(
+ new NextRequest(`https://platform.agpt.co${path}`),
+ );
+
+ expect(response.headers.get("x-middleware-rewrite")).toBeNull();
+ expect(authMiddlewareMock).toHaveBeenCalledTimes(1);
+ },
+ );
+});
diff --git a/autogpt_platform/frontend/src/middleware.ts b/autogpt_platform/frontend/src/middleware.ts
index c2a059c7a6..f8e539b932 100644
--- a/autogpt_platform/frontend/src/middleware.ts
+++ b/autogpt_platform/frontend/src/middleware.ts
@@ -1,6 +1,10 @@
import { authMiddleware } from "@/lib/auth/middleware";
import { SENTRY_TUNNEL_PATH } from "@/lib/sentry-tunnel";
import { relaySentryEnvelope } from "@/lib/sentry-tunnel-middleware";
+import {
+ isPostHogProxyPath,
+ proxyPostHogRequest,
+} from "@/providers/posthog/posthog-proxy-middleware";
import { NextResponse, type NextRequest } from "next/server";
export async function middleware(request: NextRequest) {
@@ -10,17 +14,40 @@ export async function middleware(request: NextRequest) {
return relaySentryEnvelope(request);
}
+ // PostHog's own requests never reach the auth checks: a redirect here would
+ // silently drop events.
+ if (isPostHogProxyPath(request.nextUrl.pathname)) {
+ return proxyPostHogRequest(request) ?? NextResponse.next();
+ }
+
+ const canonicalURL = getCanonicalURL(request);
+ if (canonicalURL) return NextResponse.redirect(canonicalURL, 308);
+
+ return await authMiddleware(request);
+}
+
+function getCanonicalURL(request: NextRequest) {
+ // A plain URL: a cloned NextURL puts a stripped trailing slash back.
+ const url = new URL(request.nextUrl.href);
+ let changed = false;
+
// Redirect www to non-www so auth cookies are issued against a single,
// canonical host and avoid the auth/cookie domain mismatch (#9188).
// Use url.hostname (already lowercase-normalized by the URL parser) instead
// of the raw Host header, which RFC 7230 treats as case-insensitive.
- const url = request.nextUrl.clone();
if (url.hostname.startsWith("www.")) {
url.hostname = url.hostname.slice(4);
- return NextResponse.redirect(url, 308);
+ changed = true;
}
- return await authMiddleware(request);
+ // Next's own trailing-slash redirect is off for the PostHog proxy's sake
+ // (`skipTrailingSlashRedirect` in next.config.mjs), so pages keep it here.
+ if (url.pathname !== "/" && url.pathname.endsWith("/")) {
+ url.pathname = url.pathname.replace(/\/+$/, "") || "/";
+ changed = true;
+ }
+
+ return changed ? url : null;
}
export const config = {
@@ -35,6 +62,9 @@ export const config = {
* itself via httpOnly cookies)
* Feel free to modify this pattern to include more paths.
*
+ * Keep the PostHog proxy path (/relay/pnosthog) matched: middleware is
+ * what forwards it to PostHog.
+ *
* Note: /auth/authorize and /auth/integrations/* ARE protected and need
* middleware to run for authentication checks.
*/
diff --git a/autogpt_platform/frontend/src/providers/posthog/__tests__/posthog-provider.test.tsx b/autogpt_platform/frontend/src/providers/posthog/__tests__/posthog-provider.test.tsx
index 2b2378a544..db31108ab8 100644
--- a/autogpt_platform/frontend/src/providers/posthog/__tests__/posthog-provider.test.tsx
+++ b/autogpt_platform/frontend/src/providers/posthog/__tests__/posthog-provider.test.tsx
@@ -5,7 +5,10 @@ const posthog = vi.hoisted(() => ({
init: vi.fn(),
register: vi.fn(),
}));
-const credentials = vi.hoisted(() => ({ key: "phc_test" as string }));
+const credentials = vi.hoisted(() => ({
+ key: "phc_test" as string,
+ host: "https://eu.i.posthog.com",
+}));
vi.mock("posthog-js", () => ({ default: posthog }));
@@ -22,7 +25,7 @@ vi.mock("@/services/environment", () => ({
isPostHogEnabled: () => true,
getPostHogCredentials: () => ({
key: credentials.key,
- host: "https://eu.i.posthog.com",
+ host: credentials.host,
}),
},
}));
@@ -48,6 +51,32 @@ describe("PostHogProvider", () => {
posthog.init.mockClear();
posthog.register.mockClear();
credentials.key = "phc_test";
+ credentials.host = "https://eu.i.posthog.com";
+ });
+
+ it("sends PostHog Cloud traffic through our own domain", async () => {
+ const { PostHogProvider } = await import("../posthog-provider");
+
+ render(<PostHogProvider>app</PostHogProvider>);
+
+ expect(posthog.init).toHaveBeenCalledWith(
+ "phc_test",
+ expect.objectContaining({
+ api_host: "/relay/pnosthog",
+ ui_host: "https://eu.posthog.com",
+ }),
+ );
+ });
+
+ it("talks to a self-hosted PostHog directly", async () => {
+ credentials.host = "https://posthog.example.com";
+ const { PostHogProvider } = await import("../posthog-provider");
+
+ render(<PostHogProvider>app</PostHogProvider>);
+
+ const config = posthog.init.mock.calls[0][1];
+ expect(config.api_host).toBe("https://posthog.example.com");
+ expect(config).not.toHaveProperty("ui_host");
});
it("registers the base properties once PostHog is initialised", async () => {
diff --git a/autogpt_platform/frontend/src/providers/posthog/__tests__/posthog-proxy.test.ts b/autogpt_platform/frontend/src/providers/posthog/__tests__/posthog-proxy.test.ts
new file mode 100644
index 0000000000..f61201634e
--- /dev/null
+++ b/autogpt_platform/frontend/src/providers/posthog/__tests__/posthog-proxy.test.ts
@@ -0,0 +1,47 @@
+import { describe, expect, it } from "vitest";
+import { getPostHogProxyTarget } from "../posthog-proxy";
+
+describe("getPostHogProxyTarget", () => {
+ it("targets the PostHog Cloud region the host names", () => {
+ expect(
+ getPostHogProxyTarget({
+ key: "phc_test",
+ host: "https://eu.i.posthog.com",
+ }),
+ ).toEqual({
+ apiHost: "https://eu.i.posthog.com",
+ assetsHost: "https://eu-assets.i.posthog.com",
+ uiHost: "https://eu.posthog.com",
+ });
+ expect(
+ getPostHogProxyTarget({
+ key: "phc_test",
+ host: "https://us.i.posthog.com/",
+ }),
+ ).toEqual({
+ apiHost: "https://us.i.posthog.com",
+ assetsHost: "https://us-assets.i.posthog.com",
+ uiHost: "https://us.posthog.com",
+ });
+ });
+
+ it("accepts the older region host without the .i", () => {
+ expect(
+ getPostHogProxyTarget({ key: "phc_test", host: "https://eu.posthog.com" })
+ ?.apiHost,
+ ).toBe("https://eu.i.posthog.com");
+ });
+
+ it("leaves self-hosted, unset or keyless PostHog alone", () => {
+ expect(
+ getPostHogProxyTarget({
+ key: "phc_test",
+ host: "https://posthog.example.com",
+ }),
+ ).toBeNull();
+ expect(getPostHogProxyTarget({ key: "phc_test", host: "" })).toBeNull();
+ expect(
+ getPostHogProxyTarget({ key: "", host: "https://eu.i.posthog.com" }),
+ ).toBeNull();
+ });
+});
diff --git a/autogpt_platform/frontend/src/providers/posthog/posthog-provider.tsx b/autogpt_platform/frontend/src/providers/posthog/posthog-provider.tsx
index 5a8e5706ee..78ee6a3287 100644
--- a/autogpt_platform/frontend/src/providers/posthog/posthog-provider.tsx
+++ b/autogpt_platform/frontend/src/providers/posthog/posthog-provider.tsx
@@ -21,6 +21,7 @@ import {
forgetPostHogStorageWithoutConsent,
getConsentGatedConfig,
} from "./posthog-consent";
+import { getPostHogClientHosts } from "./posthog-proxy";
export function PostHogProvider({ children }: { children: ReactNode }) {
const isPostHogEnabled = environment.isPostHogEnabled();
@@ -38,7 +39,7 @@ export function PostHogProvider({ children }: { children: ReactNode }) {
const anonymousID = getAnonymousID();
forgetPostHogStorageWithoutConsent(postHogCredentials.key);
posthog.init(postHogCredentials.key, {
- api_host: postHogCredentials.host,
+ ...getPostHogClientHosts(postHogCredentials),
defaults: "2025-11-30",
capture_pageview: false,
capture_pageleave: true,
diff --git a/autogpt_platform/frontend/src/providers/posthog/posthog-proxy-middleware.ts b/autogpt_platform/frontend/src/providers/posthog/posthog-proxy-middleware.ts
new file mode 100644
index 0000000000..d10af61aa8
--- /dev/null
+++ b/autogpt_platform/frontend/src/providers/posthog/posthog-proxy-middleware.ts
@@ -0,0 +1,74 @@
+import { NextResponse, type NextRequest } from "next/server";
+import { getPostHogProxyTarget, POSTHOG_PROXY_PATH } from "./posthog-proxy";
+
+export function isPostHogProxyPath(pathname: string) {
+ return (
+ pathname === POSTHOG_PROXY_PATH ||
+ pathname.startsWith(`${POSTHOG_PROXY_PATH}/`)
+ );
+}
+
+// Forwards a proxy-path request to PostHog Cloud (null when not configured).
+// Middleware, not a next.config rewrite: a rewrite forwards every header.
+export function proxyPostHogRequest(request: NextRequest) {
+ const key = process.env.NEXT_PUBLIC_POSTHOG_KEY;
+ const target = getPostHogProxyTarget({
+ key,
+ host: process.env.NEXT_PUBLIC_POSTHOG_HOST,
+ });
+ if (!key || !target) return null;
+
+ const path = request.nextUrl.pathname.slice(POSTHOG_PROXY_PATH.length);
+ const upstream = getUpstreamHost({ path, key, target });
+ if (!upstream) return new NextResponse(null, { status: 404 });
+
+ // Never resolve the path against the host: "//evil.com/x" would replace it.
+ const destination = new URL(upstream);
+ destination.pathname = path;
+ destination.search = request.nextUrl.search;
+
+ const headers = new Headers({ host: destination.host });
+ for (const name of FORWARDED_HEADERS) {
+ const value = request.headers.get(name);
+ if (value !== null) headers.set(name, value);
+ }
+
+ return NextResponse.rewrite(destination, { request: { headers } });
+}
+
+interface UpstreamArgs {
+ path: string;
+ key: string;
+ target: NonNullable<ReturnType<typeof getPostHogProxyTarget>>;
+}
+
+// Any other path on PostHog's hosts would be served as our own origin.
+function getUpstreamHost({ path, key, target }: UpstreamArgs) {
+ if (API_PATHS.has(path)) return target.apiHost;
+ const isAsset =
+ path.startsWith("/static/") ||
+ path === `/array/${key}/config` ||
+ path === `/array/${key}/config.js`;
+ return isAsset ? target.assetsHost : null;
+}
+
+// What posthog-js calls for capture, session replay, feature flags and surveys.
+const API_PATHS = new Set([
+ "/e/",
+ "/i/v0/e/",
+ "/s/",
+ "/flags/",
+ "/api/surveys/",
+]);
+
+// An allowlist: no cookie or auth header, now or added later, reaches PostHog.
+const FORWARDED_HEADERS = [
+ "accept",
+ "accept-encoding",
+ "content-encoding",
+ "content-length",
+ "content-type",
+ "user-agent",
+ // PostHog places the visitor by IP.
+ "x-forwarded-for",
+];
diff --git a/autogpt_platform/frontend/src/providers/posthog/posthog-proxy.ts b/autogpt_platform/frontend/src/providers/posthog/posthog-proxy.ts
new file mode 100644
index 0000000000..9176c253c6
--- /dev/null
+++ b/autogpt_platform/frontend/src/providers/posthog/posthog-proxy.ts
@@ -0,0 +1,31 @@
+// Browser PostHog traffic goes through our own domain so blanket ad-block
+// lists for *.posthog.com don't drop consented visitors' events. Consent is
+// unaffected: posthog-js sends nothing until analytics is accepted.
+// Misspelt on purpose: blocklist rules match the literal word "posthog".
+export const POSTHOG_PROXY_PATH = "/relay/pnosthog";
+
+const POSTHOG_CLOUD_HOST = /^https:\/\/(us|eu)(?:\.i)?\.posthog\.com\/?$/i;
+
+interface PostHogConfig {
+ key?: string;
+ host?: string;
+}
+
+// Only PostHog Cloud is proxied, in whichever region NEXT_PUBLIC_POSTHOG_HOST
+// names. A self-hosted PostHog, or none at all, keeps talking to its own host.
+export function getPostHogProxyTarget({ key, host }: PostHogConfig) {
+ if (!key) return null;
+ const region = host?.trim().match(POSTHOG_CLOUD_HOST)?.[1]?.toLowerCase();
+ if (!region) return null;
+ return {
+ apiHost: `https://${region}.i.posthog.com`,
+ assetsHost: `https://${region}-assets.i.posthog.com`,
+ uiHost: `https://${region}.posthog.com`,
+ };
+}
+
+export function getPostHogClientHosts({ key, host }: PostHogConfig) {
+ const target = getPostHogProxyTarget({ key, host });
+ if (!target) return { api_host: host };
+ return { api_host: POSTHOG_PROXY_PATH, ui_host: target.uiHost };
+}