Skip to content

Fix authentication#573

Merged
mehul-m-prajapati merged 4 commits into
GitMetricsLab:mainfrom
SUMIQVERSE:fix-authentication
May 31, 2026
Merged

Fix authentication#573
mehul-m-prajapati merged 4 commits into
GitMetricsLab:mainfrom
SUMIQVERSE:fix-authentication

Conversation

@SUMIQVERSE
Copy link
Copy Markdown
Contributor

@SUMIQVERSE SUMIQVERSE commented May 27, 2026

Description

This PR resolves the core issues preventing the authentication flow (Login/Signup) from working in the live production environment (Netlify frontend + Node.js backend).

Previously, API requests were defaulting to the Netlify domain causing 404 Not Found errors, and the backend was blocking cross-origin requests due to a CORS typo and missing cookie configurations.

Changes Made

Frontend Updates (Signup.tsx & Login.tsx):

  1. Dynamic API Routing: Replaced hardcoded relative paths with import.meta.env.VITE_BACKEND_URL || "" to ensure requests route to the correct backend server.
  2. Cross-Origin Sessions: Added { withCredentials: true } to Axios requests so session cookies are properly sent to the backend.
  3. TypeScript Fixes: Resolved ESLint/TS any type warnings in the catch blocks by implementing explicit type-checking with axios.isAxiosError().

