arkitel / frontend /src /lib /auth.ts
CBV01
fix: landing page redirect, Spintax variation preview with paragraphs, compact single-screen onboarding, header dropdowns unclipped, admin broadcasts ticker, and 2-row admin tabs
3ab7243
Raw History Blame Contribute Delete
2.22 kB
export const setToken = (token: string) => {
if (typeof window !== 'undefined') {
localStorage.setItem('tg_auth_token', token);
}
};
export const getToken = () => {
if (typeof window !== 'undefined') {
return localStorage.getItem('tg_auth_token');
}
return null;
};
export const removeToken = () => {
if (typeof window !== 'undefined') {
localStorage.removeItem('tg_auth_token');
}
};
export const getAuthHeaders = (): Record<string, string> => {
const token = getToken();
return token ? { Authorization: `Bearer ${token}` } : {};
};
export const getApiBase = (): string => {
const envBase = (process.env.NEXT_PUBLIC_API_URL || '').replace(/\/$/, '');
if (envBase) return envBase;
return 'https://arkitel.onrender.com';
};
export const apiFetch = async (endpoint: string, options: any = {}) => {
const apiBase = getApiBase();
const isAbsolute = /^https?:\/\//i.test(endpoint);
// On production/when apiBase is set, we want ALL /api calls to go to the backend
const url = isAbsolute ? endpoint : (apiBase ? `${apiBase}${endpoint}` : endpoint);
const method = (options.method || 'GET').toUpperCase();
const defaultHeaders: Record<string, string> = {
...getAuthHeaders(),
};
if (method !== 'GET' && options.body && !('Content-Type' in (options.headers || {}))) {
if (typeof FormData === 'undefined' || !(options.body instanceof FormData)) {
defaultHeaders['Content-Type'] = 'application/json';
}
}
const headers = { ...defaultHeaders, ...(options.headers || {}) };
const response = await fetch(url, { ...options, method, headers });
if (response.status === 401) {
removeToken();
if (typeof window !== 'undefined') {
const path = window.location.pathname;
const isPublicRoute = path === '/' || path === '/get-started' || path === '/login' || path === '/register' || path === '/admin/login';
if (!isPublicRoute) {
const isAdminPath = path.startsWith('/admin');
window.location.href = isAdminPath ? '/admin/login' : '/login';
}
}
}
return response;
};