Link should accept external links #4901
Send to my agentWhich 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.
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
schiller-manuel(GitHub profile, opens in a new tab) added labelstypes
schiller-manuel(GitHub profile, opens in a new tab) added labelsenhancement
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> ); }Thanks for pointing it out @rothsandro My bad indeed. Will post if I manage to get a more solid approach.
Running into this as well. My initial approach was actually specifying the
hrefprop 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
toto navigate to a fully built href, e.g. pointing to an external target.EDIT: Ah I see you noted the issue with the
hrefprop not working at runtime. I feel like that should be highlighted as a bigger issue 😅I have this problem with the normal
Linkcomponent imported fromimport { Link } from "@tanstack/react-router";. I don't think this problem is specific to only custom links.Chiming in here: when using the
hrefprop for an external URL, TS complains about missingto. When adding additionalfromprop here, the TS error abouttodisappears, 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.
This was very unexpected and frustrating, especially as
NavigateOptionssupportshreffor external links, as already mentioned before, docs didn't seem clear on that, at least to me. And changing allhreftotois kinda a hassle in a big migration.birkskyum(GitHub profile, opens in a new tab) added labelspackage: react-router
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:ormailto: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
unsafeboolean 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
Linkcomponent by a styled link, you need to makeCustomLinkPropsitself 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..)
- A
Confirmed on current main. External
tovalues are still rejected by the registered-router types even thoughLinkhandles them at runtime.hrefis present onNavigateOptions, but anhref-onlyLinkstill requiresto. At runtime,Linkalso replaces the suppliedhrefwith the internally built location.Keeping this open. Any implementation should cover
Link,createLink, andlinkOptionswhile preserving params and search validation for internal routes.I'd like to take this. Plan: widen
toin 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. CoversLink,createLinkandlinkOptionsacross react, solid and vue, with type tests. Does that direction work before I start?Gentle bump on this, happy to start on the approach above if it works for you.
Sign in to join this conversation.
Have this issue too since a recent update from
1.121.21to1.132.7. And additionally with usingmailto:...