EverydayTech Platform - Developer Reference
Complete Source Code Documentation - All Applications
Loading...
Searching...
No Matches
api.js
Go to the documentation of this file.
1// Simple global fetch wrapper: injects Authorization header (if token)
2// and redirects to login on 401/403 responses.
3const originalFetch = window.fetch.bind(window);
4
5window.fetch = async (input, init = {}) => {
6 const token = localStorage.getItem('token');
7 init.headers = init.headers || {};
8
9 // Normalize URL for checks
10 const url = typeof input === 'string' ? input : (input && input.url) ? input.url : '';
11 const isLoginRequest = url.includes('/users/login');
12
13 // If Authorization not already present, add it (but never for login requests)
14 if (!isLoginRequest && token && !init.headers.Authorization && !init.headers.authorization) {
15 init.headers = { ...init.headers, Authorization: `Bearer ${token}` };
16 }
17
18 try {
19 const res = await originalFetch(input, init);
20
21 // Don't auto-redirect on auth errors for login calls or when we're already on the login page
22 // Only redirect on 401 (unauthenticated). Do NOT redirect on 403 (forbidden) as it may be a legitimate ACL deny.
23 if ((res.status === 401) && !isLoginRequest && window.location.pathname !== '/login') {
24 try { localStorage.removeItem('token'); } catch (e) {}
25 // Send users to the login page instead of home
26 window.location.href = '/login';
27 }
28 return res;
29 } catch (err) {
30 // network error - rethrow so callers can handle
31 throw err;
32 }
33};
34
35export {};