Skip to content

Fix session cookies with proper CORS and credentialed auth requests#254

Open
ChaitanyaChute wants to merge 2 commits into
GitMetricsLab:mainfrom
ChaitanyaChute:fix/cors
Open

Fix session cookies with proper CORS and credentialed auth requests#254
ChaitanyaChute wants to merge 2 commits into
GitMetricsLab:mainfrom
ChaitanyaChute:fix/cors

Conversation

@ChaitanyaChute
Copy link
Copy Markdown
Contributor

@ChaitanyaChute ChaitanyaChute commented May 15, 2026

Related Issue


Description

  • Fix backend CORS configuration to allow credentialed requests from the frontend.
  • Ensure login/signup requests send cookies so session persists.

Type of Change

  • Bug fix
  • New feature
  • Code style update
  • Breaking change
  • Documentation update

Summary by CodeRabbit

Release Notes

  • Bug Fixes
    • Authentication now properly maintains session credentials during login and signup.
    • CORS restrictions updated to allow only explicitly configured frontend sources.
    • Improved error messaging during signup for clearer user feedback.

Review Change Stack

@netlify
Copy link
Copy Markdown

netlify Bot commented May 15, 2026

Deploy Preview for github-spy failed.

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

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented May 15, 2026

📝 Walkthrough

Walkthrough

Backend CORS configuration switches from a wildcard origin to an explicit allowlist derived from the FRONTEND_URL environment variable, with credentials: true enabled. Frontend Login and Signup requests now include { withCredentials: true } in their Axios calls to send and receive session cookies.

Changes

Session Authentication with Credentials

Layer / File(s) Summary
Backend CORS allowlist configuration
backend/server.js
CORS configuration switched from wildcard origin to an explicit allowlist parsed from FRONTEND_URL environment variable (comma-separated, trimmed), with credentials: true enabled to allow credentialed session requests.
Frontend API requests with credentials
src/pages/Login/Login.tsx, src/pages/Signup/Signup.tsx
Login and Signup form submissions now explicitly include Axios request option { withCredentials: true } to ensure session cookies are sent and received. Signup also validates the success message and navigates to login on match, with generic error handling in the catch block.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

Possibly related PRs

Poem

🐰 A cookie, a credential, a trust to be earned,
The credentials now flow where the session once turned,
With CORS allowlist and withCredentials: true,
Authentication persists the whole journey through! 🍪✨

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely summarizes the main changes: fixing session cookies by implementing proper CORS configuration and enabling credentialed auth requests.
Description check ✅ Passed The PR description covers all required template sections with relevant details: related issue (#249), clear description of changes, and appropriate bug fix classification. Testing section is empty but non-critical.
Linked Issues check ✅ Passed The code changes directly address issue #249's requirements: backend CORS configured with explicit origin allowlist and credentials enabled; frontend login/signup requests updated with withCredentials: true.
Out of Scope Changes check ✅ Passed All changes are directly related to fixing the session cookie persistence issue outlined in #249. No unrelated modifications to other features or systems were introduced.
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.

@ChaitanyaChute ChaitanyaChute changed the title Fix/cors Fix session cookies with proper CORS and credentialed auth requests May 15, 2026
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.

🧹 Nitpick comments (1)
src/pages/Signup/Signup.tsx (1)

40-56: ⚡ Quick win

Consider removing the commented-out mock implementation.

The old mock code and TODO comments are no longer needed since the real backend integration is now working. Removing dead code improves maintainability.

🧹 Proposed cleanup
-    
-    // // Simulate API call (replace with your actual backend integration)
-    // try {
-    //   // Mock successful signup
-    //   setMessage("Account created successfully! Redirecting to login...");
-      
-    //   // In your actual implementation, integrate with your backend here:
-    //   // const response = await fetch(`${backendUrl}/api/auth/signup`, {
-    //   //   method: 'POST',
-    //   //   headers: { 'Content-Type': 'application/json' },
-    //   //   body: JSON.stringify(formData)
-    //   // });
-      
-    //   setTimeout(() => {
-    //     // Navigate to login page in your actual implementation
-    //     console.log("Redirecting to login page...");
-    //   }, 2000);
-      
     } catch (error) {
       setMessage("Something went wrong. Please try again.");
     }
🤖 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 40 - 56, Remove the dead
commented-out mock signup flow in Signup.tsx: delete the block that simulates
the API call and the setTimeout/console.log redirect (the commented lines
referencing setMessage, formData, and the mock fetch), leaving only the real
backend integration in the signup handler (e.g., the actual fetch/POST logic and
subsequent setMessage/navigation). Ensure no leftover TODOs or commented code
related to the old mock remain.
🤖 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.

