File size: 1,926 Bytes
ec1372e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
'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;
}