From d2d8370c95c3a9e99eb68258ead849e40a105e3b Mon Sep 17 00:00:00 2001 From: Evan Reichard Date: Thu, 5 Feb 2026 18:21:47 -0500 Subject: [PATCH] feat: add CORS middleware to backend server Add cross-origin resource sharing support to the backend API to fix frontend console errors when accessing resources from different origins. The middleware handles preflight requests and includes necessary CORS headers for API endpoints. Fixes: Cross-Origin Request Blocked error --- backend/internal/api/server.go | 24 +++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/backend/internal/api/server.go b/backend/internal/api/server.go index b94943a..fd0cc89 100644 --- a/backend/internal/api/server.go +++ b/backend/internal/api/server.go @@ -15,6 +15,25 @@ type ErrorResponse struct { Error string `json:"error"` } +// CORS middleware for allowing cross-origin requests +func corsMiddleware(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + // Allow requests from any origin during development + // In production, you would specify allowed origins + w.Header().Set("Access-Control-Allow-Origin", "*") + w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS") + w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization") + + // Handle preflight requests + if r.Method == "OPTIONS" { + w.WriteHeader(http.StatusOK) + return + } + + next.ServeHTTP(w, r) + }) +} + type Server struct { storage *storage.Storage host string @@ -42,10 +61,13 @@ func (s *Server) Start() error { // Frontend SPA fallback mux.HandleFunc("/", s.handleFrontend) + // Wrap with CORS middleware + handler := corsMiddleware(mux) + addr := fmt.Sprintf("%s:%d", s.host, s.port) logger.Infof("Starting server on %s", addr) - return http.ListenAndServe(addr, mux) + return http.ListenAndServe(addr, handler) } func (s *Server) handleFiles(w http.ResponseWriter, r *http.Request) {