Backend Updates (server.js):

  1. CORS Typo Fix: Corrected the allowed origins array (https://github-spy.etlify.app -> https://github-spy.netlify.app).
  2. Proxy Trust: Added app.set('trust proxy', 1); which is necessary for setting secure cookies when the backend is deployed behind a proxy (like Render/Railway).
  3. Production Cookie Policy: Updated express-session to use secure: process.env.NODE_ENV === 'production' and sameSite: 'none' (when in production) so browsers don't block the third-party session cookies.

Important Action Required by Maintainers

For this fix to work on the live deployment, please ensure the following Environment Variables are set in your hosting platforms:

  • Netlify (Frontend): Add VITE_BACKEND_URL pointing to the live backend API URL.
  • Backend Host (Render/Railway): Ensure NODE_ENV=production is set so the secure cookie flags are activated.

Closes #561
Assigned under GSSoC 26

Summary by CodeRabbit

  • Bug Fixes

    • Fixed backend URL fallback for API requests when environment variables are missing
    • Improved signup form error messaging with better error detection
    • Updated CORS domain for production deployment
  • Chores

    • Strengthened password validation requirements (mixed case, digits, special characters, minimum 8 characters)
    • Enhanced session cookie security (HTTPS enforcement in production, improved cookie policies)
    • Configured proxy trust settings for deployment environments

Review Change Stack

@netlify
Copy link
Copy Markdown

netlify Bot commented May 27, 2026

Deploy Preview for github-spy failed.

Name Link
🔨 Latest commit ae2fceb
🔍 Latest deploy log https://app.netlify.com/projects/github-spy/deploys/6a1c0c687ab5630008b72faf

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented May 27, 2026

Warning

Review limit reached

@mehul-m-prajapati, we couldn't start this review because you've reached your PR review rate limit.

More reviews will be available in 48 minutes and 27 seconds. Learn how PR review limits work.

Your organization has run out of usage credits. Purchase more in the billing tab.

⌛ How to resolve this issue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans include higher PR review limits than trial, open-source, and free plans. In all cases, reviews become available again over time. During sustained high-volume PR review activity, CodeRabbit may temporarily slow when the next review becomes available.

Please see our Fair Usage Limits Policy for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: c79d5099-ae81-4815-b694-7f0f3de3b212

📥 Commits

Reviewing files that changed from the base of the PR and between f5145e0 and ae2fceb.

📒 Files selected for processing (4)
  • backend/server.js
  • backend/validators/authValidator.js
  • src/pages/Login/Login.tsx
  • src/pages/Signup/Signup.tsx
📝 Walkthrough

Walkthrough

This PR fixes authentication API requests returning 404 errors on Netlify production (#561) by enabling Express trust proxy, updating CORS to the Netlify domain, configuring secure session cookies, adding backend URL fallbacks in frontend components, and strengthening password validation with type-aware error handling.

Changes

Netlify Production Authentication Flow

Layer / File(s) Summary
Backend Server Configuration for Netlify Production
backend/server.js
Enables trust proxy to respect X-Forwarded-For headers, updates CORS allowedOrigins from github-spy.etlify.app to github-spy.netlify.app, and adds explicit session cookie configuration with secure (HTTPS only in production), sameSite ('none' in production, 'lax' otherwise), and 24-hour maxAge.
Frontend Backend URL Resolution
src/pages/Login/Login.tsx, src/pages/Signup/Signup.tsx
Both login and signup pages update backendUrl initialization to fall back to an empty string when VITE_BACKEND_URL is undefined, ensuring API request URLs like ${backendUrl}/api/auth/login form valid relative paths when the environment variable is not set.
Authentication Validation and Error Handling
backend/validators/authValidator.js, src/pages/Signup/Signup.tsx
Signup password validation regex is replaced with a stricter lookahead pattern requiring at least one lowercase letter, one uppercase letter, one digit, and one special character. Signup error handling in handleSubmit uses axios.isAxiosError to extract server error messages for Axios errors and applies a generic fallback for non-Axios exceptions.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

Possibly related PRs

Suggested labels

type:bug

Poem

🐰 A Netlify home, CORS now blessed,
Trust proxy flows, cookies dressed,
URLs fallback, soft and light,
Auth validation holds on tight,
From etlify dreams to netlify flight!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 inconclusive)

Check name Status Explanation Resolution
Title check ❓ Inconclusive The title 'Fix authentication' is vague and generic, using non-descriptive terminology that doesn't convey specific information about the production deployment authentication issues being resolved. Make the title more specific to the main changes, such as 'Fix authentication API routing and CORS configuration for production deployment' or 'Enable authentication flow in production with dynamic backend URL routing'.
✅ Passed checks (4 passed)
Check name Status Explanation
Description check ✅ Passed The PR description is comprehensive, well-structured, and covers all required template sections including related issue reference, detailed description of changes, testing considerations, and change type classification.
Linked Issues check ✅ Passed All code changes directly address the root cause identified in issue #561: dynamic backend URL routing via environment variables on frontend, CORS origin correction on backend, and proper cross-origin cookie handling for production authentication.
Out of Scope Changes check ✅ Passed All changes are directly scoped to resolving the production authentication failures: frontend API routing, backend CORS/cookie configuration, and password validation improvements are all required for the authentication fix.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented May 27, 2026

Your plan includes 1 PR review per hour. Reviews are available now.

@SUMIQVERSE
Copy link
Copy Markdown
Contributor Author

@coderabbitai review

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented May 27, 2026

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

Copy link
Copy Markdown
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: 1

Caution

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

⚠️ Outside diff range comments (2)
src/pages/Login/Login.tsx (1)

33-33: ⚠️ Potential issue | 🔴 Critical | ⚡ Quick win

Missing withCredentials: true for cross-origin cookie support.

The PR objective states that { withCredentials: true } should be included on Axios requests to send session cookies. Without this option, the browser won't attach cookies on cross-origin requests, breaking authentication in production where frontend and backend are on different domains.

🐛 Proposed fix
-      const response = await axios.post(`${backendUrl}/api/auth/login`, formData);
+      const response = await axios.post(`${backendUrl}/api/auth/login`, formData, { withCredentials: true });
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/pages/Login/Login.tsx` at line 33, The axios POST call in the Login
component is missing the withCredentials flag so cookies won't be sent
cross-origin; update the axios.post call in the Login.tsx submit/login handler
(the line creating "response = await axios.post(`${backendUrl}/api/auth/login`,
formData)") to include the config object { withCredentials: true } as the third
argument so session cookies are attached to the request; ensure the change is
made in the function that performs the login request within the Login component.
src/pages/Signup/Signup.tsx (1)

86-88: ⚠️ Potential issue | 🔴 Critical | ⚡ Quick win

Missing withCredentials: true despite comment indicating cookie intent.

The comment states "Include cookies for session" but the actual withCredentials: true option is absent. This must be added for cross-origin cookie handling to work in production.

🐛 Proposed fix
       const response = await axios.post(`${backendUrl}/api/auth/signup`,
-        formData // Include cookies for session
+        formData,
+        { withCredentials: true }
       );
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/pages/Signup/Signup.tsx` around lines 86 - 88, The axios.post call that
creates `response` in Signup.tsx claims to "Include cookies for session" but
doesn't set withCredentials; update the `axios.post` call that posts to
`${backendUrl}/api/auth/signup` to pass the config object `{ withCredentials:
true }` (e.g., axios.post(url, formData, { withCredentials: true })) so browsers
will send/receive cross-site cookies for the session; keep the existing
`formData` argument and ensure no other axios defaults are overriding
credentials.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@backend/validators/authValidator.js`:
- Around line 20-23: Update the frontend password validation in
src/pages/Signup/Signup.tsx to match the backend rule used in
backend/validators/authValidator.js: replace the current regex
/^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d@$!%*#?&]{8,}$/ with the backend regex
/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[\W_]).{8,}$/ (update both occurrences
around lines 56 and 77) and ensure the frontend error message mirrors the
backend message ("Password must contain uppercase, lowercase, number, and
special character") so client-side validation matches server-side behavior.

---

Outside diff comments:
In `@src/pages/Login/Login.tsx`:
- Line 33: The axios POST call in the Login component is missing the
withCredentials flag so cookies won't be sent cross-origin; update the
axios.post call in the Login.tsx submit/login handler (the line creating
"response = await axios.post(`${backendUrl}/api/auth/login`, formData)") to
include the config object { withCredentials: true } as the third argument so
session cookies are attached to the request; ensure the change is made in the
function that performs the login request within the Login component.

In `@src/pages/Signup/Signup.tsx`:
- Around line 86-88: The axios.post call that creates `response` in Signup.tsx
claims to "Include cookies for session" but doesn't set withCredentials; update
the `axios.post` call that posts to `${backendUrl}/api/auth/signup` to pass the
config object `{ withCredentials: true }` (e.g., axios.post(url, formData, {
withCredentials: true })) so browsers will send/receive cross-site cookies for
the session; keep the existing `formData` argument and ensure no other axios
defaults are overriding credentials.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: d5d66548-6c79-4559-b97e-ff4ed58c4af4

📥 Commits

Reviewing files that changed from the base of the PR and between 4ae0ef6 and f5145e0.

📒 Files selected for processing (4)
  • backend/server.js
  • backend/validators/authValidator.js
  • src/pages/Login/Login.tsx
  • src/pages/Signup/Signup.tsx

Comment thread backend/validators/authValidator.js
@SUMIQVERSE
Copy link
Copy Markdown
Contributor Author

@coderabbitai resolve

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented May 27, 2026

✅ Actions performed

Comments resolved. Approval is disabled; enable reviews.request_changes_workflow to allow explicit top-level @coderabbitai resolve or @coderabbitai approve commands.

@mehul-m-prajapati mehul-m-prajapati merged commit c6399ff into GitMetricsLab:main May 31, 2026
2 of 6 checks passed
@github-actions
Copy link
Copy Markdown

🎉🎉 Thank you for your contribution! Your PR #573 has been merged! 🎉🎉

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 Report: Authentication API requests returning 404 Not Found on Netlify production

2 participants