reactjstypescripttanstacktanstack-router

Is there a way to construct a route path as string in Tanstack Router?


Question

I'm using Tanstack Router and Tanstack Start and I'm wondering if there's a way to do something like:

const path = buildPath({ to: "/$lang/posts/$id", params: { lang, id }});

so that path is the resolved string and buildPath only accepts type safe to and params.

Specific use case

I'm using OAuth as an authentication method and I have an api route at /api/auth/google which accepts a redirect query param so that once the authentication is complete the flow ends by redirecting to redirect and I'd like to pass a valid path to this redirect query param like so:

const path = buildPath({ to: "/$lang/posts/$id", params: { lang, id }});

// ...

<a href={`/api/auth/google?redirect=${encodeURIComponent(path)}`}>...</a>

Solution

  • You can build a pathname using:

    const router = useRouter();
    

    and then:

    router.buildLocation({ to: "...", params: { ... }, search: { ... }});
    

    this will return a string that can be used anywhere.


    Credits to Manuel Schiller from the Tanstack Discord Server.