Skip to content

Conversation

@mohanteja781112
Copy link
Contributor

@mohanteja781112 mohanteja781112 commented Dec 6, 2025

Description:
I encountered a "Signup and Login Failed" error while setting up the project locally. Upon investigation, I identified two root causes preventing contributors and users from running the project:

  1. CORS Policy: The backend was configured to block requests from the frontend port.
  2. Frontend Connection: The client was hardcoded to localhost:3000, which caused failures locally (where the backend runs on 5000) and would fail in production environments.

Changes Made:

  • Updated UserAuth.jsx: Replaced the hardcoded URL with import.meta.env.VITE_API_URL. This ensures the app connects dynamically in both local (localhost:5000) and deployed environments.
  • Updated backend/app.js: Configured CORS (origin: true) to allow frontend communication from any origin.
  • Updated .env.example: Added missing authentication secret templates to help new contributors setup their environment.

Testing:

  • Verified that new users can now sign up and log in successfully.
  • Verified that the API URL correctly falls back to localhost when no environment variable is set.

Fixes #2689

Before:
Screenshot 2025-12-06 001206

After:
Screenshot 2025-12-06 003853
Screenshot 2025-12-06 101710
Screenshot 2025-12-06 102024

Summary by CodeRabbit

Release Notes

  • Chores
    • Updated server configuration to run on port 5000.
    • Enhanced authentication and session configuration settings.
    • Implemented environment-based API endpoint configuration for improved deployment flexibility.

✏️ Tip: You can customize this high-level summary in your review settings.

@vercel
Copy link

vercel bot commented Dec 6, 2025

@mohanteja781112 is attempting to deploy a commit to the Vivek Prajapati's projects Team on Vercel.

A member of the Team first needs to authorize it.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Dec 6, 2025

Walkthrough

Configuration and middleware updates to resolve local development setup issues—port alignment (3000→5000), universal CORS with credentials support, memory-based sessions, and environment-driven API endpoints for frontend communication.

Changes

Cohort / File(s) Summary
Environment Configuration
backend/.env.example
Updated server port from 3000 to 5000; replaced local MONGO_URI with remote connection string; added JWT and authentication secrets (token expiry, SALT_ROUNDS); updated Google OAuth callback URL to http://localhost:5000/auth/google/callback.
Backend Middleware & Sessions
backend/app.js
Configured universal CORS with credentials support (origin: true, credentials: true); replaced MongoStore session store with memory-based configuration; updated session secret default value.
Frontend API Integration
src/User/pages/UserAuth/UserAuth.jsx
Replaced hardcoded localhost:3000 API base URL with environment-driven resolution using VITE_API_URL, defaulting to http://localhost:5000 for login and signup requests.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

  • Verify CORS configuration correctly enables credentials and matches frontend port expectations
  • Confirm environment variable fallback in UserAuth.jsx resolves to correct backend endpoint
  • Validate .env.example defaults align with app.js middleware configuration (port, session secret)

Possibly related PRs

Suggested labels

BackEnd, good first issue

Suggested reviewers

  • codervivek5

Poem

🐰 A port and a CORS, a secret or two,
The frontend now knows where the backend grew,
Five-thousand's the number, credentials ring true,
No more signup sadness—the local way's new! 🎉

Pre-merge checks and finishing touches

✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title directly and clearly summarizes the main fixes: signup/login failures resolved through CORS, API port, and auth config updates.
Description check ✅ Passed The description includes all required sections: issue reference (Fixes #2689), changes proposed, testing verification, and before/after screenshots demonstrating the fix.
Linked Issues check ✅ Passed The PR satisfies all primary coding objectives from issue #2689: CORS configuration updated for credentials [#2689], API URL made configurable [#2689], and .env.example updated with auth templates [#2689].
Out of Scope Changes check ✅ Passed All changes directly address the linked issue objectives: CORS middleware, session configuration, API URL resolution, and .env templates align with signup/login failure resolution scope.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/User/pages/UserAuth/UserAuth.jsx (1)

168-172: Google login still hardcodes port 3000 instead of using the new API base URL.

The Google flow is redirecting to http://localhost:3000/auth/google, which will no longer match the backend now running on port 5000 and also breaks the env-driven URL objective. Please update this to reuse the same VITE_API_URL + localhost fallback you introduced for login/signup so Google login works in both local and deployed environments.

Example:

-    } else if (provider === "google") {
-      const apiUrl =
-        "http://localhost:3000";
-      // Google ke liye backend par redirect karein
-      window.location.href = `${apiUrl}/auth/google`;
-    }
+    } else if (provider === "google") {
+      const apiUrl = import.meta.env.VITE_API_URL || "http://localhost:5000";
+      window.location.href = `${apiUrl}/auth/google`;
+    }
🧹 Nitpick comments (2)
src/User/pages/UserAuth/UserAuth.jsx (1)

88-90: Env-driven API base URL looks good; consider centralizing it.

Using import.meta.env.VITE_API_URL || "http://localhost:5000" for both login and signup is the right direction for local + deployed setups. Since the same logic is used in multiple handlers (and may be needed elsewhere), consider hoisting it into a single const API_URL = ... near the top of the module or inside the component so all auth flows (including social) share one source of truth.

Also applies to: 119-121

backend/app.js (1)

54-60: Double-check route prefixes (/api reuse and /vpi path).

Mounting routes at both / and /api plus userRoutes at /vpi is a bit surprising; it may be intentional, but it’s easy for paths to drift from what the frontend expects (especially now that base URLs are being standardized). Please verify that:

  • /vpi is the intended prefix for userRoutes (and not a typo for /api), and
  • duplicating routes on both / and /api doesn’t create confusing or duplicate endpoints.

If everything is intentional, consider adding a short comment explaining the routing scheme.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between de0bfbe and 4480519.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (3)
  • backend/.env.example (1 hunks)
  • backend/app.js (2 hunks)
  • src/User/pages/UserAuth/UserAuth.jsx (2 hunks)
🧰 Additional context used
🪛 dotenv-linter (4.0.0)
backend/.env.example

[warning] 3-3: [UnorderedKey] The MONGO_URI key should go before the PORT key

(UnorderedKey)


[warning] 7-7: [UnorderedKey] The ACCESS_TOKEN_SECRET key should go before the JWT_SECRET key

(UnorderedKey)


[warning] 8-8: [UnorderedKey] The ACCESS_TOKEN_EXPIRES key should go before the ACCESS_TOKEN_SECRET key

(UnorderedKey)


[warning] 10-10: [UnorderedKey] The REFRESH_TOKEN_EXPIRES key should go before the REFRESH_TOKEN_SECRET key

(UnorderedKey)


[warning] 16-16: [EndingBlankLine] No blank line at the end of the file

(EndingBlankLine)


[warning] 16-16: [UnorderedKey] The GOOGLE_CALLBACK_URL key should go before the GOOGLE_CLIENT_ID key

(UnorderedKey)

🔇 Additional comments (1)
backend/app.js (1)

24-30: Universal CORS with origin: true + credentials: true is unsafe for production.

This configuration echoes back any caller origin and allows credentialed requests from arbitrary sites, creating a CSRF/CORS vulnerability. Restrict allowed origins via an environment-driven whitelist and differentiate between development and production:

const allowedOrigins = (process.env.CORS_ORIGINS || "http://localhost:5173").split(",");

app.use(
  cors({
    origin: (origin, cb) => {
      if (!origin || allowedOrigins.includes(origin)) return cb(null, true);
      return cb(new Error("Not allowed by CORS"));
    },
    credentials: true,
    methods: ["GET", "POST", "PUT", "DELETE"],
    allowedHeaders: ["Content-Type", "Authorization"],
  })
);

Comment on lines +1 to +16
# Server Configuration
PORT=5000
MONGO_URI=mongodb+srv://<username>:<password>@cluster0.mongodb.net/vigybag

