Type safe router in monorepo #6879
Replies: 1 comment
-
|
The type error happens because each app generates its own route tree types, and your shared Here's how to set this up properly: Option 1: Make your shared form components route-agnostic Don't use router hooks ( // packages/form/src/LoginForm.tsx
interface LoginFormProps {
email?: string
onNavigate: (path: string) => void
}
export function LoginForm({ email, onNavigate }: LoginFormProps) {
// No router dependency — receives everything via props
return (
<form>
<input defaultValue={email} />
<button type="button" onClick={() => onNavigate("/register")}>
Register instead
</button>
</form>
)
}// apps/admin/routes/auth/login.tsx
import { LoginForm } from "@monorepo/form"
import { useSearch, useNavigate } from "@tanstack/react-router"
export function LoginPage() {
const { email } = useSearch({ from: "/auth/login" })
const navigate = useNavigate()
return <LoginForm email={email} onNavigate={(p) => navigate({ to: p })} />
}Option 2: Use generics to accept the router type If you really want router hooks in the shared package, you can make the components generic over the route: // packages/form/src/LoginForm.tsx
import { useSearch } from "@tanstack/react-router"
export function LoginForm<T extends string>({ from }: { from: T }) {
// Use `strict: false` to opt out of typed route matching
const search = useSearch({ strict: false })
const email = (search as any)?.email
// ...
}Using Option 3: Shared route types package Create a package that re-exports common search param types, and have each app's route reference those types. This is more work but gives you full type safety. I'd strongly recommend Option 1 — keeping shared UI components decoupled from the router is the cleanest pattern for monorepos. The router-specific wiring belongs in each app's route files. |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
I have a monorepo with 3 apps admin,user and creator
they all share some same route names
i have created a separate package called Form
in which i have installed tanstack router
in some form i have used for Example:
const {email} = useSearch({from:"_/auth/login"})or link components from routerbut it throws type error when building the app with tsc
please some can guide me through how should i setup my project structure
or what i am doing is correctly fine and remove tsc when building the app.
Beta Was this translation helpful? Give feedback.
All reactions