Skip to content

Conversation

Copy link

Copilot AI commented Nov 24, 2025

Frontend requests from localhost:5174 were blocked by CORS policy, and server crashed on missing Firebase credentials.

Changes

CORS Configuration

  • Added dynamic origin validation with fallback to http://localhost:5174 for development
  • Allow requests with no origin (Postman, curl)
  • Log blocked origins with expected value for debugging

Firebase Initialization

  • Validate credentials before initialization to prevent crashes
  • Server starts successfully with placeholder values, logs warnings
  • Enables development on non-auth features without full Firebase setup

MongoDB Connection

  • Enhanced error messages with actionable guidance

Environment Configuration

  • Created .env.example templates documenting all required variables
  • Default .env files with placeholder values (gitignored)

Before:

// server.js - crashed if DEVELOPMENT_CLIENT_URL undefined
if (process.env.ENVIRONMENT === "Development") {
  app.use(cors({
    origin: process.env.DEVELOPMENT_CLIENT_URL  // undefined
  }))
}

// firebaseAdmin.js - crashed on invalid credentials
admin.initializeApp({
    credential: admin.credential.cert({
        projectId: process.env.FIREBASE_PROJECT_ID,
        // ...
    })
});

After:

// server.js - defaults to localhost:5174, detailed logging
const corsOptions = {
  origin: function (origin, callback) {
    const allowedOrigin = process.env.ENVIRONMENT === "Production"
      ? process.env.PRODUCTION_CLIENT_URL
      : process.env.DEVELOPMENT_CLIENT_URL || "http://localhost:5174";
    
    if (!origin || origin === allowedOrigin) {
      callback(null, true);
    } else {
      console.warn(`⚠️  CORS: Blocked ${origin}, expected ${allowedOrigin}`);
      callback(new Error('Not allowed by CORS'));
    }
  }
};

// firebaseAdmin.js - validates before initializing
if (isFirebaseConfigured) {
    try {
        admin.initializeApp({ /* ... */ });
        console.log('✅ Firebase Admin SDK initialized');
    } catch (error) {
        console.error('❌ Failed:', error.message);
    }
} else {
    console.warn('⚠️  Firebase not initialized - see SETUP.md');
}

Documentation

  • QUICK-START.md for 5-minute setup
  • SETUP.md with troubleshooting guide
  • test-cors.sh for validation

Users must still configure their own Firebase and MongoDB credentials in .env files.

Original prompt

