Skip to content
Source
Sign inSign up
TanStack/router

Link should accept external links #4901

Send to my agent
Openrothsandro(GitHub profile, opens in a new tab) opened this issue 12 comments

Which project does this relate to?

Router

Describe the bug

The Link component, custom link components created with createLink() and possibly linkOptions() only accept internal links but should accept external links (https, mailto, tel, ...) as well.

The Link component could simply be replaced with a plain a element when using external links, but custom link components are often styled or may provide additional behavior which we want to use for external links as well.

There's already a check implemented for external links and passing an external URL for the to prop actually works at runtime but not on a type-level.

https://github.com/TanStack/router/blob/ef74fc661bb82cbc415fcc6645cffcaec9b3b8b7/packages/react-router/src/link.tsx#L88-L94

Your Example Website or App

https://stackblitz.com/edit/github-qe1tnt6t?file=src%2Fmain.tsx

Steps to Reproduce the Bug or Issue

The external links <Link to="https://..." /> work at runtime but produce a TS error. The link with just <Link href="https://..." /> doesn't work at runtime and also produces a TS error (because to is required).

Expected behavior

There should be a way to use (custom) link components with external links without TypeScript errors.

Screenshots or Videos

No response

Platform

  • Router / Start Version: 1.131.2
  • OS: macOS
  • Browser: Brave
  • Browser Version: 1.81.31
  • Bundler: Vite
  • Bundler Version: 6.3.5

Additional context

