This document describes the integration between the ExploitRAG frontend (Next.js) and backend (FastAPI).
NEXT_PUBLIC_API_URL=http://localhost:8000ALLOWED_ORIGINS=http://localhost:3000,http://localhost:8000- User registers/logs in via
/api/auth/registeror/api/auth/login - Backend returns JWT access token and refresh token
- Frontend stores tokens in localStorage
- All subsequent requests include
Authorization: Bearer <token>header - On 401 errors, frontend automatically attempts token refresh
- If refresh fails, user is redirected to login
Centralized API client with:
- Automatic token injection
- Automatic token refresh on 401
- Error handling
- Helper functions (apiGet, apiPost, apiDelete)
- Manages user authentication state
- Provides login, register, logout functions
- Handles token storage and refresh
- Exposes current user information
- Manages conversations and messages
- Handles streaming and synchronous chat queries
- Provides conversation CRUD operations
- Manages chat settings
POST /api/auth/register- Register new userPOST /api/auth/login- Login userPOST /api/auth/refresh- Refresh access tokenGET /api/auth/me- Get current user info
POST /api/chat/query- Streaming chat (SSE)POST /api/chat/query-sync- Synchronous chat
GET /api/conversations- List all conversationsPOST /api/conversations- Create new conversationGET /api/conversations/{id}- Get conversation detailsDELETE /api/conversations/{id}- Delete conversationGET /api/conversations/{id}/export/{format}- Export conversation
The frontend uses Server-Sent Events (SSE) for streaming chat responses:
const response = await fetch(`${API_BASE_URL}/api/chat/query`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${accessToken}`,
},
body: JSON.stringify({
conversation_id: conversationId,
message: content,
}),
});
const reader = response.body?.getReader();
const decoder = new TextDecoder();
// Process SSE stream
while (true) {
const { done, value } = await reader.read();
if (done) break;
const chunk = decoder.decode(value);
// Parse SSE format: "data: {json}\n\n"
// Update UI with delta content
}The backend is configured to allow requests from the frontend origin:
app.add_middleware(
CORSMiddleware,
allow_origins=settings.allowed_origins_list, # ["http://localhost:3000"]
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)- Start backend:
cd backend && uvicorn app.main:app --reload - Start frontend:
cd frontend && npm run dev - Open browser to
http://localhost:3000 - Register a new account
- Send a chat message
- Verify streaming response
Use the integration test utility:
import { runIntegrationTests } from "@/lib/integration-test";
const { overall, results } = await runIntegrationTests();
console.log("Integration tests:", results);Problem: Browser shows CORS policy errors
Solution: Ensure ALLOWED_ORIGINS in backend .env includes frontend URL
Problem: Requests fail with 401 even after login Solution: Check that tokens are being stored in localStorage and included in headers
Problem: Chat responses don't stream Solution:
- Verify SSE parsing logic
- Check browser network tab for event stream
- Ensure nginx/proxy isn't buffering responses
Problem: Infinite token refresh attempts Solution: Check token expiration times and refresh logic
- Use React DevTools to inspect AuthContext and ChatContext state
- Check Network Tab to see actual API requests/responses
- Monitor Backend Logs for server-side errors
- Use Integration Tests to verify connectivity before debugging UI
- Environment Variables: Use proper production URLs
- Token Storage: Consider using httpOnly cookies instead of localStorage
- HTTPS: Ensure all communication uses HTTPS
- Rate Limiting: Backend has rate limits (20 req/min for chat)
- Error Handling: Implement proper error boundaries and user feedback
- Token Refresh: Consider implementing silent refresh before token expiry
All TypeScript types are defined in lib/types.ts:
TokenResponse- Authentication tokensUserResponse- User informationConversationResponse- Conversation metadataMessageResponse- Message dataContextSource- RAG context sourcesChatQueryResponse- Chat response with sources
- ✅ Environment configuration
- ✅ API client implementation
- ✅ Authentication context
- ✅ Chat context with streaming
- ✅ Integration tests
- 🔄 UI components (in progress)
- ⏳ Error boundaries
- ⏳ Loading states
- ⏳ Production deployment