Skip to content

An open-source, faster Devin alternative

TypeScript

refactor(web): auth on React Query; split context/provider (no eslint disables)

Igor Zalutski3bb0108272bd
diff --git a/web/src/App.tsx b/web/src/App.tsx
index b73d3725..08d777e7 100644
--- a/web/src/App.tsx
+++ b/web/src/App.tsx
@@ -1,5 +1,5 @@
import { Routes, Route, Navigate } from 'react-router-dom'
-import { AuthProvider } from './hooks/useAuth'
+import { AuthProvider } from './hooks/auth-provider'
import ProtectedRoute from './components/ProtectedRoute'
import AppShell from './components/app-shell'
import Dashboard from './pages/Dashboard'
diff --git a/web/src/hooks/auth-provider.tsx b/web/src/hooks/auth-provider.tsx
new file mode 100644
index 00000000..12e53b81
--- /dev/null
+++ b/web/src/hooks/auth-provider.tsx
@@ -0,0 +1,55 @@
+import { useCallback, useEffect, type ReactNode } from 'react'
+import { useQuery, useQueryClient } from '@tanstack/react-query'
+import posthog from 'posthog-js'
+import { getMe, switchOrg as switchOrgApi } from '../api/client'
+import { AuthContext } from './useAuth'
+
+export function AuthProvider({ children }: { children: ReactNode }) {
+ const queryClient = useQueryClient()
+
+ // /me is server state, so React Query owns it. A 401 throws (see apiFetch)
+ // and lands as an error with no data — ProtectedRoute redirects to login.
+ const query = useQuery({
+ queryKey: ['me'],
+ queryFn: getMe,
+ retry: false,
+ staleTime: 60_000,
+ })
+ const { refetch } = query
+ const user = query.data ?? null
+
+ // Identify the analytics user once /me resolves (external-system sync).
+ useEffect(() => {
+ if (user?.id) {
+ posthog.identify(user.id, { email: user.email, org_id: user.orgId })
+ }
+ }, [user])
+
+ const refreshUser = useCallback(async () => {
+ await refetch()
+ }, [refetch])
+
+ const switchOrg = useCallback(
+ async (orgId: string) => {
+ await switchOrgApi(orgId)
+ // Drop all cached queries so no previous-org data lingers in
+ // sandboxes / billing / API keys; the active ['me'] query refetches.
+ queryClient.clear()
+ },
+ [queryClient],
+ )
+
+ // A 401 is an expected unauthenticated state, not a surfaced error.
+ const error =
+ query.error && !/unauthorized/i.test(query.error.message)
+ ? query.error.message
+ : null
+
+ return (
+ <AuthContext.Provider
+ value={{ user, loading: query.isLoading, error, switchOrg, refreshUser }}
+ >
+ {children}
+ </AuthContext.Provider>
+ )
+}
diff --git a/web/src/hooks/useAuth.ts b/web/src/hooks/useAuth.ts
new file mode 100644
index 00000000..96630353
--- /dev/null
+++ b/web/src/hooks/useAuth.ts
@@ -0,0 +1,27 @@
+import { createContext, useContext } from 'react'
+import type { OrgInfo } from '../api/client'
+
+export interface AuthUser {
+ id: string
+ email: string
+ orgId: string
+ orgs?: OrgInfo[]
+}
+
+export interface AuthContextValue {
+ user: AuthUser | null
+ loading: boolean
+ error: string | null
+ switchOrg: (orgId: string) => Promise<void>
+ refreshUser: () => Promise<void>
+}
+
+// Nullable context: `useAuth` throws when used outside <AuthProvider>, so
+// consumers never have to handle a placeholder default.
+export const AuthContext = createContext<AuthContextValue | null>(null)
+
+export function useAuth(): AuthContextValue {
+ const ctx = useContext(AuthContext)
+ if (!ctx) throw new Error('useAuth must be used within an AuthProvider')
+ return ctx
+}
diff --git a/web/src/hooks/useAuth.tsx b/web/src/hooks/useAuth.tsx
deleted file mode 100644
index 55eb739a..00000000
--- a/web/src/hooks/useAuth.tsx
+++ /dev/null
@@ -1,88 +0,0 @@
-import {
- createContext,
- useContext,
- useEffect,
- useState,
- useCallback,
- type ReactNode,
-} from 'react'
-import { useQueryClient } from '@tanstack/react-query'
-import posthog from 'posthog-js'
-import { getMe, switchOrg as switchOrgApi, type OrgInfo } from '../api/client'
-
-interface AuthUser {
- id: string
- email: string
- orgId: string
- orgs?: OrgInfo[]
-}
-
-interface AuthContextValue {
- user: AuthUser | null
- loading: boolean
- error: string | null
- switchOrg: (orgId: string) => Promise<void>
- refreshUser: () => Promise<void>
-}
-
-const AuthContext = createContext<AuthContextValue>({
- user: null,
- loading: true,
- error: null,
- switchOrg: async () => {},
- refreshUser: async () => {},
-})
-
-export function AuthProvider({ children }: { children: ReactNode }) {
- const queryClient = useQueryClient()
- const [user, setUser] = useState<AuthUser | null>(null)
- const [loading, setLoading] = useState(true)
- const [error, setError] = useState<string | null>(null)
-
- const refreshUser = useCallback(async () => {
- try {
- const me = await getMe()
- setUser(me)
- if (me?.id) {
- posthog.identify(me.id, { email: me.email, org_id: me.orgId })
- }
- } catch (err: unknown) {
- if (err instanceof Error && !err.message.includes('Unauthorized')) {
- setError(err.message)
- }
- }
- }, [])
-
- useEffect(() => {
- // Initial auth load on mount. setLoading runs in the promise's .finally
- // (after the fetch settles), not synchronously during the effect.
- // eslint-disable-next-line react-hooks/set-state-in-effect
- refreshUser().finally(() => setLoading(false))
- }, [refreshUser])
-
- const switchOrg = useCallback(
- async (orgId: string) => {
- await switchOrgApi(orgId)
- await refreshUser()
- // Drop all cached queries so no previous-org data lingers in
- // sessions / billing / API keys while the new org loads.
- queryClient.clear()
- },
- [refreshUser, queryClient],
- )
-
- return (
- <AuthContext.Provider
- value={{ user, loading, error, switchOrg, refreshUser }}
- >
- {children}
- </AuthContext.Provider>
- )
-}
-
-// Co-located with the provider by design; the hook export trips react-refresh's
-// component-only rule, which is a fast-refresh DX hint, not a correctness issue.
-// eslint-disable-next-line react-refresh/only-export-components
-export function useAuth() {
- return useContext(AuthContext)
-}