Nitpick comments:
In `@src/pages/Signup/Signup.tsx`:
- Around line 40-56: Remove the dead commented-out mock signup flow in
Signup.tsx: delete the block that simulates the API call and the
setTimeout/console.log redirect (the commented lines referencing setMessage,
formData, and the mock fetch), leaving only the real backend integration in the
signup handler (e.g., the actual fetch/POST logic and subsequent
setMessage/navigation). Ensure no leftover TODOs or commented code related to
the old mock remain.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: f369502f-c36b-422e-a280-f53d5dc44797

📥 Commits

Reviewing files that changed from the base of the PR and between 56e17a3 and 97c7321.

📒 Files selected for processing (6)
  • Dockerfile.prod
  • backend/routes/auth.js
  • backend/server.js
  • spec/auth.routes.spec.cjs
  • src/pages/Login/Login.tsx
  • src/pages/Signup/Signup.tsx

@mehul-m-prajapati
Copy link
Copy Markdown
Collaborator

@ChaitanyaChute : resolve conflicts

  • do i need to set FRONTEND_URI in netlify somewhere for deployment?

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: 2

Caution

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

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

72-82: ⚠️ Potential issue | 🔴 Critical | 🏗️ Heavy lift

Critical: Remove duplicate code that creates syntax errors.

Lines 72-82 contain old code that was not removed during the refactor, creating invalid JavaScript syntax:

  1. Syntax error: After the catch block at line 70-71, there's unreachable code (line 72-77) followed by another } catch statement at line 78, which is invalid.
  2. Missing finally block: The new try-catch (lines 40-71) is missing the finally block that resets isLoading. The finally block exists only in the old code (lines 80-82) that should be deleted.

The correct fix:

  • Delete lines 72-79 entirely (duplicate axios call and catch block)
  • Move the finally block (lines 80-82) to immediately follow the new catch block at line 71

This code will not compile or run in its current state.

🚨 Proposed fix to remove duplicate code and restore finally block
     } catch (error) {
       setMessage(
         (error as any).response?.data?.message || "Something went wrong. Please try again."
       );
-      const response = await axios.post(`${backendUrl}/api/auth/signup`, formData);
-      setMessage(response.data.message);
-
-      if (response.data.message === "User created successfully") {
-        navigate("/login");
-      }
-    } catch (error: any) {
-      setMessage(error.response?.data?.message || "Something went wrong. Please try again.");
     } finally {
       setIsLoading(false);
     }
🤖 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 72 - 82, Remove the duplicated
axios call and stray catch block that remained after refactor (the duplicate
axios.post(...) and its associated catch) and ensure the finally block that
calls setIsLoading(false) is moved to immediately follow the existing try/catch;
specifically, inside the Signup component remove the old duplicate code that
repeats the axios.post to `${backendUrl}/api/auth/signup` and the extra `} catch
(...)` block, then place the finally block that resets `isLoading` right after
the current catch so setIsLoading(false) always runs; keep existing uses of
setMessage(response.data.message), navigate("/login") when response.data.message
=== "User created successfully", and the error handling that reads
error.response?.data?.message.
🧹 Nitpick comments (1)
src/pages/Signup/Signup.tsx (1)

49-50: ⚡ Quick win

Consider checking response status instead of exact message text.

The current implementation checks for an exact message string match ('User created successfully'), which tightly couples the frontend to the backend's specific message wording. If the backend message changes, navigation will silently fail.

Consider using response.status === 201 or a response.data.success boolean flag for more robust success detection.

♻️ Proposed refactor using status code
-      if (response.data.message === 'User created successfully') {
-        navigate("/login");}
+      if (response.status === 201 || response.status === 200) {
+        navigate("/login");
+      }
🤖 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 49 - 50, Replace the fragile string
check in the Signup component (the if that currently tests response.data.message
=== 'User created successfully') with a status- or flag-based check: inspect
response.status === 201 or response.data.success (whichever the API guarantees)
and call navigate("/login") when that condition is true; update the signup
submission handler in Signup.tsx to use this new conditional so navigation no
longer depends on exact backend message wording.
🤖 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 `@src/pages/Signup/Signup.tsx`:
- Around line 70-71: Restore extraction of the backend-provided error message in
the Signup component's catch block: when catching the error in the signup
handler, read error.response?.data?.message (falling back to error.message or a
generic string) and pass that to setMessage instead of the hardcoded "Something
went wrong..." so users see validation/backend errors; update the catch block
around the signup submission (where setMessage is currently called) to use this
extraction logic.
- Around line 53-69: Remove the dead commented-out mock API block inside the
Signup component (the commented "Simulate API call" section) so the file no
longer contains the old mock fetch/timeout code; specifically delete the
commented lines within the Signup.tsx handleSubmit/submit flow that start with
the "Simulate API call" comment and the subsequent try/Mock successful
signup/setTimeout stubs, leaving only the real implementation and any real
messaging (e.g., setMessage) intact.

---

