From 18a4857c2b59c97142ddfc5003dd9a1e72c14ad1 Mon Sep 17 00:00:00 2001 From: "DESKTOP-RTLN3BA\\$punk" Date: Fri, 19 Dec 2025 14:49:49 -0800 Subject: [PATCH] feat: enhance CORS configuration for frontend integration - Updated CORS middleware to allow specific origins based on NEXT_FRONTEND_URL. - Added support for localhost origins for local development. - Ensured compatibility with both www and non-www variants of the frontend URL. --- surfsense_backend/app/app.py | 33 ++++++++++++++++++++++++++++++++- 1 file changed, 32 insertions(+), 1 deletion(-) diff --git a/surfsense_backend/app/app.py b/surfsense_backend/app/app.py index b4c47de8f..3faa76e1a 100644 --- a/surfsense_backend/app/app.py +++ b/surfsense_backend/app/app.py @@ -34,9 +34,40 @@ app = FastAPI(lifespan=lifespan) app.add_middleware(ProxyHeadersMiddleware, trusted_hosts="*") # Add CORS middleware +# When using credentials, we must specify exact origins (not "*") +# Build allowed origins list from NEXT_FRONTEND_URL +allowed_origins = [] +if config.NEXT_FRONTEND_URL: + allowed_origins.append(config.NEXT_FRONTEND_URL) + # Also allow without trailing slash and with www/without www variants + frontend_url = config.NEXT_FRONTEND_URL.rstrip("/") + if frontend_url not in allowed_origins: + allowed_origins.append(frontend_url) + # Handle www variants + if "://www." in frontend_url: + non_www = frontend_url.replace("://www.", "://") + if non_www not in allowed_origins: + allowed_origins.append(non_www) + elif "://" in frontend_url and "://www." not in frontend_url: + # Add www variant + www_url = frontend_url.replace("://", "://www.") + if www_url not in allowed_origins: + allowed_origins.append(www_url) + +# For local development, also allow common localhost origins +if not config.BACKEND_URL or ( + config.NEXT_FRONTEND_URL and "localhost" in config.NEXT_FRONTEND_URL +): + allowed_origins.extend( + [ + "http://localhost:3000", + "http://127.0.0.1:3000", + ] + ) + app.add_middleware( CORSMiddleware, - allow_origins=["*"], # Allows all origins + allow_origins=allowed_origins, allow_credentials=True, allow_methods=["*"], # Allows all methods allow_headers=["*"], # Allows all headers