Skip to content

Commit b441e60

Browse files
committed
Fix CORS origin handling for Railway frontend
1 parent e87bcbd commit b441e60

1 file changed

Lines changed: 45 additions & 8 deletions

File tree

  • backend/internal/middleware/cors
Lines changed: 45 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,25 @@
11
package middleware
22

3-
import
4-
("net/http"
5-
3+
import (
4+
"net/http"
5+
"os"
6+
"strings"
67
)
78

89
func CORS(next http.Handler) http.Handler {
10+
allowedOrigins := allowedOriginsFromEnv()
911

1012
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
11-
url:="https://scintillating-commitment-production-2429.up.railway.app/"
12-
w.Header().Set("Access-Control-Allow-Origin", url)
13+
origin := strings.TrimSpace(r.Header.Get("Origin"))
14+
if isAllowedOrigin(origin, allowedOrigins) {
15+
w.Header().Set("Access-Control-Allow-Origin", origin)
16+
w.Header().Add("Vary", "Origin")
17+
}
1318

1419
w.Header().Set("Access-Control-Allow-Credentials", "true")
15-
1620
w.Header().Set("Access-Control-Allow-Headers", "Authorization, Content-Type")
17-
1821
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PATCH, PUT, DELETE, OPTIONS")
1922

20-
// preflight
2123
if r.Method == http.MethodOptions {
2224
w.WriteHeader(http.StatusOK)
2325
return
@@ -26,3 +28,38 @@ func CORS(next http.Handler) http.Handler {
2628
next.ServeHTTP(w, r)
2729
})
2830
}
31+
32+
func allowedOriginsFromEnv() map[string]struct{} {
33+
origins := map[string]struct{}{}
34+
35+
for _, envKey := range []string{"CLIENT_URL", "CORS_ALLOWED_ORIGINS"} {
36+
raw := strings.TrimSpace(os.Getenv(envKey))
37+
if raw == "" {
38+
continue
39+
}
40+
41+
for _, candidate := range strings.Split(raw, ",") {
42+
origin := strings.TrimSpace(strings.TrimSuffix(candidate, "/"))
43+
if origin == "" {
44+
continue
45+
}
46+
origins[origin] = struct{}{}
47+
}
48+
}
49+
50+
if len(origins) == 0 {
51+
origins["http://localhost:5173"] = struct{}{}
52+
}
53+
54+
return origins
55+
}
56+
57+
func isAllowedOrigin(origin string, allowed map[string]struct{}) bool {
58+
if origin == "" {
59+
return false
60+
}
61+
62+
normalized := strings.TrimSuffix(strings.TrimSpace(origin), "/")
63+
_, ok := allowed[normalized]
64+
return ok
65+
}

0 commit comments

Comments
 (0)