Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: rewrite 404 in middleware #1664

Merged
merged 2 commits into from
Oct 12, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions packages/ui/app/src/analytics/posthog.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,9 @@ function ifCustomer(posthog: PostHog, run: (hog: PostHogWithCustomer) => void):

export async function initializePosthog(api_host: string, customerConfig?: DocsV1Read.PostHogConfig): Promise<void> {
const apiKey = process.env.NEXT_PUBLIC_POSTHOG_API_KEY?.trim() ?? "";
/**
* TODO: refactor this to use the posthog react provider
*/
const posthog = (await import("posthog-js")).default;

if (posthog.__loaded) {
Expand Down
1 change: 1 addition & 0 deletions packages/ui/app/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
export { capturePosthogEvent } from "./analytics/posthog";
export { type CustomerAnalytics } from "./analytics/types";
export type { DocsProps } from "./atoms";
export * from "./docs/DocsPage";
Expand Down
17 changes: 16 additions & 1 deletion packages/ui/docs-bundle/src/middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,21 @@ export const middleware: NextMiddleware = async (request) => {

const pathname = extractNextDataPathname(request.nextUrl.pathname);

/**
* attempt to rewrite /404 and /_error data routes to the correct destination,
* otherwise nextjs will match to `__next_data_catchall`.
*
* this is important for `hardNavigate404` to work, because it relies on knowing that the destination is /404.json
*/
if ((pathname === "/404" || pathname === "/_error") && request.nextUrl.pathname.includes("/_next/data/")) {
const buildId = getBuildId(request);
nextUrl.pathname = `/_next/data/${buildId}${pathname}.json`;
if (nextUrl.pathname === request.nextUrl.pathname) {
return NextResponse.next({ request: { headers } });
}
return NextResponse.rewrite(nextUrl, { request: { headers } });
}

const fernToken = request.cookies.get(COOKIE_FERN_TOKEN);
const authConfig = await getAuthEdgeConfig(xFernHost);
let fernUser: FernUser | undefined;
Expand Down Expand Up @@ -159,7 +174,7 @@ export const config = {
* - _next/image (image optimization files)
* - favicon.ico (favicon file)
*/
"/((?!api/fern-docs|_next/static|_next/image|_next/data/:buildId/404.json|_next/data/:buildId/500.json|_vercel|favicon.ico).*)",
"/((?!api/fern-docs|_next/static|_next/image|_vercel|favicon.ico).*)",
],
};

Expand Down
7 changes: 6 additions & 1 deletion packages/ui/docs-bundle/src/pages/404.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,15 @@
import { capturePosthogEvent } from "@fern-ui/ui";
import Error from "next/error";
import { ReactElement } from "react";
import { ReactElement, useEffect } from "react";

/**
* This is required for Next.js to generate `_next/static/chunks/pages/404.js`
* Which helps prevent a client-side error to be thrown when navigating to a non-existent page
*/
export default function Page(): ReactElement {
useEffect(() => {
capturePosthogEvent("not_found");
});

return <Error statusCode={404} />;
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,12 @@
* In both cases, we want to extract `/learn/home`
*/
export function extractNextDataPathname(pathname: string): string {
if (pathname.includes("/404.json")) {
return "/404";
} else if (pathname.includes("/_error.json")) {
return "/_error";
}

return (
removeIndex(
pathname.match(/\/_next\/data\/.*\/_next\/data\/[^/]*(\/.*)\.json.json/)?.[1] ??
Expand Down
Loading