# Database
MONGO_URI=mongodb://localhost:27017/vigybag
# Authentication Secrets (Please change these to your own random strings)
JWT_SECRET=your_jwt_secret_here
ACCESS_TOKEN_SECRET=your_access_token_secret_here
ACCESS_TOKEN_EXPIRES=1d
REFRESH_TOKEN_SECRET=your_refresh_token_secret_here
REFRESH_TOKEN_EXPIRES=7d
SALT_ROUNDS=10

# Auth / Security
JWT_SECRET=change_me
SESSION_SECRET=change_me_session

# Google OAuth
GOOGLE_CLIENT_ID=
GOOGLE_CLIENT_SECRET=
# When running locally, set to http://localhost:3000/auth/google/callback
GOOGLE_CALLBACK_URL=

# Email (OTP, password reset)
EMAIL=
EMAIL_PASSWORD=

# ContactRoute (if used separately)
EMAIL_USER=
EMAIL_PASS=
EMAIL_TO=
# Google/Social Login (Optional)
GOOGLE_CLIENT_ID=your_google_client_id
GOOGLE_CLIENT_SECRET=your_google_client_secret
GOOGLE_CALLBACK_URL=http://localhost:5000/auth/google/callback
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Add SESSION_SECRET to the example env and align with session config.

backend/app.js reads process.env.SESSION_SECRET and otherwise falls back to a hardcoded value. To avoid insecure defaults and help new contributors configure things correctly, this example file should include a SESSION_SECRET=your_session_secret_here entry (and ideally mention it in any setup docs). That keeps session behavior explicit and consistent with the rest of the auth secrets you’ve added.

Separately, dotenv-linter is flagging key-order and final-newline warnings here; they’re non-functional, but you can address them easily if you want a clean lint run (e.g., reordering keys as suggested and adding a trailing newline).

🧰 Tools
🪛 dotenv-linter (4.0.0)

[warning] 3-3: [UnorderedKey] The MONGO_URI key should go before the PORT key

(UnorderedKey)


[warning] 7-7: [UnorderedKey] The ACCESS_TOKEN_SECRET key should go before the JWT_SECRET key

(UnorderedKey)


[warning] 8-8: [UnorderedKey] The ACCESS_TOKEN_EXPIRES key should go before the ACCESS_TOKEN_SECRET key

(UnorderedKey)


[warning] 10-10: [UnorderedKey] The REFRESH_TOKEN_EXPIRES key should go before the REFRESH_TOKEN_SECRET key

(UnorderedKey)


[warning] 16-16: [EndingBlankLine] No blank line at the end of the file

(EndingBlankLine)


[warning] 16-16: [UnorderedKey] The GOOGLE_CALLBACK_URL key should go before the GOOGLE_CLIENT_ID key

(UnorderedKey)

Comment on lines +35 to 45
// --- FIX: Session (Memory only, prevents MongoStore crash) ---
app.use(
session({
secret: process.env.SESSION_SECRET || "Our little secret.",
secret: process.env.SESSION_SECRET || "vigybag_secret",
resave: false,
saveUninitialized: false,
// 2. CONFIGURE THE MONGOSTORE
store: MongoStore.create({
mongoUrl: process.env.MONGO_URI,
collectionName: 'sessions' // Optional: name of the collection to store sessions
}),
cookie: {
maxAge: 1000 * 60 * 60 * 24 * 7 // Optional: 1 week
maxAge: 1000 * 60 * 60 * 24 * 7 // 1 week
}
})
);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical

🧩 Analysis chain

🏁 Script executed:

# First, let's examine the backend/app.js file around the specified lines
head -50 backend/app.js | tail -30

Repository: codervivek5/VigyBag

Length of output: 182


🏁 Script executed:

# Check if MONGO_URI or MongoStore is used elsewhere in the codebase
rg "MONGO_URI|MongoStore" --type js

Repository: codervivek5/VigyBag

Length of output: 182


🏁 Script executed:

