Files
supabase/apps/studio/lib/profile.tsx
Alaister YoungandAlaister Young d98f706b7c [FE-5109] (part 1) refactor(studio): migrate core hooks, lib, and prefetchers off next/router (#54053)
Part 1 of a 6-PR stack migrating all `next/router` and
`next/compat/router` imports in `apps/studio` onto TanStack Router hooks
and removing the router shims.

| Part | PR | Scope |
| --- | --- | --- |
| **1** | **#54053 ← this PR** | **Core navigation helpers, `hooks/**`,
`lib/**`, `data/prefetchers/**`** |
| 2 | #54054 | `components/ui/**` |
| 3 | #54055 | `components/layouts/**` and `state/tabs.tsx` |
| 4 | #54056 | Database, Branching, Compute, Edge Functions, Explorer,
SQL Editor, Storage, Table Editor |
| 5 | #54057 | Remaining `components/interfaces/**` and
`QueryInsightsTable` router events |
| 6 | #54058 | Remove `next/router` & `next/compat/router` shims,
`_router-events.ts`, Vite aliases, and test mocks |

Introduces the shared TanStack navigation helpers needed across the
stack and migrates `hooks/**`, `lib/**`, and `data/prefetchers/**` off
`next/router`.

**Added:**

- `navigateToUrl` in `apps/studio/lib/navigation.ts` (plus unit tests in
`lib/navigation.test.ts`): shared helper for navigating to internal
string URLs via TanStack's `useNavigate` (splitting pathname, search
params, and hash via `splitInternalUrl`, and handling
external/protocol-relative URLs)
- `useRoutePattern` in `apps/studio/hooks/misc/useRoutePattern.ts` (plus
`useRoutePattern.test.tsx`): returns the active matched TanStack route
template (e.g. `/project/$ref/editor/$id`) as the replacement for Next's
`router.pathname`

**Changed:**

- Migrated `hooks/misc/*` (`useHydratedQuery`,
`useStudioCommandMenuTelemetry`, `useTableEditorFiltersSort`,
`withAuth`) and `hooks/use-check-latest-deploy.tsx` to TanStack's
`useLocation`, `useNavigate`, `useRoutePattern`, and `useParams` from
`common`
- Migrated `lib/profile.tsx` and `lib/telemetry/track.ts` off
`next/router`
- Migrated `data/prefetchers/project.$ref.tsx`,
`project.$ref.editor.tsx`, and `project.$ref.editor.$id.tsx` to
`useRouter().preloadRoute`
- Wrapped `ReactQueryTestConfig` in `apps/studio/tests/helpers.tsx` with
`RouterContextProvider` and updated hook/navigation tests
(`useTableEditorFiltersSort*.test.*`,
`useFilterLifeCycle.navigation.test.tsx`,
`useTableFilter.navigation.test.tsx`, `useInboundBranding.test.ts`,
`state/tabs.test.ts`)

**Simplified:**

- `navigateToUrl` passes `replace` straight through and documents that
`url` must be an app-relative path or an external URL.
`StudioFrameworkProvider`'s `push` now reuses it.
- `useRoutePattern` reads matches and location in a single
`useRouterState` subscription
- `useTrack` and `useStudioCommandMenuTelemetry` take the pathname from
`useFramework()`, the same source as pageviews, so custom events and
pageviews always send the same pattern (e.g. `/project/[ref]/sql/[id]`).
New tests pin the strings sent, and `toRoutePattern` now has its own
unit tests.
- Removed `useCurrentPath` (a one-line wrapper with one consumer):
`OrganizationSettingsLayout` calls `useLocation` directly
- Dropped the no-op `.catch(() => {})` on `preloadRoute` in the
prefetchers (`preloadRoute` never rejects)
- `useTableEditorFiltersSort` builds the next search with a spread
instead of a delete loop
- Added `createTestRouter()` to `tests/lib/custom-render.tsx`, and
`customRender`/`customRenderHook` now return the `router`. The rest of
the stack uses these instead of hand-copied `createRouter` setups.

