Skip to content

fix(auth): add withCredentials and fix CORS to persist session cookies#464

Open
anshul23102 wants to merge 1 commit into
GitMetricsLab:mainfrom
anshul23102:fix/414-withcredentials-session-cookie
Open

fix(auth): add withCredentials and fix CORS to persist session cookies#464
anshul23102 wants to merge 1 commit into
GitMetricsLab:mainfrom
anshul23102:fix/414-withcredentials-session-cookie

Conversation

@anshul23102
Copy link
Copy Markdown

@anshul23102 anshul23102 commented May 23, 2026

Summary

Fixes #414

The root cause of the broken session is a missing { withCredentials: true } in both axios calls, compounded by a wildcard CORS config that the browser rejects whenever credentials are involved. Three files are changed.

Changes

src/pages/Login/Login.tsx
Added { withCredentials: true } as the third argument to axios.post for /api/auth/login. Without this flag the browser silently discards the Set-Cookie header on every cross-origin response, so no session cookie is ever stored.

src/pages/Signup/Signup.tsx
Same fix for /api/auth/signup. Also removed the stale inline comment // Include cookies for session that documented the intended behaviour but was never implemented.

backend/server.js
Replaced cors('*') with a credentials-aware configuration:

app.use(cors({
  origin: process.env.FRONTEND_URL || 'http://localhost:5173',
  credentials: true,
}));

The Fetch specification forbids Access-Control-Allow-Origin: * when Access-Control-Allow-Credentials: true is set. Browsers reject the response silently, which means withCredentials: true on the client side has no effect without this server-side change. A specific origin is required; FRONTEND_URL is read from the backend .env file, with a localhost fallback for local development.

Test plan

  • Start backend and frontend locally
  • Log in with valid credentials
  • Open DevTools > Application > Cookies: confirm session cookie is stored after login
  • Navigate to a protected page: confirm Cookie header is present on subsequent requests
  • Log out: confirm cookie is cleared
  • Repeat for signup flow
  • Set FRONTEND_URL in backend/.env to the production URL and confirm CORS header matches in prod

Summary by CodeRabbit

  • Bug Fixes
    • Enhanced authentication handling to properly transmit browser credentials during login and signup operations, ensuring more reliable session establishment and consistent user access. These improvements enable better credential handling across different browser configurations and environments, strengthening the overall authentication workflow.

Review Change Stack

@netlify
Copy link
Copy Markdown

netlify Bot commented May 23, 2026

Deploy Preview for github-spy ready!

Name Link
🔨 Latest commit d55fbcf
🔍 Latest deploy log https://app.netlify.com/projects/github-spy/deploys/6a12fa8bb643660008e1477f
😎 Deploy Preview https://deploy-preview-464--github-spy.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify project configuration.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented May 23, 2026

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 2827752f-0adf-49e8-a46e-accf5b05498c

📥 Commits

Reviewing files that changed from the base of the PR and between fbf9cd8 and d55fbcf.

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

📝 Walkthrough

Walkthrough

Login and Signup pages update their axios POST requests to include { withCredentials: true }, enabling the browser to store and send session cookies on cross-origin authenticated requests. The requests are reformatted across multiple lines with explicit axios configuration, while preserving existing endpoint URLs, response handling, and error messaging.

Changes

Frontend Credential Configuration

Layer / File(s) Summary
Login and Signup credential handling
src/pages/Login/Login.tsx, src/pages/Signup/Signup.tsx
Both pages update their axios POST requests to /api/auth/login and /api/auth/signup with { withCredentials: true }, enabling the browser to store and transmit session cookies on cross-origin requests. Requests are reformatted across multiple lines while preserving endpoint URLs and response message extraction.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~8 minutes

Possibly related issues

Possibly related PRs

  • GitMetricsLab/github_tracker#269: Modifies src/pages/Signup/Signup.tsx handleSubmit flow and axios request structure, overlapping at the signup request configuration level with the current PR's changes.

Poem

🐰 Cookies now stick, credentials flow free,
Login and signup, authenticated spree!
withCredentials: true sets the session so right,
Cross-origin requests now hold sessions tight! 🍪✨

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The PR title clearly and specifically describes the main changes: adding withCredentials to axios calls and fixing CORS configuration to persist session cookies.
Description check ✅ Passed The description includes all required template sections with detailed explanations of the problem, changes made, and a comprehensive test plan.
Linked Issues check ✅ Passed All coding requirements from issue #414 are addressed: withCredentials added to Login.tsx and Signup.tsx, CORS configuration updated in backend/server.js to allow credentials with specific origin.
Out of Scope Changes check ✅ Passed All changes directly address issue #414 requirements; the three modified files are exactly those specified in the issue with no extraneous modifications detected.
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.

