Skip to content

Commit 94a5c82

Browse files
committed
fixed:cookie 3
1 parent 6771f08 commit 94a5c82

File tree

3 files changed

+206
-2
lines changed

3 files changed

+206
-2
lines changed

DEPLOYMENT_FIXES.md

Lines changed: 180 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,180 @@
1+
# 🚀 Cookie Issues - Deployment Fixes
2+
3+
## **Issues Fixed:**
4+
5+
### 1. **Dockerfile Problems Fixed:**
6+
-**Port Mismatch**: Dockerfile exposed port 3000, app runs on 4000
7+
-**Fixed**: Now exposes port 4000
8+
-**Missing NODE_ENV**: No production environment set
9+
-**Fixed**: Added `ENV NODE_ENV=production`
10+
-**Missing Prisma Generate**: Production stage didn't generate Prisma client
11+
-**Fixed**: Added `RUN pnpm exec prisma generate`
12+
13+
### 2. **Environment Configuration Fixed:**
14+
-**No dotenv**: Environment variables not loaded
15+
-**Fixed**: Added `dotenv.config()` in server.ts
16+
-**No debugging info**: Hard to troubleshoot deployment issues
17+
-**Fixed**: Added comprehensive logging and health check endpoint
18+
19+
### 3. **Cookie Configuration Fixed:**
20+
-**Inconsistent SameSite**: Login used "strict", logout used "none"
21+
-**Fixed**: Environment-based SameSite settings
22+
-**No domain support**: Cookies couldn't be shared across subdomains
23+
-**Fixed**: Added domain configuration support
24+
25+
## 🔧 **Updated Docker Commands:**
26+
27+
### Build and Run Locally:
28+
```bash
29+
# Build the Docker image
30+
docker build -t your-app-name .
31+
32+
# Run with proper environment variables
33+
docker run -d -p 4000:4000 \
34+
-e NODE_ENV=production \
35+
-e DATABASE_URL="your_database_url" \
36+
-e JWT_SECRET="your_jwt_secret" \
37+
-e COOKIE_DOMAIN="yourdomain.com" \
38+
-e FRONTEND_URL="https://yourfrontend.com" \
39+
your-app-name
40+
```
41+
42+
### For Production Deployment:
43+
```bash
44+
# Build for production
45+
docker build -t your-app-name:latest .
46+
47+
# Run in production
48+
docker run -d -p 4000:4000 \
49+
--name your-app \
50+
--restart unless-stopped \
51+
-e NODE_ENV=production \
52+
-e DATABASE_URL="postgresql://user:pass@host:port/db" \
53+
-e JWT_SECRET="your-super-secret-jwt-key" \
54+
-e COOKIE_DOMAIN=".yourdomain.com" \
55+
-e FRONTEND_URL="https://yourfrontend.com" \
56+
your-app-name:latest
57+
```
58+
59+
## 🧪 **Testing Your Deployment:**
60+
61+
### 1. **Health Check:**
62+
```bash
63+
curl https://your-api.com/health
64+
```
65+
Should return:
66+
```json
67+
{
68+
"status": "OK",
69+
"timestamp": "2024-01-01T00:00:00.000Z",
70+
"environment": "production",
71+
"port": 4000
72+
}
73+
```
74+
75+
### 2. **Test Cookie Functionality:**
76+
```bash
77+
# Test login (should set cookie)
78+
curl -X POST https://your-api.com/api/auth/login \
79+
-H "Content-Type: application/json" \
80+
-d '{"email":"[email protected]","password":"password"}' \
81+
-c cookies.txt
82+
83+
# Test authenticated request (should use cookie)
84+
curl -X GET https://your-api.com/api/auth/me \
85+
-b cookies.txt
86+
```
87+
88+
## 🔍 **Debugging Steps:**
89+
90+
### 1. **Check Docker Logs:**
91+
```bash
92+
docker logs your-app-name
93+
```
94+
Look for:
95+
- Environment variables being loaded
96+
- Cookie domain settings
97+
- CORS configuration
98+
99+
### 2. **Check Health Endpoint:**
100+
Visit `https://your-api.com/health` to see:
101+
- Environment status
102+
- Port configuration
103+
- Cookie domain settings
104+
105+
### 3. **Browser Developer Tools:**
106+
- Check Network tab for cookie headers
107+
- Verify `Set-Cookie` response headers
108+
- Check if cookies are being sent in requests
109+
110+
## 🌐 **Frontend Configuration:**
111+
112+
Make sure your frontend includes credentials:
113+
114+
```javascript
115+
// Example fetch configuration
116+
const apiCall = async (url, options = {}) => {
117+
const response = await fetch(`https://your-api.com${url}`, {
118+
...options,
119+
credentials: 'include', // This is crucial!
120+
headers: {
121+
'Content-Type': 'application/json',
122+
...options.headers,
123+
},
124+
});
125+
return response.json();
126+
};
127+
128+
// Login example
129+
const login = async (email, password) => {
130+
return apiCall('/api/auth/login', {
131+
method: 'POST',
132+
body: JSON.stringify({ email, password }),
133+
});
134+
};
135+
```
136+
137+
## 🚨 **Common Issues & Solutions:**
138+
139+
### Issue: Cookies not being set
140+
**Solution**:
141+
- Ensure `NODE_ENV=production` is set
142+
- Verify HTTPS is enabled
143+
- Check `sameSite: "none"` for cross-origin requests
144+
145+
### Issue: Cookies not being sent
146+
**Solution**:
147+
- Add `credentials: 'include'` to frontend requests
148+
- Verify CORS allows your frontend origin
149+
- Check cookie domain configuration
150+
151+
### Issue: CORS errors
152+
**Solution**:
153+
- Add your frontend URL to CORS origins
154+
- Set `FRONTEND_URL` environment variable
155+
- Verify `credentials: true` in CORS config
156+
157+
## 📋 **Environment Variables Checklist:**
158+
159+
```env
160+
# Required
161+
NODE_ENV=production
162+
DATABASE_URL=postgresql://user:pass@host:port/db
163+
JWT_SECRET=your-super-secret-key
164+
165+
# Optional (for cookie sharing)
166+
COOKIE_DOMAIN=.yourdomain.com
167+
168+
# Optional (for CORS)
169+
FRONTEND_URL=https://yourfrontend.com
170+
```
171+
172+
## 🎯 **Next Steps:**
173+
174+
1. **Rebuild your Docker image** with these fixes
175+
2. **Deploy with proper environment variables**
176+
3. **Test the health endpoint** first
177+
4. **Test login/logout functionality**
178+
5. **Verify cookies work in your frontend**
179+
180+
The main issues were in the Dockerfile configuration and missing environment setup. These fixes should resolve your cookie sharing problems! 🎉

Dockerfile

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,12 +18,18 @@ FROM node:20-alpine
1818
WORKDIR /app
1919
RUN npm install -g pnpm
2020

21+
# Set production environment
22+
ENV NODE_ENV=production
23+
2124
COPY package.json pnpm-lock.yaml ./
2225
RUN pnpm install --prod --frozen-lockfile --shamefully-hoist
2326

2427
COPY --from=builder /app/dist ./dist
2528
COPY --from=builder /app/node_modules ./node_modules
2629
COPY prisma ./prisma
2730

28-
EXPOSE 3000
31+
# Generate Prisma client for production
32+
RUN pnpm exec prisma generate
33+
34+
EXPOSE 4000
2935
CMD ["node", "dist/server.js"]

src/server.ts

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,12 @@
1+
import dotenv from "dotenv";
12
import express from "express";
23
import morgan from "morgan";
34
import router from "./routes/router";
45
import cookieParser from "cookie-parser";
56
import cors from "cors";
7+
8+
// Load environment variables
9+
dotenv.config();
610
const PORT = Number(process.env.PORT) || 4000;
711
const app = express();
812
app.use(express.json());
@@ -27,8 +31,22 @@ const corsOptions = {
2731

2832
app.use(cors(corsOptions));
2933
app.use(morgan("combined"));
34+
35+
// Health check endpoint
36+
app.get("/health", (req, res) => {
37+
res.status(200).json({
38+
status: "OK",
39+
timestamp: new Date().toISOString(),
40+
environment: process.env.NODE_ENV || "development",
41+
port: PORT,
42+
});
43+
});
44+
3045
app.use("/api", router);
3146

3247
app.listen(PORT, "0.0.0.0", () => {
33-
console.log(`App is running and listening on port: ${PORT}`);
48+
console.log(`🚀 App is running and listening on port: ${PORT}`);
49+
console.log(`🌍 Environment: ${process.env.NODE_ENV || "development"}`);
50+
console.log(`🍪 Cookie domain: ${process.env.COOKIE_DOMAIN || "not set"}`);
51+
console.log(`🔗 Frontend URL: ${process.env.FRONTEND_URL || "not set"}`);
3452
});

0 commit comments

Comments
 (0)