Skip to content

Commit

Permalink
inject correct next path
Browse files Browse the repository at this point in the history
  • Loading branch information
abvthecity committed Jan 31, 2024
1 parent fe50ef5 commit 0951905
Showing 1 changed file with 26 additions and 3 deletions.
29 changes: 26 additions & 3 deletions packages/ui/app/src/next-app/NextApp.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ export function NextApp({ Component, pageProps, router }: AppProps<Partial<DocsP
useInterceptNextDataHref({
router,
basePath: pageProps.baseUrl?.basePath,
host: pageProps.baseUrl?.domain,
});
return (
<>
Expand All @@ -28,16 +29,38 @@ export function NextApp({ Component, pageProps, router }: AppProps<Partial<DocsP
}

// hack for basepath: https://github.com/vercel/next.js/discussions/25681#discussioncomment-2026813
const useInterceptNextDataHref = ({ router, basePath }: { router: Router; basePath: string | undefined }) => {
const useInterceptNextDataHref = ({
router,
basePath,
host,
}: {
router: Router;
basePath: string | undefined;
host: string | undefined;
}) => {
useEffect(() => {
if (basePath != null && router.pageLoader?.getDataHref) {
const prefixedBasePath = basePath.startsWith("/") ? basePath : `/${basePath}`;
// eslint-disable-next-line jest/unbound-method
const originalGetDataHref = router.pageLoader.getDataHref;
router.pageLoader.getDataHref = function (...args: Parameters<PageLoader["getDataHref"]>) {
const r = originalGetDataHref.call(router.pageLoader, ...args);
return r && r.startsWith("/_next/data") ? `${prefixedBasePath}${r}` : r;
return r && r.startsWith("/_next/data") ? fixHost(`${prefixedBasePath}${r}`, host) : r;
};
}
}, [router, basePath]);
}, [router, basePath, host]);
};

function fixHost(path: string, host: string | undefined) {
// path is like /_next/data/development/.../index.json?host=docs&slug=x&slug=x
// we want to replace the host with the actual host like docs.devexpress.com
if (host == null) {
return path;
}
if (!path.includes("?") || path.includes(`?host=${host}`)) {
return path;
}

// use regex to replace ?host=docs&slug=x&slug=x with ?host=docs.devexpress.com&slug=host&slug=x&slug=x
return path.replace(/(\?host=)([^&]+)/, `$1${host}&slug=$2`);
}

0 comments on commit 0951905

Please sign in to comment.