Skip to content

Commit fbf9cd8

Browse files
committed
fix(auth): add withCredentials and fix CORS to persist session cookies
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 #414
1 parent 373dde2 commit fbf9cd8

3 files changed

Lines changed: 16 additions & 5 deletions

File tree

backend/server.js

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,12 @@ const logger = require('./logger');
1414
const app = express();
1515

1616
// CORS configuration
17-
app.use(cors('*'));
17+
// withCredentials requires a specific origin — wildcard ('*') is rejected by browsers
18+
// when credentials are involved. FRONTEND_URL must be set in the backend .env file.
19+
app.use(cors({
20+
origin: process.env.FRONTEND_URL || 'http://localhost:5173',
21+
credentials: true,
22+
}));
1823

1924
// Middleware
2025
app.use(bodyParser.json());

src/pages/Login/Login.tsx

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,11 @@ const Login: React.FC = () => {
3030
setIsLoading(true);
3131

3232
try {
33-
const response = await axios.post(`${backendUrl}/api/auth/login`, formData);
33+
const response = await axios.post(
34+
`${backendUrl}/api/auth/login`,
35+
formData,
36+
{ withCredentials: true }
37+
);
3438
setMessage(response.data.message);
3539

3640
if (response.data.message === 'Login successful') {

src/pages/Signup/Signup.tsx

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -83,10 +83,12 @@ const SignUp: React.FC = () => {
8383
}
8484
setIsLoading(true);
8585
try {
86-
const response = await axios.post(`${backendUrl}/api/auth/signup`,
87-
formData // Include cookies for session
86+
const response = await axios.post(
87+
`${backendUrl}/api/auth/signup`,
88+
formData,
89+
{ withCredentials: true }
8890
);
89-
setMessage(response.data.message); // Show success message from backend
91+
setMessage(response.data.message);
9092

9193
// Navigate to login page after successful signup
9294
if (response.data.message === 'User created successfully') {

0 commit comments

Comments
 (0)