From 03b76a8e582c92ded7ddd75e4318ce6ea32d2f6c Mon Sep 17 00:00:00 2001 From: Koncept Kit <63216427+konceptkit@users.noreply.github.com> Date: Mon, 5 Jan 2026 15:42:11 +0700 Subject: [PATCH] Add defensive backend URL validation and auto-cleanup - Add getApiUrl() function to validate and clean backend URL - Automatically strip /membership or /api suffix if present - Log all environment variables on module load for debugging - Add detailed URL logging in login function - Provide fallback if REACT_APP_BACKEND_URL is undefined This fixes the intermittent CORS error caused by incorrect backend URL --- src/context/AuthContext.js | 35 +++++++++++++++++++++++++++++++++-- 1 file changed, 33 insertions(+), 2 deletions(-) diff --git a/src/context/AuthContext.js b/src/context/AuthContext.js index b029b7a..b2aa1b7 100644 --- a/src/context/AuthContext.js +++ b/src/context/AuthContext.js @@ -3,7 +3,34 @@ import axios from 'axios'; const AuthContext = createContext(); -const API_URL = process.env.REACT_APP_BACKEND_URL; +// Ensure API_URL is correctly set, with fallback and validation +const getApiUrl = () => { + const url = process.env.REACT_APP_BACKEND_URL; + + // Log the environment variable for debugging + console.log('[AuthContext] Environment check:', { + REACT_APP_BACKEND_URL: url, + REACT_APP_BASENAME: process.env.REACT_APP_BASENAME, + PUBLIC_URL: process.env.PUBLIC_URL + }); + + if (!url) { + console.error('[AuthContext] REACT_APP_BACKEND_URL is not defined!'); + // Fallback to current origin API (same domain) + return window.location.origin.replace('/membership', ''); + } + + // Remove any trailing /membership or /api from the backend URL + const cleanUrl = url.replace(/\/(membership|api)\/?$/, ''); + + if (cleanUrl !== url) { + console.warn('[AuthContext] Cleaned backend URL:', { original: url, cleaned: cleanUrl }); + } + + return cleanUrl; +}; + +const API_URL = getApiUrl(); export const AuthProvider = ({ children }) => { const [user, setUser] = useState(null); @@ -55,7 +82,11 @@ export const AuthProvider = ({ children }) => { const login = async (email, password) => { try { - console.log('[AuthContext] Starting login request...'); + console.log('[AuthContext] Starting login request...', { + API_URL: API_URL, + envBackendUrl: process.env.REACT_APP_BACKEND_URL, + fullUrl: `${API_URL}/api/auth/login` + }); const response = await axios.post( `${API_URL}/api/auth/login`,