Copy link
Copy Markdown

@github-actions github-actions Bot left a comment

Choose a reason for hiding this comment

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

🎉 Thank you @anshul23102 for your contribution. Please make sure your PR follows https://github.com/GitMetricsLab/github_tracker/blob/main/CONTRIBUTING.md#-pull-request-guidelines

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.

Caution

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

⚠️ Outside diff range comments (1)
backend/server.js (1)

26-30: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Add express-session cookie sameSite/secure options for credentialed cross-origin requests.

backend/server.js enables CORS with credentials: true, and the frontend sends axios requests with { withCredentials: true }, but the express-session config lacks cookie.sameSite/cookie.secure. For cross-origin deployments, browsers will reject/drop the session cookie unless sameSite: 'none' and secure: true are set.

File: backend/server.js
Lines: 26-30

app.use(session({
    secret: process.env.SESSION_SECRET,
    resave: false,
    saveUninitialized: false,
}));
🍪 Proposed fix for cross-origin cookie support
 app.use(session({
     secret: process.env.SESSION_SECRET,
     resave: false,
     saveUninitialized: false,
+    cookie: {
+      secure: process.env.NODE_ENV === 'production', // HTTPS only in production
+      sameSite: process.env.NODE_ENV === 'production' ? 'none' : 'lax',
+      httpOnly: 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 `@backend/server.js` around lines 26 - 30, The session cookie config in the
app.use(session(...)) call is missing cookie options required for cross-origin
credentialed requests; update the session middleware (the app.use(session)
invocation) to include a cookie object with sameSite: 'none' and secure: true,
and ensure the app trusts proxies when running behind an HTTPS terminator by
setting app.set('trust proxy', 1) or equivalent so secure cookies are sent;
optionally guard secure by NODE_ENV if you need a different behavior in
development.
🤖 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.

Outside diff comments:
In `@backend/server.js`:
- Around line 26-30: The session cookie config in the app.use(session(...)) call
is missing cookie options required for cross-origin credentialed requests;
update the session middleware (the app.use(session) invocation) to include a
cookie object with sameSite: 'none' and secure: true, and ensure the app trusts
proxies when running behind an HTTPS terminator by setting app.set('trust
proxy', 1) or equivalent so secure cookies are sent; optionally guard secure by
NODE_ENV if you need a different behavior in development.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: b2edab9d-7137-4ead-a7e8-37874a13d922

📥 Commits

Reviewing files that changed from the base of the PR and between 373dde2 and fbf9cd8.

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

@anshul23102
Copy link
Copy Markdown
Author

Hi @GitMetricsLab team, just checking in on this one. The fix addresses the session cookie issue where the browser was silently dropping Set-Cookie headers on every cross-origin response because withCredentials was missing on the axios calls, and the wildcard CORS config was incompatible with credentialed requests. Both the client-side flag and the server-side CORS config are updated together so the fix actually sticks. Happy to make any changes if something needs adjusting before merge.

Login.tsx and Signup.tsx were sending axios POST requests without
{ withCredentials: true }, so the browser silently discarded the
Set-Cookie header on every cross-origin login/signup response. No
session cookie was ever stored, making every subsequent request
appear unauthenticated.

Changes:
- src/pages/Login/Login.tsx: pass { withCredentials: true } as the
  third argument to axios.post for /api/auth/login
- src/pages/Signup/Signup.tsx: same fix for /api/auth/signup; also
  remove the stale "Include cookies for session" comment that noted
  the intent but was never fulfilled
- backend/server.js: replace cors('*') with a credentials-aware
  config (origin: FRONTEND_URL, credentials: true); a wildcard origin
  is rejected by browsers when credentials are present, so a specific
  origin is required for Set-Cookie to be honoured

Fixes GitMetricsLab#414
@anshul23102 anshul23102 force-pushed the fix/414-withcredentials-session-cookie branch from fbf9cd8 to d55fbcf Compare May 24, 2026 13:18
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] axios requests in Login.tsx and Signup.tsx missing withCredentials: true — session cookie never attached

1 participant