Files
Alaister YoungandAlaister Young 0833c586ac fix(studio): use redirect({ to }) for internal TanStack redirects (#48469)
Hover-preloading any link that points at a redirecting path (e.g. the
org invite "Decline" link to `/projects`) hung the tab under the
TanStack runtime: `redirect({ href })` is treated as an opaque external
target, and the router's preload retry ignores `href` when rebuilding
the location, so it re-runs the same `beforeLoad`, throws the same
redirect, and recurses forever (TanStack/router#7141 — internal targets
must use `to`).

**Changed:**

- `routes/__root.tsx` — the redirect-table `beforeLoad` splits the
destination with `splitInternalUrl()` and throws `redirect({ to, search,
hash, statusCode })` instead of `redirect({ href })`. `to` is
basepath-relative, so the manual `BASE_PATH` prefix goes away too.
- `routes/index.tsx` — same `href` → `to`/`search`/`hash` switch for the
`/` redirects; the "targets aren't in the routeTree yet" comment was
stale (all three destinations resolve to real routes now).
- `OrganizationInvite.tsx` — "Decline" links straight to
`/organizations`, skipping the `/projects` redirect hop entirely.

## To test

- On the TanStack runtime, hover (don't click) a link to a redirecting
path — e.g. the auth overview's "Go to observability" link
(`/project/:ref/reports/auth`) or the 404 page's `/projects` link. The
page must stay responsive (this hung before).
- `/projects` → `/organizations` (307), `/project/:ref/database` →
`/database/tables` (308), `/` → `/org`.
- Query/hash semantics still hold: `/?next=new-project&projectName=x` →
`/new/new-project?projectName=x`;
`/project/:ref/database/wrappers?foo=bar` →
`/integrations?category=wrapper&foo=bar`; `/org/:slug/invoices#other` →
`/org/:slug/billing#invoices`.
- Chained redirects stay bounded: `/project/:ref/database/linter` →
`/advisors/security` in two hops.

All of the above verified locally via Playwright against the TanStack
dev server; `redirects.shared` / `internal-url` / compat-router unit
tests pass.

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

- **Bug Fixes**
- Fixed the invitation “Decline” action to route users to the
Organizations page instead of the Projects page.
- Improved Studio redirect/navigation handling by correctly preserving
URL search parameters and hash fragments and routing to the intended
destination.
- **Tests**
- Updated Organization Invite test expectations to reflect the corrected
“Decline” link destination.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Alaister Young <10985857+alaister@users.noreply.github.com>
2026-07-30 12:42:47 +08:00

203 lines
6.1 KiB
TypeScript

import { useIsLoggedIn, useParams } from 'common'
import Link from 'next/link'
import { useRouter } from 'next/router'
import type { ReactNode } from 'react'
import { toast } from 'sonner'
import { Button, Card, CardContent } from 'ui'
import { Admonition } from 'ui-patterns/Admonition'
import { ShimmeringLoader } from 'ui-patterns/ShimmeringLoader'
import {
getOrganizationInviteContent,
getOrganizationInviteStatus,
} from './OrganizationInvite.utils'
import { OrganizationInviteError } from './OrganizationInviteError'
import {
InterstitialAccountRow,
InterstitialLayout,
SupabaseLogo,
} from '@/components/layouts/InterstitialLayout'
import { useOrganizationAcceptInvitationMutation } from '@/data/organization-members/organization-invitation-accept-mutation'
import { useOrganizationInvitationTokenQuery } from '@/data/organization-members/organization-invitation-token-query'
import { useIsFeatureEnabled } from '@/hooks/misc/useIsFeatureEnabled'
import { useProfile, useProfileNameAndPicture } from '@/lib/profile'
export const OrganizationInvite = () => {
const router = useRouter()
const isLoggedIn = useIsLoggedIn()
const { profile, isLoading: isLoadingProfile } = useProfile()
const { username, avatarUrl, primaryEmail } = useProfileNameAndPicture()
const { slug, token } = useParams()
const isSignUpEnabled = useIsFeatureEnabled('dashboard_auth:sign_up')
const {
data,
error,
isSuccess: isSuccessInvitation,
isError: isErrorInvitation,
isPending: isLoadingInvitation,
} = useOrganizationInvitationTokenQuery(
{ slug, token },
{
retry: false,
refetchOnWindowFocus: false,
enabled: !!profile && !!slug && !!token,
}
)
const inviteStatus = getOrganizationInviteStatus({
data,
error,
isErrorInvitation,
isLoadingInvitation,
isLoadingProfile,
isLoggedIn,
isRouterReady: router.isReady,
isSuccessInvitation,
profileExists: !!profile,
})
const isSignedOut = inviteStatus === 'signed-out'
const isInvitationLoading = inviteStatus === 'loading'
const inviteContent = getOrganizationInviteContent({
data,
error,
isSignUpEnabled,
status: inviteStatus,
})
const hasError = ['wrong-account', 'expired', 'invalid', 'error'].includes(inviteStatus)
const loginRedirectLink = `/sign-in?returnTo=${encodeURIComponent(`/join?token=${token}&slug=${slug}`)}`
const signupRedirectLink = `/sign-up?returnTo=${encodeURIComponent(`/join?token=${token}&slug=${slug}`)}`
const mfaRequiredError = error?.message.includes('MFA required')
const { mutate: joinOrganization, isPending: isJoining } =
useOrganizationAcceptInvitationMutation({
onSuccess: () => {
router.push('/organizations')
},
onError: (error) => {
toast.error(`Failed to join organization: ${error.message}`)
},
})
async function handleJoinOrganization() {
if (!slug) return console.error('Slug is required')
if (!token) return console.error('Token is required')
joinOrganization({ slug, token })
}
const withLayout = (children: ReactNode) => (
<InterstitialLayout
logo={<SupabaseLogo />}
titleClassName="text-xl"
title={
isInvitationLoading ? (
<ShimmeringLoader className="mx-auto h-7 w-36 max-w-full py-0" />
) : (
inviteContent.title
)
}
description={
isInvitationLoading ? (
<ShimmeringLoader className="mx-auto h-4 w-48 max-w-full py-0" />
) : (
inviteContent.description
)
}
>
<div className="px-6 pb-6">{children}</div>
</InterstitialLayout>
)
if (isSignedOut) {
return withLayout(
<div className="flex flex-col gap-2">
<Button asChild variant="primary" block>
<Link href={loginRedirectLink}>Sign in</Link>
</Button>
{isSignUpEnabled && (
<Button asChild variant="default" block>
<Link href={signupRedirectLink}>Create an account</Link>
</Button>
)}
</div>
)
}
if (isInvitationLoading) {
return withLayout(
<div className="flex flex-col gap-6">
<Card className="shadow-none">
<CardContent className="flex items-center gap-3 border-none px-4 py-3">
<ShimmeringLoader className="size-8 flex-shrink-0 rounded-full py-0" />
<div className="min-w-0 flex-1 space-y-2">
<ShimmeringLoader className="h-3 w-20 py-0" />
<ShimmeringLoader className="h-4 w-40 max-w-full py-0" />
</div>
</CardContent>
</Card>
<div className="flex flex-col gap-2">
<ShimmeringLoader className="h-10 w-full py-0" />
<ShimmeringLoader className="h-10 w-full py-0" />
</div>
</div>
)
}
if (inviteStatus === 'no-longer-valid') {
return withLayout(
<div className="flex flex-col gap-3">
<Admonition
type="warning"
description="This invite has already been accepted or declined."
/>
<Button variant="default" block asChild>
<Link href="/">Back to dashboard</Link>
</Button>
</div>
)
}
if (mfaRequiredError) {
return withLayout(
<div className="flex flex-col gap-3">
<Button variant="default" block asChild>
<Link href="/account/security">Go to account settings</Link>
</Button>
</div>
)
}
if (hasError) {
return withLayout(
<OrganizationInviteError
data={data}
error={error}
isError={isErrorInvitation}
isInvalidInvite={inviteStatus === 'invalid'}
/>
)
}
return withLayout(
<div className="flex flex-col gap-6">
<InterstitialAccountRow avatarUrl={avatarUrl} displayName={primaryEmail ?? username ?? ''} />
<div className="flex flex-col gap-2">
<Button
variant="primary"
block
loading={isJoining}
disabled={isJoining}
onClick={handleJoinOrganization}
>
Accept invite
</Button>
<Button asChild variant="text" block>
<Link href="/organizations">Decline</Link>
</Button>
</div>
</div>
)
}