:5174/:1 Access to XMLHttpRequest at 'http://localhost:3000/api/users/verify' from origin 'http://localhost:5174' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
useUser.js:13 AxiosError
:3000/api/users/verify:1 Failed to load resource: net::ERR_FAILED
StartProject:1 Access to XMLHttpRequest at 'http://localhost:3000/api/users/verify' from origin 'http://localhost:5174' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
useUser.js:13 AxiosError
:3000/api/users/verify:1 Failed to load resource: net::ERR_FAILED
identitytoolkit.googleapis.com/v1/projects?key=AIzaSyBKGx9x8YZ3QY7cZvK9mF5qJ0oYpxJ8xYo:1 Failed to load resource: the server responded with a status of 400 ()
installHook.js:1 Google Sign-in or verification failed: FirebaseError: Firebase: Error (auth/api-key-not-valid.-please-pass-a-valid-api-key.).
at createErrorInternal (firebase_auth.js?v=bd967ac9:698:37)
at _fail (firebase_auth.js?v=bd967ac9:660:9)
at _performFetchWithErrorHandling (firebase_auth.js?v=bd967ac9:1140:9)
at async _validateOrigin (firebase_auth.js?v=bd967ac9:7351:33)
overrideMethod @ installHook.js:1
www.googleapis.com/identitytoolkit/v3/relyingparty/getProjectConfig?key=AIzaSyBKGx9x8YZ3QY7cZvK9mF5qJ0oYpxJ8xYo&cb=1764001400089:1 Failed to load resource: the server responded with a status of 400 ()
iframe.js:311 {"error":{"code":400,"message":"API key not valid. Please pass a valid API key.","errors":[{"message":"API key not valid. Please pass a valid API key.","domain":"global","reason":"badRequest"}],"status":"INVALID_ARGUMENT","details":[{"@type":"type.googleapis.com/google.rpc.ErrorInfo","reason":"API_KEY_INVALID","domain":"googleapis.com","metadata":{"service":"identitytoolkit.googleapis.com"}},{"@type":"type.googleapis.com/google.rpc.LocalizedMessage","locale":"en-US","message":"API key not valid. Please pass a valid API key."}]}}
kl @ iframe.js:311
installHook.js:1 Login failed: FirebaseError: Firebase: Error (auth/api-key-not-valid.-please-pass-a-valid-api-key.).
at createErrorInternal (firebase_auth.js?v=bd967ac9:698:37)
at _fail (firebase_auth.js?v=bd967ac9:660:9)
at _performFetchWithErrorHandling (firebase_auth.js?v=bd967ac9:1140:9)
at async _validateOrigin (firebase_auth.js?v=bd967ac9:7351:33)
overrideMethod @ installHook.js:1
handleLogin @ AffiliateSignup.jsx:69
await in handleLogin
callCallback2 @ chunk-SXRIVT2P.js?v=bd967ac9:3680
invokeGuardedCallbackDev @ chunk-SXRIVT2P.js?v=bd967ac9:3705
invokeGuardedCallback @ chunk-SXRIVT2P.js?v=bd967ac9:3739
invokeGuardedCallbackAndCatchFirstError @ chunk-SXRIVT2P.js?v=bd967ac9:3742
executeDispatch @ chunk-SXRIVT2P.js?v=bd967ac9:7046
processDispatchQueueItemsInOrder @ chunk-SXRIVT2P.js?v=bd967ac9:7066
processDispatchQueue @ chunk-SXRIVT2P.js?v=bd967ac9:7075
dispatchEventsForPlugins @ chunk-SXRIVT2P.js?v=bd967ac9:7083
(anonymous) @ chunk-SXRIVT2P.js?v=bd967ac9:7206
batchedUpdates$1 @ chunk-SXRIVT2P.js?v=bd967ac9:18966
batchedUpdates @ chunk-SXRIVT2P.js?v=bd967ac9:3585
dispatchEventForPluginEventSystem @ chunk-SXRIVT2P.js?v=bd967ac9:7205
dispatchEventWithEnableCapturePhaseSelectiveHydrationWithoutDiscreteEventReplay @ chunk-SXRIVT2P.js?v=bd967ac9:5484
dispatchEvent @ chunk-SXRIVT2P.js?v=bd967ac9:5478
dispatchDiscreteEvent @ chunk-SXRIVT2P.js?v=bd967ac9:5455

[Chronological Review: The conversation began with the user requesting to pull the most recent branch of the repository. The user then asked to get the application running for testing. Following that, the user requested an update to the environment file with specific configuration details. The user subsequently requested to restart the application. The conversation then shifted to error messages related to CORS policy and Firebase API key issues, indicating problems encountered while trying to access the application.]

[Intent Mapping:

  1. "I want to pull the most recent branch" - User wants to ensure they are working with the latest code.
  2. "get this running for me to test" - User wants to run the application for testing purposes.
  3. "update my env file" - User wants to modify the environment configuration for the application.
  4. "start it again" - User wants to restart the application after making changes.
  5. "Access to XMLHttpRequest... has been blocked by CORS policy" - User is reporting an error encountered while testing the application, indicating a need for troubleshooting.]

[Technical Inventory:

  • Repository: Feelize-website
  • Current branch: backend-changes
  • Technologies mentioned: MongoDB, Firebase, Axios for HTTP requests, CORS policy issues.]

[Code Archaeology:

  • Environment file updates were discussed, including variables for PORT, MONGO_DB_CONNECTION_STRING, FIREBASE_PROJECT_ID, and others.
  • Error messages indicate issues with API calls to Firebase and CORS configuration.]

[Progress Assessment:

  • Co...

Created from VS Code via the GitHub Pull Request extension.


💬 We'd love your input! Share your thoughts on Copilot coding agent in our 2 minute survey.

Copilot AI and others added 6 commits November 24, 2025 16:29
Co-authored-by: TAPUZE <203028494+TAPUZE@users.noreply.github.com>
Co-authored-by: TAPUZE <203028494+TAPUZE@users.noreply.github.com>
Co-authored-by: TAPUZE <203028494+TAPUZE@users.noreply.github.com>
Co-authored-by: TAPUZE <203028494+TAPUZE@users.noreply.github.com>
Co-authored-by: TAPUZE <203028494+TAPUZE@users.noreply.github.com>
Co-authored-by: TAPUZE <203028494+TAPUZE@users.noreply.github.com>
Copilot AI changed the title [WIP] Fix CORS issue for API verification endpoint Fix CORS blocking and add graceful Firebase initialization Nov 24, 2025
Copilot AI requested a review from TAPUZE November 24, 2025 16:44
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants