umer6016 commited on
Commit
c57cfaf
·
1 Parent(s): 7267617

Configure FastAPI to serve React frontend static files

Browse files
Files changed (1) hide show
  1. backend/app/main.py +29 -0
backend/app/main.py CHANGED
@@ -24,6 +24,35 @@ def get_application() -> FastAPI:
24
  )
25
 
26
  app.include_router(api_router, prefix="/api")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
  return app
28
 
29
 
 
24
  )
25
 
26
  app.include_router(api_router, prefix="/api")
27
+
28
+ # Serve static files (Frontend)
29
+ import os
30
+ from fastapi.staticfiles import StaticFiles
31
+ from fastapi.responses import FileResponse
32
+
33
+ # Determine absolute path to dist folder
34
+ # In Docker (WORKDIR /app), this is /app/frontend/dist
35
+ # Locally, it depends where we run from. We'll rely on relative path from root.
36
+ DIST_DIR = os.path.join(os.getcwd(), "frontend", "dist")
37
+
38
+ if os.path.exists(DIST_DIR):
39
+ app.mount("/assets", StaticFiles(directory=os.path.join(DIST_DIR, "assets")), name="assets")
40
+
41
+ # Catch-all for SPA routing (must be last)
42
+ @app.get("/{full_path:path}")
43
+ async def serve_spa(full_path: str):
44
+ # If API request fell through to here, return 404
45
+ if full_path.startswith("api/"):
46
+ return {"detail": "Not Found"}
47
+
48
+ # Use index.html for all other routes (SPA)
49
+ index_path = os.path.join(DIST_DIR, "index.html")
50
+ if os.path.exists(index_path):
51
+ return FileResponse(index_path)
52
+ return {"detail": "Frontend not found (build missing)"}
53
+ else:
54
+ print(f"⚠️ Frontend dist not found at {DIST_DIR}. Serving API only.")
55
+
56
  return app
57
 
58