Skip to content

Commit

Permalink
fix: rewrite posthog requests to pass in full header context (#1431)
Browse files Browse the repository at this point in the history
  • Loading branch information
abvthecity authored Sep 10, 2024
1 parent 9f6fc49 commit ff82d37
Show file tree
Hide file tree
Showing 4 changed files with 45 additions and 43 deletions.
1 change: 1 addition & 0 deletions packages/ui/docs-bundle/next.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ const nextConfig = {
optimizePackageImports: ["@fern-ui/ui"],
},
trailingSlash: isTruthy(process.env.TRAILING_SLASH),
skipTrailingSlashRedirect: true,
/**
* Customers who opt-in for subpath routing must use rewrite rules from their hosting provider. Because of the
* multi-tenant nature of this app, we cannot set a global basepath in the next.config.js. As a result, the `_next`
Expand Down
13 changes: 13 additions & 0 deletions packages/ui/docs-bundle/src/middleware.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { NextResponse, type NextRequest } from "next/server";
import { rewritePosthog } from "./utils/rewritePosthog";

export function middleware(request: NextRequest): NextResponse {
if (request.nextUrl.pathname.includes("/api/fern-docs/analytics/posthog")) {
return rewritePosthog(request);
}
return NextResponse.next();
}

export const config = {
matcher: ["/api/fern-docs/analytics/posthog/:path*", "/:prefix*/api/fern-docs/analytics/posthog/:path*"],
};

This file was deleted.

31 changes: 31 additions & 0 deletions packages/ui/docs-bundle/src/utils/rewritePosthog.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { withDefaultProtocol } from "@fern-ui/core-utils";
import { NextResponse, type NextRequest } from "next/server";

const DEFAULT_POSTHOG_INSTANCE = "https://us.i.posthog.com";

export function rewritePosthog(request: NextRequest): NextResponse {
const url = request.nextUrl.clone();

const destination = new URL(
withDefaultProtocol(request.headers.get("x-fern-posthog-host") ?? DEFAULT_POSTHOG_INSTANCE),
);

const [, intendedPathname = "/"] = request.nextUrl.pathname.split("/api/fern-docs/analytics/posthog");

const hostname =
intendedPathname.startsWith("/static/") && destination.hostname.endsWith(".i.posthog.com")
? destination.hostname.replace(".i.posthog.com", "-assets.i.posthog.com") // i.e. us.i.posthog.com -> us-assets.i.posthog.com
: destination.hostname;

const requestHeaders = new Headers(request.headers);
requestHeaders.set("host", hostname);

url.pathname = intendedPathname;
url.protocol = "https";
url.hostname = hostname;
url.port = "443";

return NextResponse.rewrite(url, {
headers: requestHeaders,
});
}

0 comments on commit ff82d37

Please sign in to comment.