T
TanStack2mo ago
fair-rose

Type safe create url

Hello guys, I need to create a type-safe recovery password email with a token as URL search params. I would like to have a function that generates that URL like a Link component, but I haven’t found anything. I created this utility function to solve the problem, but it would be great if the router provided something like this.
import type { LinkProps, RegisteredRouter } from "@tanstack/react-router";

type CreateUrl<TTo extends string> = LinkProps<
unknown,
RegisteredRouter,
string,
TTo,
string,
string
> & {
to: TTo;
};

export function createUrl<TTo extends string>(props: CreateUrl<TTo>) {
const domain = process.env.DOMAIN;

const url = new URL(props.to, domain);
Object.entries(props.search ?? {}).forEach(([key, value]) => {
url.searchParams.set(key, value);
});
return url.toString();
}
import type { LinkProps, RegisteredRouter } from "@tanstack/react-router";

type CreateUrl<TTo extends string> = LinkProps<
unknown,
RegisteredRouter,
string,
TTo,
string,
string
> & {
to: TTo;
};

export function createUrl<TTo extends string>(props: CreateUrl<TTo>) {
const domain = process.env.DOMAIN;

const url = new URL(props.to, domain);
Object.entries(props.search ?? {}).forEach(([key, value]) => {
url.searchParams.set(key, value);
});
return url.toString();
}
1 Reply
graceful-blue
graceful-blue2mo ago
router.buildLocation()

Did you find this page helpful?