fix(web): stop flooding console with 401 ApiError during initial load
Some checks failed
CI / E2E Tests (push) Has been skipped
CodeQL Analysis / CodeQL (javascript-typescript) (push) Failing after 1m5s
Deploy / Build API Image (push) Failing after 27s
Deploy / Build Web Image (push) Failing after 12s
Deploy / Build AI Services Image (push) Failing after 10s
E2E Tests / Playwright E2E (push) Failing after 16s
Security Scanning / Dependency Audit (pnpm) (push) Failing after 3s
Security Scanning / Trivy Scan — API Image (push) Failing after 57s
Deploy / Deploy to Staging (push) Has been cancelled
Deploy / Rollback Staging (push) Has been cancelled
Deploy / Smoke Test Production (push) Has been cancelled
Deploy / Rollback Production (push) Has been cancelled
CI / Lint → Typecheck → Test → Build (22) (push) Failing after 11s
Deploy / Smoke Test Staging (push) Has been cancelled
Deploy / Deploy to Production (push) Has been cancelled
Security Scanning / Trivy Scan — Web Image (push) Failing after 46s
Security Scanning / Trivy Filesystem Scan (push) Has been cancelled
Security Scanning / Security Gate (push) Has been cancelled
Security Scanning / Trivy Scan — AI Services Image (push) Has been cancelled

Five compounding problems caused hundreds of "Console ApiError:
Unauthorized" entries on every load of /dashboard (and friends) while
unauthenticated or while the auth cookie was stale:

1. QueryClient had `throwOnError: true` as a blanket default, so every
   401 from any react-query hook propagated to the nearest error
   boundary instead of staying in the query's `error` state. That
   also invited React to re-render and re-fire the boundary multiple
   times per failing query.

2. React Query retried all failures 3 times with exponential backoff,
   so a single 401 became four requests. 401 isn't fixable by retry,
   so this is just noise.

3. Dashboard layout rendered `<NotificationBell />` unconditionally,
   which polled /notifications/unread-count on mount even when no user
   was signed in → 401 on every mount.

4. Dashboard + Admin layouts had no redirect-to-login guard, so
   protected queries (market-report, heatmap, admin/dashboard, …) all
   mounted and fired against the API before the user ever saw the
   login screen.

5. Admin layout waited on `user` but had no way to distinguish "store
   still initialising" from "user genuinely absent" — so an expired
   cookie left the page stuck on a spinner while the same 401 storm
   played out in the background.

Fixes
- query-client.ts: `throwOnError` and `retry` are now predicates. Only
  5xx / network errors bubble to boundaries and are retried; 4xx
  (auth, validation, not-found) stay in query error state so the
  component can render an empty/auth placeholder.
- auth-store.ts: new `isInitialized` flag set in a finally block at
  the end of `initialize()`. Downstream guards use it to distinguish
  "still booting" from "definitely logged out".
- (dashboard)/layout.tsx: redirects to /login?next=<path> once
  initialised and unauthenticated, and renders a lightweight loading
  screen in the meantime so child queries never mount.
- (admin)/layout.tsx: same guard. Non-ADMIN logged-in users still
  bounce to /dashboard.
- notification-bell.tsx: short-circuits `fetchUnreadCount` when
  `isAuthenticated` is false.

Verified in dev: visiting /vi/dashboard unauthenticated now redirects
to /login?redirect=/dashboard with zero console errors and no
/analytics/… calls to the backend.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
Ho Ngoc Hai
2026-04-19 09:41:35 +07:00
parent d5915b8655
commit ad8577e2bd
6 changed files with 89 additions and 14 deletions

View File