Related discussion on Discord: https://discord.com/channels/719702312431386674/1391990807225171968

  1. Have this issue too since a recent update from 1.121.21 to 1.132.7. And additionally with using mailto:...

  2. Went with a wrapper approach.

    import { Link as TSLink } from '@tanstack/react-router';
    import type { HTMLAttributes, ReactNode } from 'react';
    
    type TSLinkProps = Parameters<typeof TSLink>[0];
    
    interface Props extends Omit<TSLinkProps, 'to'>, Omit<HTMLAttributes<HTMLAnchorElement>, 'href'> {
      to?: TSLinkProps['to'] | `http://${string}` | `https://${string}` | `mailto:${string}`; // add others as necessary
      children: ReactNode;
    }
    
    export function Link({ to, children, ...props }: Props) {
      const isExternalUrl = typeof to === 'string' && (to.startsWith('http://') || to.startsWith('https://') || to.startsWith('mailto:'));
    
      if (isExternalUrl) {
        return (
          <a href={to} {...props} rel="noopener noreferrer" target="_blank">
            {children}
          </a>
        );
      }
    
      return (
        <TSLink to={to as TSLinkProps['to']} {...props}>
          {children}
        </TSLink>
      );
    }
  3. @alex-parra The wrapper breaks type-safety. The wrapper doesn't require params:

    Image

    TS Playground

  4. Thanks for pointing it out @rothsandro My bad indeed. Will post if I manage to get a more solid approach.

  5. Running into this as well. My initial approach was actually specifying the href prop instead as I thought that should work based on the documentation here, but it seems that it doesn't work for me:

    This can be used instead of to to navigate to a fully built href, e.g. pointing to an external target.

    EDIT: Ah I see you noted the issue with the href prop not working at runtime. I feel like that should be highlighted as a bigger issue 😅

  6. I have this problem with the normal Link component imported from import { Link } from "@tanstack/react-router";. I don't think this problem is specific to only custom links.

  7. Chiming in here: when using the href prop for an external URL, TS complains about missing to. When adding additional from prop here, the TS error about to disappears, but the Link does not navigate to the external URL at runtime, but rather to .

    Was also confused by the docs stating that this should work.

  8. This was very unexpected and frustrating, especially as NavigateOptions supports href for external links, as already mentioned before, docs didn't seem clear on that, at least to me. And changing all href to to is kinda a hassle in a big migration.

  9. birkskyum(GitHub profile, opens in a new tab) added labelspackage: react-router

  10. I'm currently rewriting a single-page-app from react router to Tanstack Router. This is one of the issues I'm facing.

    Data, including links, is coming from a headless CMS and could be anything:

    • A tel: or mailto: link
    • A file
    • An external link
    • An internal page → tanstack router should pick this up, so there's no full page reload

    I used to have a custom Link component for styling and some additional logic, like setting additional attributes when it's external. This same component was also used for static internal links (where we want type-safety).

    After a lot of fiddling around I came up with this wrapper component, that keeps type-safety unless the unsafe boolean prop is set (see updated playground -thanks @rothsandro).

    import {
      type LinkComponentProps,
      type RegisteredRouter,
      Link as TSLink,
      useRouter,
    } from "@tanstack/react-router";
    
    type SafeProps = LinkComponentProps<"a"> & { unsafe?: false };
    type UnsafeProps = Omit<LinkComponentProps<"a">, "to"> & {
      unsafe: true;
      to: string;
    };
    export type CustomLinkProps = SafeProps | UnsafeProps;
    
    interface CustomLink {
      <
        const TFrom extends string = string,
        const TTo extends string | undefined = undefined,
        const TMaskFrom extends string = TFrom,
        const TMaskTo extends string = '',
      >(
        props: LinkComponentProps<'a', RegisteredRouter, TFrom, TTo, TMaskFrom, TMaskTo> & {
          unsafe?: false;
        },
      ): React.ReactElement;
      (props: UnsafeProps): React.ReactElement;
    }
    
    /**
     * Wraps Tanstack router's Link component, but allows any `to` string when `unsafe` is passed.
     */
    export const Link: CustomLink = (props: CustomLinkProps): React.ReactElement {
      const router = useRouter();
    
      if (!props.unsafe) {
        const { unsafe: _unsafe, ...rest } = props;
        return <TSLink {...(rest as SafeProps)} />;
      }
    
      const { unsafe: _unsafe, to, ...rest } = props;
      const path = sameOriginPath(to);
    
      if (path && router.getMatchedRoutes(path).foundRoute) {
        // Validated at runtime
        return <TSLink {...(rest as object)} to={path as LinkComponentProps["to"]} />;
      }
    
      // This is totally optional -for external links
      const anchorRest = rest as React.ComponentPropsWithoutRef<"a">;
      if (to.startsWith("http")) {
        anchorRest.target = "_blank";
        anchorRest.rel = "noopener noreferrer";
      }
    
      return <a {...anchorRest} href={to} />;
    }
    
    /**
     * Strips origin if it is the same, so TS Router can take over (no page reload)
     */
    function sameOriginPath(to: string): string | null {
      if (to.startsWith("/") || to.startsWith("#")) return to;
      try {
        const url = new URL(to);
        if (url.origin === window.location.origin) {
          return `${url.pathname}${url.search}${url.hash}`;
        }
      } catch {}
      return to;
    }
    Consideration: Of course it would be possible to use the stock "TSLink" component for internal routes and a custom one for the CMS routes, then just `as LinkComponentProps` the whole thing (it will work runtime). But suppose you want to add another wrapper -a `StyledLink` component. Then you need to make 2 variants again. You can see where this goes.

    If you want to wrap this Link component by a styled link, you need to make CustomLinkProps itself a generic too:

    interface LinkLike<TExtra extends object = {}> {
      <
        const TFrom extends string = string,
        const TTo extends string | undefined = undefined,
        const TMaskFrom extends string = TFrom,
        const TMaskTo extends string = '',
      >(
        props: LinkComponentProps<'a', RegisteredRouter, TFrom, TTo, TMaskFrom, TMaskTo> & {
          unsafe?: false;
        } & TExtra,
      ): React.ReactElement;
      (props: UnsafeProps & TExtra): React.ReactElement;
    }
    
    // then use like so:
    
    type StyledLinkProps = {
      size?: "base" | "small";
    };
    
    export const StyledLink: LinkLike<StyledLinkProps> = ({
      size = "inherit",
      className,
      ...props
    }: CustomLinkProps & StyledLinkProps) => {
      const cls = clsx(style.link, style[size], className);
    
      // `props` is still the safe|unsafe union here. Spreading the union into the
      // overloaded `Link` matches NEITHER overload, so narrow on `unsafe` first;
      // each branch then forwards a single, concrete shape.
      // This is anything but pretty...
      if (props.unsafe) {
        return <Link className={cls} {...props} />;
      }
      return <Link className={cls} {...props} />;
    };

    Disclaimer: had some AI help for this

    It would be a very convenient QoL feature to have on the original Tanstack Router Link component. Is this something you would consider in one form or another @birkskyum? (tagged you as maintainer..)

  11. Confirmed on current main. External to values are still rejected by the registered-router types even though Link handles them at runtime.

    href is present on NavigateOptions, but an href-only Link still requires to. At runtime, Link also replaces the supplied href with the internally built location.

    Keeping this open. Any implementation should cover Link, createLink, and linkOptions while preserving params and search validation for internal routes.

  12. I'd like to take this. Plan: widen to in router-core so absolute URLs (with a scheme) are accepted and rendered as a plain <a href>, skipping route matching, while internal paths keep full params/search typing and validation. Covers Link, createLink and linkOptions across react, solid and vue, with type tests. Does that direction work before I start?

  13. Gentle bump on this, happy to start on the approach above if it works for you.

Sign in to join this conversation.