# Look for environment variable configurations and NODE_ENV checks
rg "NODE_ENV|process.env" backend/ --type js -B 2 -A 2

Repository: codervivek5/VigyBag

Length of output: 182


🏁 Script executed:

# Check for .env.example or similar configuration documentation
fd "\\.env" . | head -20

Repository: codervivek5/VigyBag

Length of output: 182


🏁 Script executed:

# Search for session configuration patterns across the codebase
rg "session\\(" backend/ --type js -B 3 -A 8

Repository: codervivek5/VigyBag

Length of output: 182


🌐 Web query:

express-session memory store production security risks scalability

💡 Result:

Short answer
Do not use the default express-session MemoryStore in production — it leaks memory, won’t scale beyond a single process, and can cause outages/DoS and session loss on restarts. Use a production session store (Redis, Mongo, etc.) and follow session hardening best practices. [1][2][3][4]

Why MemoryStore is unsafe (concise)

  • Memory leaks / unbounded RAM growth → process OOM or degraded performance (DoS risk). [1][2]
  • Single-process only → sessions aren’t shared across instances / containers behind a load‑balancer (breaks horizontal scaling). [1][2]
  • Volatile: all sessions lost on restart/deploy → user logouts and inconsistent state. [1][3]
  • Operational complexity: GC/eviction behavior and lack of persistence make TTL/enforcement unreliable. [1][2]

Security & reliability consequences

  • Availability risk (OOM, crashes) → attackers can exploit to cause denial of service. [2]
  • Data loss and stale authentication states after restarts. [1]
  • Potential for accidental sensitive data retention in RAM if your app stores secrets in sessions (no encryption-at-rest/persistence controls). [1][3]

Recommended mitigations (practical)

  1. Replace MemoryStore with a production store:
    • Redis (connect-redis) for low latency, high throughput, built-in TTL/eviction. [3]
    • MongoDB stores (connect-mongo or connect-mongodb-session) if you already use Mongo and want persistence. [4]
  2. Configure secure cookie and session options: secure=true (HTTPS), httpOnly, SameSite, reasonable maxAge, saveUninitialized=false, resave=false. [1][3]
  3. Limit session size and avoid storing secrets in sessions; store minimal data or reference IDs. [1]
  4. Use TTLs and automatic cleanup in the store; use persistent/replicated store for HA. [3][4]
  5. Monitor store metrics (memory, connection count, latency) and set alerts. [3]
  6. If you need in-memory caching for short-lived sessions, use a maintained package (e.g., memorystore) only after understanding its limits — but prefer external stores for production. [2][7]

Quick links (sources)

  • express-session docs (MemoryStore warning and options). [1]
  • express-session GitHub / issues discussion on MemoryStore warning. [2]
  • Redis guidance for session stores / scalability. [3]
  • connect-mongo (MongoDB session store) docs. [4]

If you want, I can: (a) show example express-session config for Redis or Mongo, or (b) compare Redis vs Mongo vs cookie-based sessions for your specific deployment.


🌐 Web query:

express-session MongoStore production deployment best practices

💡 Result:

