TanStackT
TanStack2y ago
2 replies
urgent-maroon

Navigating between Micro-Frontends with TanStack Router's <Link> component

Hi everyone,

I'm working on a monorepo with multiple micro-frontends using single-spa and module federation. I'm using TanStack Router for routing within each micro-frontend.

I'm trying to figure out the best way to extend the <Link> component so it can navigate between these micro-frontends. I have a basic implementation that removes the basepath when ignoreBasePath is set to
true
, but I'm not sure if this is the most efficient or recommended approach.

Here's my current code:
import { FC, ReactNode } from "react";
import {
  createLink,
  Link as TanStackLink,
  LinkProps,
  useRouter,
} from "@tanstack/react-router";

interface ExtendedLinkProps extends LinkProps {
  ignoreBasePath?: boolean;
}

export const Link: FC<ExtendedLinkProps> = ({
  ignoreBasePath = false,
  ...restProps
}) => {
  const router = useRouter();

  if (ignoreBasePath) {
    const CustomLink = createLink(
      ({
        href = "",
        children,
        ...rest
      }: {
        href: string;
        children: ReactNode;
        [key: string]: unknown;
      }) => {
        const basePath = router.basepath || "";
        const modifiedHref = href.replace(basePath, "");
        return (
          <a href={modifiedHref} {...rest}>
            {children}
          </a>
        );
      }
    );
    return <CustomLink {...restProps} />;
  } else {
    return <TanStackLink {...restProps} />;
  }
};


Does anyone have experience with this scenario? Are there any best practices or recommended patterns for navigating between micro-frontends using TanStack Router?

Thanks in advance for your help!
Was this page helpful?