Skip to content

Commit 086310d

Browse files
committed
Fix allowedOrigins by trusting all origins in production
1 parent 2a716e5 commit 086310d

File tree

1 file changed

+34
-13
lines changed

1 file changed

+34
-13
lines changed

backend/src/server.ts

Lines changed: 34 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -46,21 +46,42 @@ const NODE_ENV = process.env.NODE_ENV || 'development';
4646

4747
const app = express()
4848
const PORT = parseInt(process.env.PORT || '5001', 10);
49-
const allowedOrigins = process.env.NODE_ENV === 'production'
50-
? ['http://localhost:3000', 'http://localhost']
51-
: ['http://localhost:5173', 'http://10.0.0.153:5173', 'http://localhost:3000', 'http://10.0.0.153:3000'];
49+
// CORS configuration
50+
// In Docker production: Nginx proxies /api requests, so browser sees same-origin (no CORS needed)
51+
// For flexibility, users can set CORS_ORIGINS env var with comma-separated origins
52+
const getCorsOrigins = (): string[] | true => {
53+
// In production with Docker, allow all origins since Nginx handles proxying
54+
if (process.env.NODE_ENV === 'production') {
55+
// If user wants to restrict origins, they can set CORS_ORIGINS
56+
if (process.env.CORS_ORIGINS) {
57+
return process.env.CORS_ORIGINS.split(',').map(o => o.trim());
58+
}
59+
// Default: allow all origins (Nginx proxy makes this safe)
60+
return true as const;
61+
}
62+
63+
// Development mode: use CORS_ORIGINS if set, otherwise default to localhost
64+
if (process.env.CORS_ORIGINS) {
65+
return process.env.CORS_ORIGINS.split(',').map(o => o.trim());
66+
}
67+
return ['http://localhost:5173', 'http://localhost:3000'];
68+
};
69+
70+
const corsOrigins = getCorsOrigins();
5271

5372
app.use(cors({
54-
origin: (origin, callback) => {
55-
// Allow requests with no origin (like mobile apps or curl requests)
56-
if (!origin) return callback(null, true);
57-
58-
if (allowedOrigins.indexOf(origin) !== -1 || process.env.NODE_ENV === 'production') {
59-
callback(null, true);
60-
} else {
61-
callback(new Error('Not allowed by CORS'));
62-
}
63-
},
73+
origin: corsOrigins === true
74+
? true // Allow all origins
75+
: (origin, callback) => {
76+
// Allow requests with no origin (like mobile apps or curl requests)
77+
if (!origin) return callback(null, true);
78+
79+
if (corsOrigins.includes(origin)) {
80+
callback(null, true);
81+
} else {
82+
callback(new Error('Not allowed by CORS'));
83+
}
84+
},
6485
credentials: true
6586
}))
6687
app.use(express.json());

0 commit comments

Comments
 (0)