Below are concise production best practices for using express-session with MongoStore (connect-mongo), with short rationale and pointers.

  1. Use a persistent store (not MemoryStore). Configure connect-mongo (MongoStore.create / new MongoStore). [1][2]

  2. Secure cookie settings:

    • cookie.httpOnly: true, cookie.secure: true (only over HTTPS), set SameSite appropriately (lax for same-site, none for cross-site + Secure).
    • app.set('trust proxy', 1) when behind a reverse proxy/Load Balancer so secure cookies work. [1][3]
  3. Session options to reduce DB churn:

    • resave: false, saveUninitialized: false — avoid writing unchanged or empty sessions.
    • use touchAfter / lazy updates to avoid frequent writes for read-only requests. [2]
  4. Manage TTL / expiration:

    • Let connect-mongo use MongoDB TTL indexes (autoRemove: 'native') or create/manage the TTL index yourself in highly concurrent environments. Set reasonable ttl or rely on cookie expiry. [2]
  5. MongoDB connection hardening & performance:

    • Use a production MongoDB (replica set), authenticated connections, TLS, connection pooling, and proper timeouts/retries. Monitor connection/ops. Prefer a managed DB (Atlas, etc.) if you don’t run ops yourself. [2]
  6. Don’t store sensitive/large data in session:

    • Keep session payload minimal (IDs/flags). If you must store sensitive data, encrypt it before saving or use other secure storage. [2]
  7. Rotate and protect secrets:

    • Keep the session secret in env vars/secret manager and rotate periodically. Use strong secrets and limit access.
  8. Scaling / load-balancing:

    • With multiple app instances, use the shared MongoStore (no sticky sessions required). Ensure Mongo can handle session write/read QPS; consider tuning touchAfter and TTL to reduce load. [2]
  9. CORS / credential handling for web clients:

    • If frontend and API are on different origins, enable CORS with credentials and set fetch/axios to send credentials ('include' / withCredentials). Set cookie SameSite=None + Secure when cross-site. [3]
  10. Observability & cleanup:

  • Emit/handle store events (create/update/destroy/touch), monitor session collection size, indexes, and set up backups and alerting. Periodically audit session TTL index behavior. [2]

References:

  • Express-session docs (cookie, trust proxy, options). [1]
  • connect-mongo / MongoStore README (ttl, autoRemove, touchAfter, encryption notes, events). [2]
  • Practical cookie/CORS notes (SameSite, credentials, cross-origin cookies). [3]

If you want, I can produce a minimal production-ready config snippet (express + connect-mongo) tuned for your app (include NODE_ENV, example ttl, touchAfter, CORS settings).


In-memory session store and default secret are unsuitable for production.

The default memory store leaks memory, loses all sessions on server restart, and cannot scale across multiple instances—creating availability and data loss risks in production. The hardcoded fallback secret ("vigybag_secret") is insecure if SESSION_SECRET is missing.

For production: (a) replace MemoryStore with a persistent store such as MongoStore using MONGO_URI, and (b) require SESSION_SECRET to be explicitly set (do not provide a fallback in production environments).

Example configuration:

const isProd = process.env.NODE_ENV === "production";

session({
  secret: isProd ? process.env.SESSION_SECRET : (process.env.SESSION_SECRET || "dev_only_secret"),
  resave: false,
  saveUninitialized: false,
  // store: isProd ? mongoStoreInstance : undefined,
  cookie: { maxAge: 1000 * 60 * 60 * 24 * 7 }
});

If SESSION_SECRET is missing in production, throw an error at startup rather than silently using an insecure default.

🤖 Prompt for AI Agents
In backend/app.js around lines 35 to 45, the code uses the default in-memory
session store and an insecure hardcoded fallback secret; for production replace
the MemoryStore with a persistent store (e.g., connect-mongo / MongoStore)
initialized from process.env.MONGO_URI and only attach it to session when
NODE_ENV === "production", require process.env.SESSION_SECRET to be set in
production (throw an error and exit at startup if missing) while allowing a
dev-only fallback secret for non-production, and keep resave/saveUninitialized
and cookie settings as before.

@vercel
Copy link

vercel bot commented Dec 6, 2025

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Preview Comments Updated (UTC)
vigybag Ready Ready Preview Comment Dec 6, 2025 10:33am

@codervivek5 codervivek5 merged commit ca111ea into codervivek5:main Dec 6, 2025
3 of 4 checks passed
@github-actions
Copy link

github-actions bot commented Dec 6, 2025

Congratulations, Your pull request has been successfully merged 🥳🎉 Thank you for your valuable contribution to the project 🚀 Keep contributing!! ✨

📢 Don’t forget to share your VigyBag PR on LinkedIn and tag @VigyBag and me — we’d love to celebrate your achievement with you! 🔗💡

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Bug: "Signup Failed" error when trying to create an account.

2 participants