T
TanStack6mo ago
breakable-bronze

Programmatically get path in `__root.tsx`?

I'd like to get the current URL path within my __root.tsx. Is this possible? My goal is to define my canonical URL in my head's links::
{
rel: "canonical",
href: `${import.meta.env.PUBLIC_ORIGIN}${pathname????}`,
},
{
rel: "canonical",
href: `${import.meta.env.PUBLIC_ORIGIN}${pathname????}`,
},
Solutions considered: - Specify this per route to override the head -- I don't want to do this, for this property, b/c not DRY. - window.location.pathname -- won't work b/c of SSR - ctx - the path is not available on the ctx unfortunately.
No description
1 Reply
breakable-bronze
breakable-bronzeOP6mo ago
I found a solution. Use const location = useLocation(); from import { useLocation } from "@tanstack/react-router";, to get location.pathname Then manually create a JSX element for the canonical URL in __root.tsx: <link rel="canonical" href=http://localhost:3000/signup"> and use it as the path there. I was hoping for a solution to do it in the __root.tsx's head, b/c it'd be cleaner and would allow for per-route overrides. But this works ok. Ideal solution: if the head(ctx) function's argument within createRootRouteWithContext() provided the location, so we could use when constructing values for the head.

Did you find this page helpful?