Addresses
[FE-5109](https://linear.app/supabase/issue/FE-5109/replace-the-nextrouter-shims-with-tanstack-router-hooks)

## To test

- [ ] Auth redirect flow (`withAuth`) still preserves `returnTo` query
parameters when redirecting unauthenticated users to `/sign-in`
- [ ] Table Editor sort and filter URL sync
(`useTableEditorFiltersSort`) persists and clears `?sort=` / `?filter=`
across table switches
- [ ] Hovering project and table editor links still triggers route/data
prefetching without console errors
- [ ] Page view and command menu telemetry still records route patterns
and paths accurately

---------

Co-authored-by: Alaister Young <10985857+alaister@users.noreply.github.com>
2026-11-27 09:37:49 +00:00

158 lines
5.3 KiB
TypeScript

import * as Sentry from '@sentry/react'
import { useQueryClient } from '@tanstack/react-query'
import { useNavigate } from '@tanstack/react-router'
import { useIsLoggedIn, useUser } from 'common'
import { createContext, PropsWithChildren, useContext, useEffect, useMemo } from 'react'
import { toast } from 'sonner'
import { useSignOut } from './auth'
import { getGitHubProfileImgUrl } from './github'
import { organizationKeys } from '@/data/organizations/keys'
import { permissionKeys } from '@/data/permissions/keys'
import { usePermissionsQuery } from '@/data/permissions/permissions-query'
import { usePermissionsQueryV2 } from '@/data/permissions/permissions-query-v2'
import { profileKeys } from '@/data/profile/keys'
import { useProfileCreateMutation } from '@/data/profile/profile-create-mutation'
import { useProfileIdentitiesQuery } from '@/data/profile/profile-identities-query'
import { useProfileQuery } from '@/data/profile/profile-query'
import type { Profile } from '@/data/profile/types'
import type { StudioError } from '@/lib/errors/studio-errors'
import { useTrack } from '@/lib/telemetry/track'
export type ProfileContextType = {
profile: Profile | undefined
error: StudioError | null
isLoading: boolean
isError: boolean
isSuccess: boolean
}
export const ProfileContext = createContext<ProfileContextType>({
profile: undefined,
error: null,
isLoading: true,
isError: false,
isSuccess: false,
})
export const ProfileProvider = ({ children }: PropsWithChildren<{}>) => {
const user = useUser()
const queryClient = useQueryClient()
const isLoggedIn = useIsLoggedIn()
const navigate = useNavigate()
const signOut = useSignOut()
const track = useTrack()
const { mutate: createProfile, isPending: isCreatingProfile } = useProfileCreateMutation({
onSuccess: () => {
track('sign_up', { category: 'conversion' })
if (user) {
// Send an event to GTM, will do nothing if GTM is not enabled
const thisWindow = window as any
thisWindow.dataLayer = thisWindow.dataLayer || []
thisWindow.dataLayer.push({
event: 'sign_up',
email: user.email,
})
}
},
onError: (error) => {
if (error.code === 409) {
// The profile already exists (e.g. GET hit a lagging replica, or it was created
// elsewhere), so the earlier "not found" is stale. Refetch rather than leaving the
// user stuck on the cached error. Sentry capture is kept to monitor how often this occurs.
Sentry.captureMessage('Profile already exists: ' + error.message)
queryClient.invalidateQueries({ queryKey: profileKeys.profile() })
queryClient.invalidateQueries({ queryKey: organizationKeys.list() })
queryClient.invalidateQueries({ queryKey: permissionKeys.list() })
} else {
Sentry.captureMessage('Failed to create users profile: ' + error.message)
toast.error('Failed to create your profile. Please refresh to try again.')
}
},
})
// Track telemetry for the current user
const {
error,
data: profile,
isPending: isLoadingProfile,
isError,
isSuccess,
} = useProfileQuery({
enabled: isLoggedIn,
})
const isProfileNotFound = isError && error?.message === "User's profile not found"
useEffect(() => {
if (!isProfileNotFound || !user?.id) return
createProfile()
}, [isProfileNotFound, user?.id, createProfile])
// [Alaister] If the user has a bad auth token, auth-js won't know about it
// and will think the user is authenticated. Since fetching the profile happens
// on every page load, we can check for a 401 here and sign the user out if
// they have a bad token.
const isUnauthorized = isError && error?.code === 401
useEffect(() => {
if (!isUnauthorized) return
signOut().then(() => void navigate({ to: '/sign-in' }))
}, [isUnauthorized, signOut, navigate])
const { isInitialLoading: isLoadingPermissions } = usePermissionsQuery({ enabled: isLoggedIn })
const { isInitialLoading: isLoadingPermissionsV2 } = usePermissionsQueryV2({
enabled: isLoggedIn,
})
const value = useMemo(() => {
const isLoading =
isLoadingProfile || isCreatingProfile || isLoadingPermissions || isLoadingPermissionsV2
return {
error,
profile,
isLoading,
isError,
isSuccess,
}
}, [
isLoadingProfile,
isCreatingProfile,
isLoadingPermissions,
isLoadingPermissionsV2,
profile,
error,
isError,
isSuccess,
])
return <ProfileContext.Provider value={value}>{children}</ProfileContext.Provider>
}
export const useProfile = () => useContext(ProfileContext)
export function useProfileNameAndPicture(): {
username?: string
primaryEmail?: string
avatarUrl?: string
isLoading: boolean
} {
const { profile, isLoading: isLoadingProfile } = useProfile()
const { data: identitiesData, isPending: isLoadingIdentities } = useProfileIdentitiesQuery()
const isGitHubProfile = profile?.auth0_id?.startsWith('github')
const gitHubUsername = isGitHubProfile
? identitiesData?.identities.find((x) => x.provider === 'github')?.identity_data?.user_name
: undefined
const avatarUrl = isGitHubProfile ? getGitHubProfileImgUrl(gitHubUsername) : undefined
return {
username: profile?.username,
primaryEmail: profile?.primary_email,
avatarUrl,
isLoading: isLoadingProfile || isLoadingIdentities,
}
}