Outside diff comments:
In `@src/pages/Signup/Signup.tsx`:
- Around line 72-82: Remove the duplicated axios call and stray catch block that
remained after refactor (the duplicate axios.post(...) and its associated catch)
and ensure the finally block that calls setIsLoading(false) is moved to
immediately follow the existing try/catch; specifically, inside the Signup
component remove the old duplicate code that repeats the axios.post to
`${backendUrl}/api/auth/signup` and the extra `} catch (...)` block, then place
the finally block that resets `isLoading` right after the current catch so
setIsLoading(false) always runs; keep existing uses of
setMessage(response.data.message), navigate("/login") when response.data.message
=== "User created successfully", and the error handling that reads
error.response?.data?.message.

---

Nitpick comments:
In `@src/pages/Signup/Signup.tsx`:
- Around line 49-50: Replace the fragile string check in the Signup component
(the if that currently tests response.data.message === 'User created
successfully') with a status- or flag-based check: inspect response.status ===
201 or response.data.success (whichever the API guarantees) and call
navigate("/login") when that condition is true; update the signup submission
handler in Signup.tsx to use this new conditional so navigation no longer
depends on exact backend message wording.
🪄 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: ef36cfe8-2f78-4b5e-a019-1cdd11a774e0

📥 Commits

Reviewing files that changed from the base of the PR and between 97c7321 and 8e89435.

📒 Files selected for processing (1)
  • src/pages/Signup/Signup.tsx

Comment on lines +53 to +69
// // Simulate API call (replace with your actual backend integration)
// try {
// // Mock successful signup
// setMessage("Account created successfully! Redirecting to login...");

// // In your actual implementation, integrate with your backend here:
// // const response = await fetch(`${backendUrl}/api/auth/signup`, {
// // method: 'POST',
// // headers: { 'Content-Type': 'application/json' },
// // body: JSON.stringify(formData)
// // });

// setTimeout(() => {
// // Navigate to login page in your actual implementation
// console.log("Redirecting to login page...");
// }, 2000);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion | 🟠 Major | ⚡ Quick win

Remove commented-out mock code.

The commented mock API implementation should be deleted entirely. Leaving dead code as comments clutters the codebase and provides no value since the actual implementation is now in place.

🧹 Proposed cleanup
-    
-    // // Simulate API call (replace with your actual backend integration)
-    // try {
-    //   // Mock successful signup
-    //   setMessage("Account created successfully! Redirecting to login...");
-      
-    //   // In your actual implementation, integrate with your backend here:
-    //   // const response = await fetch(`${backendUrl}/api/auth/signup`, {
-    //   //   method: 'POST',
-    //   //   headers: { 'Content-Type': 'application/json' },
-    //   //   body: JSON.stringify(formData)
-    //   // });
-      
-    //   setTimeout(() => {
-    //     // Navigate to login page in your actual implementation
-    //     console.log("Redirecting to login page...");
-    //   }, 2000);
-      
     } catch (error) {
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// // Simulate API call (replace with your actual backend integration)
// try {
// // Mock successful signup
// setMessage("Account created successfully! Redirecting to login...");
// // In your actual implementation, integrate with your backend here:
// // const response = await fetch(`${backendUrl}/api/auth/signup`, {
// // method: 'POST',
// // headers: { 'Content-Type': 'application/json' },
// // body: JSON.stringify(formData)
// // });
// setTimeout(() => {
// // Navigate to login page in your actual implementation
// console.log("Redirecting to login page...");
// }, 2000);
} catch (error) {
🤖 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 53 - 69, Remove the dead
commented-out mock API block inside the Signup component (the commented
"Simulate API call" section) so the file no longer contains the old mock
fetch/timeout code; specifically delete the commented lines within the
Signup.tsx handleSubmit/submit flow that start with the "Simulate API call"
comment and the subsequent try/Mock successful signup/setTimeout stubs, leaving
only the real implementation and any real messaging (e.g., setMessage) intact.

Comment on lines +70 to +71
} catch (error) {
setMessage("Something went wrong. Please try again.");
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Restore backend error message extraction for better UX.

The new error handler uses a generic message, but the backend likely returns specific validation errors (e.g., "Username already exists", "Invalid email format"). Showing these details helps users understand and fix their input.

The previous implementation correctly extracted error.response?.data?.message with a fallback - that pattern should be preserved.

🔧 Proposed fix
     } catch (error) {
-      setMessage("Something went wrong. Please try again.");
+      setMessage(
+        (error as any).response?.data?.message || "Something went wrong. Please try again."
+      );
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
} catch (error) {
setMessage("Something went wrong. Please try again.");
} catch (error) {
setMessage(
(error as any).response?.data?.message || "Something went wrong. Please try again."
);
🤖 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 70 - 71, Restore extraction of the
backend-provided error message in the Signup component's catch block: when
catching the error in the signup handler, read error.response?.data?.message
(falling back to error.message or a generic string) and pass that to setMessage
instead of the hardcoded "Something went wrong..." so users see
validation/backend errors; update the catch block around the signup submission
(where setMessage is currently called) to use this extraction logic.

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: Session cookies are not persisted due to incorrect CORS setup and missing credentials in frontend requests

2 participants