Spaces:
Running
Running
| 'use client'; | |
| import { useAuth } from '@/contexts/AuthContext'; | |
| import { useRouter } from 'next/navigation'; | |
| import { useCallback } from 'react'; | |
| /** | |
| * Custom hook that wraps fetch with automatic authentication handling | |
| * | |
| * Features: | |
| * - Automatically adds Authorization header to all requests | |
| * - Detects 401 Unauthorized responses | |
| * - Automatically logs out and redirects to /login on 401 | |
| * - Returns standard fetch API for drop-in replacement | |
| * | |
| * @example | |
| * const authFetch = useAuthFetch(); | |
| * const response = await authFetch('/api/conversations'); | |
| */ | |
| export function useAuthFetch() { | |
| const { getAuthHeader, logout } = useAuth(); | |
| const router = useRouter(); | |
| const authFetch = useCallback( | |
| async (input: RequestInfo | URL, init?: RequestInit): Promise<Response> => { | |
| // Prepare headers with authentication | |
| const headers = new Headers(init?.headers || {}); | |
| // Add Authorization header if not already present | |
| if (!headers.has('Authorization')) { | |
| const authHeader = getAuthHeader(); | |
| if (authHeader) { | |
| headers.set('Authorization', authHeader); | |
| } | |
| } | |
| // Make the fetch request with auth headers | |
| const response = await fetch(input, { | |
| ...init, | |
| headers, | |
| }); | |
| // Handle 401 Unauthorized - automatic logout and redirect | |
| if (response.status === 401) { | |
| console.log('[useAuthFetch] 401 Unauthorized detected - logging out and redirecting to login'); | |
| await logout(); | |
| // Use window.location.replace for immediate, forced navigation | |
| if (typeof window !== 'undefined') { | |
| window.location.replace('/login'); | |
| } | |
| // Return a rejected promise to stop further execution | |
| return Promise.reject(new Error('Unauthorized - redirecting to login')); | |
| } | |
| return response; | |
| }, | |
| [getAuthHeader, logout, router] | |
| ); | |
| return authFetch; | |
| } | |