-
Notifications
You must be signed in to change notification settings - Fork 403
Fix: Resolved Signup and Login failure by updating CORS, API Port and Auth Config #2690
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Fix: Resolved Signup and Login failure by updating CORS, API Port and Auth Config #2690
Conversation
|
@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. |
WalkthroughConfiguration 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
Estimated code review effort🎯 2 (Simple) | ⏱️ ~12 minutes
Possibly related PRs
Suggested labels
Suggested reviewers
Poem
Pre-merge checks and finishing touches✅ Passed checks (5 passed)
✨ Finishing touches
🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this 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 sameVITE_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 singleconst 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 (/apireuse and/vpipath).Mounting
routesat both/and/apiplususerRoutesat/vpiis 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:
/vpiis the intended prefix foruserRoutes(and not a typo for/api), and- duplicating
routeson both/and/apidoesn’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
⛔ Files ignored due to path filters (1)
package-lock.jsonis 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 withorigin: true+credentials: trueis 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"], }) );
| # 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 |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
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)
| // --- 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 | ||
| } | ||
| }) | ||
| ); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🧩 Analysis chain
🏁 Script executed:
# First, let's examine the backend/app.js file around the specified lines
head -50 backend/app.js | tail -30Repository: 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 jsRepository: 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 2Repository: codervivek5/VigyBag
Length of output: 182
🏁 Script executed:
# Check for .env.example or similar configuration documentation
fd "\\.env" . | head -20Repository: codervivek5/VigyBag
Length of output: 182
🏁 Script executed:
# Search for session configuration patterns across the codebase
rg "session\\(" backend/ --type js -B 3 -A 8Repository: 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)
- 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]
- Configure secure cookie and session options: secure=true (HTTPS), httpOnly, SameSite, reasonable maxAge, saveUninitialized=false, resave=false. [1][3]
- Limit session size and avoid storing secrets in sessions; store minimal data or reference IDs. [1]
- Use TTLs and automatic cleanup in the store; use persistent/replicated store for HA. [3][4]
- Monitor store metrics (memory, connection count, latency) and set alerts. [3]
- 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.
-
Use a persistent store (not MemoryStore). Configure connect-mongo (MongoStore.create / new MongoStore). [1][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]
-
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]
-
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]
-
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]
-
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]
-
Rotate and protect secrets:
- Keep the session secret in env vars/secret manager and rotate periodically. Use strong secrets and limit access.
-
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]
-
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]
-
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.
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
|
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! 🔗💡 |
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:
localhost:3000, which caused failures locally (where the backend runs on5000) and would fail in production environments.Changes Made:
UserAuth.jsx: Replaced the hardcoded URL withimport.meta.env.VITE_API_URL. This ensures the app connects dynamically in both local (localhost:5000) and deployed environments.backend/app.js: Configured CORS (origin: true) to allow frontend communication from any origin..env.example: Added missing authentication secret templates to help new contributors setup their environment.Testing:
Fixes #2689
Before:

After:



Summary by CodeRabbit
Release Notes
✏️ Tip: You can customize this high-level summary in your review settings.