@@ -21,7 +21,7 @@ import { cn } from '@/lib/utils';
export default function AdminLayout({ children }: { children: React.ReactNode }) {
const pathname = usePathname();
const router = useRouter();
const { user, logout } = useAuthStore();
const { user, isAuthenticated, isInitialized, logout } = useAuthStore();
const [sidebarOpen, setSidebarOpen] = useState(false);
const t = useTranslations();
@@ -33,12 +33,20 @@ export default function AdminLayout({ children }: { children: React.ReactNode })
];
useEffect(() => {
// Once the auth store finished its initial cookie→profile probe:
// - no session → push to /login (don't leave a spinner forever)
// - authenticated but not ADMIN → push to regular dashboard
if (!isInitialized) return;
if (!isAuthenticated) {
router.replace(`/login?next=${encodeURIComponent(pathname)}`);
return;
}
if (user && user.role !== 'ADMIN') {
router.replace('/dashboard');
}
}, [user, router]);
}, [isInitialized, isAuthenticated, user, router, pathname]);
if (!user) {
if (!isInitialized || !user) {
return (
<div className="flex min-h-screen items-center justify-center" role="status">
<div className="text-muted-foreground">{t('common.loading')}</div>

View File

@@ -22,7 +22,8 @@ import {
} from 'lucide-react';
import { usePathname } from 'next/navigation';
import { useTranslations } from 'next-intl';
import { useState } from 'react';
import { useEffect, useState } from 'react';
import { useRouter } from '@/i18n/navigation';
import { NotificationBell } from '@/components/notifications/notification-bell';
import { useTheme } from '@/components/providers/theme-provider';
import { Button } from '@/components/ui/button';
@@ -44,11 +45,34 @@ interface NavGroup {
export default function DashboardLayout({ children }: { children: React.ReactNode }) {
const pathname = usePathname();
const { user, logout } = useAuthStore();
const router = useRouter();
const { user, isAuthenticated, isInitialized, logout } = useAuthStore();
const { theme, toggleTheme } = useTheme();
const t = useTranslations();
const [sidebarOpen, setSidebarOpen] = useState(false);
// Auth guard — redirect unauthenticated users to /login once the auth store
// has finished its cookie→profile probe. Without this, protected queries
// inside the dashboard fire against the API and flood the console with
// 401 ApiErrors before the user even sees the sign-in screen.
useEffect(() => {
if (isInitialized && !isAuthenticated) {
const next = encodeURIComponent(pathname);
router.replace(`/login?next=${next}`);
}
}, [isInitialized, isAuthenticated, pathname, router]);
// While the auth store initialises, OR right after we've decided to redirect,
// render a lightweight skeleton rather than the full dashboard so no queries
// mount and fire.
if (!isInitialized || !isAuthenticated) {
return (
<div className="flex min-h-screen items-center justify-center text-sm text-muted-foreground">
{t('common.loading')}
</div>
);
}
const navGroups: NavGroup[] = [
{
label: t('dashboard.title'),
@@ -251,7 +275,7 @@ export default function DashboardLayout({ children }: { children: React.ReactNod
{user.fullName}
</span>
)}
<NotificationBell />
{user && <NotificationBell />}
<LanguageSwitcher />
<Button
variant="ghost"

View File

@@ -4,6 +4,7 @@ import { Bell } from 'lucide-react';
import { useRouter } from 'next/navigation';
import { useEffect, useRef } from 'react';
import { Button } from '@/components/ui/button';
import { useAuthStore } from '@/lib/auth-store';
import type { NotificationDto } from '@/lib/notifications-api';
import { useNotificationsStore } from '@/lib/notifications-store';
import { cn } from '@/lib/utils';
@@ -19,13 +20,16 @@ export function NotificationBell() {
markAllAsRead,
fetchUnreadCount,
} = useNotificationsStore();
const isAuthenticated = useAuthStore((s) => s.isAuthenticated);
const router = useRouter();
const dropdownRef = useRef<HTMLDivElement>(null);
// Fetch unread count on mount
// Fetch unread count only when the user is actually signed in — otherwise
// the request returns 401 and floods the dev console with ApiError.
useEffect(() => {
if (!isAuthenticated) return;
fetchUnreadCount();
}, [fetchUnreadCount]);
}, [fetchUnreadCount, isAuthenticated]);
// Close on click outside
useEffect(() => {

View File

@@ -10,6 +10,7 @@ function hasAuthCookie(): boolean {
interface AuthState {
user: UserProfile | null;
isAuthenticated: boolean;
isInitialized: boolean;
isLoading: boolean;
error: string | null;
@@ -26,6 +27,7 @@ interface AuthState {
export const useAuthStore = create<AuthState>((set, get) => ({
user: null,
isAuthenticated: false,
isInitialized: false,
isLoading: false,
error: null,
@@ -108,9 +110,14 @@ export const useAuthStore = create<AuthState>((set, get) => ({
},
initialize: async () => {
if (!hasAuthCookie()) return;
set({ isAuthenticated: true });
await get().fetchProfile();
try {
if (!hasAuthCookie()) return;
set({ isAuthenticated: true });
await get().fetchProfile();
} finally {
// Always mark as initialized so downstream guards stop showing spinners.
set({ isInitialized: true });
}
},
clearError: () => set({ error: null }),

View File

@@ -1,6 +1,38 @@
'use client';
import { QueryClient } from '@tanstack/react-query';
import { ApiError } from './api-client';
/**
* 401/403 errors are expected (logged-out users hit protected endpoints during
* initial render or token expiry) and should stay in the query's error state —
* components can show a "please sign in" placeholder. Do NOT propagate them to
* the error boundary, which would unmount the whole dashboard and spam the
* console.
*
* 404 means the backend simply has no data for the query — also non-fatal, let
* the component render an empty state.
*
* Anything else (network errors, 5xx, validation) is a real problem and should
* bubble up to the error boundary.
*/
function shouldBubbleToBoundary(error: unknown): boolean {
if (error instanceof ApiError) {
return error.status !== 401 && error.status !== 403 && error.status !== 404;
}
return true;
}
/**
* Retry only when it's likely transient (network / 5xx). Don't retry 4xx auth
* or validation failures — they won't fix themselves.
*/
function shouldRetry(failureCount: number, error: unknown): boolean {
if (error instanceof ApiError) {
if (error.status >= 400 && error.status < 500) return false;
}
return failureCount < 3;
}
function makeQueryClient() {
return new QueryClient({
@@ -8,10 +40,10 @@ function makeQueryClient() {
queries: {
staleTime: 60 * 1000,
gcTime: 5 * 60 * 1000,
retry: 3,
retry: shouldRetry,
retryDelay: (attemptIndex) => Math.min(1000 * 2 ** attemptIndex, 30000),
refetchOnWindowFocus: false,
throwOnError: true,
throwOnError: shouldBubbleToBoundary,
},
mutations: {
retry: 1,

File diff suppressed because one or more lines are too long