Skip to content

armgit / spree

Public Imported from GitHub
0

Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.

Admin SPA: Simplify authentication status checking (#13992)

Damian Legawiec9f38d2ad9d4a
diff --git a/packages/admin/src/main.tsx b/packages/admin/src/main.tsx
index 07b1599ba1..da651d36e2 100644
--- a/packages/admin/src/main.tsx
+++ b/packages/admin/src/main.tsx
@@ -4,20 +4,13 @@ import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import { ConfirmProvider } from '@/components/spree/confirm-dialog'
import { TooltipProvider } from '@/components/ui/tooltip'
-import { useAuth } from '@/hooks/use-auth'
import { queryClient } from '@/lib/query-client'
import { AuthProvider } from '@/providers/auth-provider'
-import { PermissionProvider, usePermissions } from '@/providers/permission-provider'
+import { PermissionProvider } from '@/providers/permission-provider'
import { ThemeProvider } from '@/providers/theme-provider'
import { router } from '@/router'
import './index.css'
-function InnerApp() {
- const auth = useAuth()
- const { permissions } = usePermissions()
- return <RouterProvider router={router} context={{ auth, permissions }} />
-}
-
createRoot(document.getElementById('root')!).render(
<StrictMode>
<QueryClientProvider client={queryClient}>
@@ -26,7 +19,7 @@ createRoot(document.getElementById('root')!).render(
<PermissionProvider>
<TooltipProvider>
<ConfirmProvider>
- <InnerApp />
+ <RouterProvider router={router} />
</ConfirmProvider>
</TooltipProvider>
</PermissionProvider>
diff --git a/packages/admin/src/providers/auth-provider.tsx b/packages/admin/src/providers/auth-provider.tsx
index fb2356d95d..c0e6775575 100644
--- a/packages/admin/src/providers/auth-provider.tsx
+++ b/packages/admin/src/providers/auth-provider.tsx
@@ -1,6 +1,5 @@
import { createContext, type ReactNode, useCallback, useEffect, useRef, useState } from 'react'
import { adminClient } from '@/client'
-import { router } from '@/router'
interface AuthUser {
id: string
@@ -13,9 +12,9 @@ interface AuthContextValue {
user: AuthUser | null
token: string | null
isAuthenticated: boolean
- /** True while the cold-load `/auth/refresh` bootstrap is in flight. Routes should wait. */
+ /** True until the cold-load /auth/refresh bootstrap settles. */
isInitializing: boolean
- /** True while the user is actively signing in (login form). */
+ /** True while a login submission is in flight. */
isLoading: boolean
login: (email: string, password: string) => Promise<void>
logout: () => Promise<void>
@@ -24,7 +23,6 @@ interface AuthContextValue {
export const AuthContext = createContext<AuthContextValue | null>(null)
// Refresh ~30s before the JWT expires (default 5min TTL).
-// 401s on slow requests are still handled via adminClient.onUnauthorized retry.
const REFRESH_INTERVAL_MS = 4 * 60 * 1000 + 30 * 1000
export function AuthProvider({ children }: { children: ReactNode }) {
@@ -33,7 +31,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {
const [isInitializing, setIsInitializing] = useState(true)
const [isLoading, setIsLoading] = useState(false)
const refreshTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
- // Serialize all refresh calls — prevents double-rotation from StrictMode/HMR.
+ // Serialize concurrent refresh calls so StrictMode/HMR/401-retry don't double-rotate.
const refreshPromiseRef = useRef<Promise<boolean> | null>(null)
const clearRefreshTimer = useCallback(() => {
@@ -43,13 +41,10 @@ export function AuthProvider({ children }: { children: ReactNode }) {
}
}, [])
- // beforeLoad guards capture context at navigation time. Invalidate the router
- // here so any pending guards re-run with the fresh auth state.
const applySession = useCallback((accessToken: string, authUser: AuthUser) => {
adminClient.setToken(accessToken)
setToken(accessToken)
setUser(authUser)
- router.invalidate()
}, [])
const clearSession = useCallback(() => {
@@ -57,7 +52,6 @@ export function AuthProvider({ children }: { children: ReactNode }) {
setToken(null)
setUser(null)
clearRefreshTimer()
- router.invalidate()
}, [clearRefreshTimer])
const doRefresh = useCallback(async (): Promise<boolean> => {
@@ -71,7 +65,6 @@ export function AuthProvider({ children }: { children: ReactNode }) {
}
}, [applySession, clearSession])
- // Serialize: if a refresh is already in flight, await the same promise.
const refreshAccessToken = useCallback((): Promise<boolean> => {
if (refreshPromiseRef.current) return refreshPromiseRef.current
const promise = doRefresh().finally(() => {
@@ -107,14 +100,12 @@ export function AuthProvider({ children }: { children: ReactNode }) {
try {
await adminClient.auth.logout()
} catch {
- // Network/server failures shouldn't trap the user — clear locally regardless.
- // The server-side refresh row will expire naturally if the call didn't reach it.
+ // Server unreachable — clear locally; the row will expire naturally.
} finally {
clearSession()
}
}, [clearSession])
- // Register the 401 handler: refresh token (driven by cookie) and let the SDK retry.
// biome-ignore lint/correctness/useExhaustiveDependencies: only run on mount
useEffect(() => {
adminClient.onUnauthorized(async () => {
@@ -124,20 +115,13 @@ export function AuthProvider({ children }: { children: ReactNode }) {
})
}, []) // eslint-disable-line react-hooks/exhaustive-deps
- // Cold-load bootstrap: try to refresh from the cookie. If we get an access token,
- // hydrate the in-memory state. If not, stay logged out — routes will redirect to /login.
// biome-ignore lint/correctness/useExhaustiveDependencies: only run on mount
useEffect(() => {
refreshAccessToken()
.then((success) => {
if (success) scheduleRefresh()
})
- .finally(() => {
- setIsInitializing(false)
- // Guards return early while isInitializing — invalidate so they re-run
- // now that the cold-load decision has settled.
- router.invalidate()
- })
+ .finally(() => setIsInitializing(false))
return clearRefreshTimer
}, []) // eslint-disable-line react-hooks/exhaustive-deps
diff --git a/packages/admin/src/router.tsx b/packages/admin/src/router.tsx
index e67922a487..51ce5b5fc1 100644
--- a/packages/admin/src/router.tsx
+++ b/packages/admin/src/router.tsx
@@ -1,14 +1,7 @@
import { createRouter } from '@tanstack/react-router'
-import type { Permissions } from '@/providers/permission-provider'
import { routeTree } from './routeTree.gen'
-export const router = createRouter({
- routeTree,
- context: {
- auth: undefined!,
- permissions: undefined! as Permissions,
- },
-})
+export const router = createRouter({ routeTree })
declare module '@tanstack/react-router' {
interface Register {
diff --git a/packages/admin/src/routes/__root.tsx b/packages/admin/src/routes/__root.tsx
index 22d127e26a..f990ab8cfc 100644
--- a/packages/admin/src/routes/__root.tsx
+++ b/packages/admin/src/routes/__root.tsx
@@ -1,17 +1,7 @@
-import { createRootRouteWithContext, Outlet } from '@tanstack/react-router'
+import { createRootRoute, Outlet } from '@tanstack/react-router'
import { Toaster } from 'sonner'
-import type { Permissions } from '@/providers/permission-provider'
-interface RouterContext {
- auth: {
- isAuthenticated: boolean
- isInitializing: boolean
- token: string | null
- }
- permissions: Permissions
-}
-
-export const Route = createRootRouteWithContext<RouterContext>()({
+export const Route = createRootRoute({
component: RootLayout,
})
diff --git a/packages/admin/src/routes/_authenticated.tsx b/packages/admin/src/routes/_authenticated.tsx
index 20100da4a9..23178d28ae 100644
--- a/packages/admin/src/routes/_authenticated.tsx
+++ b/packages/admin/src/routes/_authenticated.tsx
@@ -1,18 +1,13 @@
-import { createFileRoute, Outlet, redirect } from '@tanstack/react-router'
+import { createFileRoute, Navigate, Outlet } from '@tanstack/react-router'
+import { useAuth } from '@/hooks/use-auth'
export const Route = createFileRoute('/_authenticated')({
- beforeLoad: ({ context }) => {
- // Wait for the cold-load `/auth/refresh` bootstrap before deciding to redirect —
- // otherwise an authenticated user with a valid refresh cookie would be bounced
- // to /login during the first render pass.
- if (context.auth.isInitializing) return
- if (!context.auth.isAuthenticated) {
- throw redirect({ to: '/login' })
- }
- },
component: AuthenticatedLayout,
})
function AuthenticatedLayout() {
+ const { isInitializing, isAuthenticated } = useAuth()
+ if (isInitializing) return null
+ if (!isAuthenticated) return <Navigate to="/login" replace />
return <Outlet />
}
diff --git a/packages/admin/src/routes/_authenticated/index.tsx b/packages/admin/src/routes/_authenticated/index.tsx
index e76bc33131..e79d799c33 100644
--- a/packages/admin/src/routes/_authenticated/index.tsx
+++ b/packages/admin/src/routes/_authenticated/index.tsx
@@ -1,22 +1,28 @@
-import { createFileRoute, redirect } from '@tanstack/react-router'
+import { createFileRoute, useNavigate } from '@tanstack/react-router'
+import { useEffect } from 'react'
import { adminClient } from '@/client'
export const Route = createFileRoute('/_authenticated/')({
- beforeLoad: async ({ context }) => {
- // Wait for bootstrap; the parent _authenticated guard will redirect to /login
- // if we end up unauthenticated. Without this guard, we'd fire a /store request
- // with no token during cold load and trigger a refresh loop.
- if (context.auth.isInitializing || !context.auth.isAuthenticated) return
+ component: IndexRedirect,
+})
+
+function IndexRedirect() {
+ const navigate = useNavigate()
- // Fetch the current store to get its prefixed ID for the URL
- try {
- const store = await adminClient.store.get()
- throw redirect({ to: '/$storeId', params: { storeId: store.id } })
- } catch (e) {
- // If it's already a redirect, re-throw
- if (e instanceof Error && 'to' in e) throw e
- // Fallback: use 'default' as store ID
- throw redirect({ to: '/$storeId', params: { storeId: 'default' } })
+ useEffect(() => {
+ let cancelled = false
+ adminClient.store
+ .get()
+ .then((store) => {
+ if (!cancelled) navigate({ to: '/$storeId', params: { storeId: store.id }, replace: true })
+ })
+ .catch(() => {
+ if (!cancelled) navigate({ to: '/$storeId', params: { storeId: 'default' }, replace: true })
+ })
+ return () => {
+ cancelled = true
}
- },
-})
+ }, [navigate])
+
+ return null
+}
diff --git a/packages/admin/src/routes/login.tsx b/packages/admin/src/routes/login.tsx
index 79f09e0ede..4ea1da7e7d 100644
--- a/packages/admin/src/routes/login.tsx
+++ b/packages/admin/src/routes/login.tsx
@@ -1,5 +1,5 @@
import { zodResolver } from '@hookform/resolvers/zod'
-import { createFileRoute, redirect, useRouter } from '@tanstack/react-router'
+import { createFileRoute, Navigate } from '@tanstack/react-router'
import { useForm } from 'react-hook-form'
import { z } from 'zod/v4'
import { Button } from '@/components/ui/button'
@@ -17,19 +17,11 @@ const loginSchema = z.object({
type LoginForm = z.infer<typeof loginSchema>
export const Route = createFileRoute('/login')({
- beforeLoad: ({ context }) => {
- // Same reasoning as in _authenticated.tsx — don't decide while bootstrap is in flight.
- if (context.auth.isInitializing) return
- if (context.auth.isAuthenticated) {
- throw redirect({ to: '/' }) // Will redirect to /$storeId via _authenticated/index
- }
- },
component: LoginPage,
})
function LoginPage() {
- const { login, isLoading } = useAuth()
- const router = useRouter()
+ const { login, isLoading, isAuthenticated } = useAuth()
const form = useForm<LoginForm>({
resolver: zodResolver(loginSchema),
@@ -39,13 +31,13 @@ function LoginPage() {
const onSubmit = async (data: LoginForm) => {
try {
await login(data.email, data.password)
- await router.invalidate()
- await router.navigate({ to: '/' })
} catch {
form.setError('root', { message: 'Invalid email or password' })
}
}
+ if (isAuthenticated) return <Navigate to="/" replace />
+
return (
<div className="flex min-h-svh flex-col items-center justify-center gap-6 bg-muted p-6 md:p-10">
<div className="flex w-full max-w-sm flex-col gap-6">