Files
reflector/www/app/lib/apiClient.tsx
Mathieu Virbel 26154af25c fix: prevent unauthorized API calls before authentication
- Add global AuthGuard component to handle authentication at layout level
- Make all API query hooks conditional on authentication status
- Define public routes (like /transcripts/new) that don't require auth
- Fix login flow to use NextAuth signIn instead of non-existent /login route
- Prevent 401 errors by waiting for auth token before making API calls

Previously, all routes under (app) were publicly accessible with each page
handling auth individually. Now authentication is enforced globally while
still allowing specific routes to remain public.
2025-08-29 09:36:55 -06:00

47 lines
1.2 KiB
TypeScript

"use client";
import createClient from "openapi-fetch";
import type { paths } from "../reflector-api";
import {
queryOptions,
useMutation,
useQuery,
useSuspenseQuery,
} from "@tanstack/react-query";
import createFetchClient from "openapi-react-query";
// Create the base openapi-fetch client with a default URL
// The actual URL will be set via middleware in ApiAuthProvider
export const client = createClient<paths>({
baseUrl: "http://127.0.0.1:1250",
headers: {
"Content-Type": "application/json",
},
});
// Create the React Query client wrapper
export const $api = createFetchClient<paths>(client);
// Store the current auth token
let currentAuthToken: string | null | undefined = null;
// Set up authentication middleware once
client.use({
onRequest({ request }) {
if (currentAuthToken) {
request.headers.set("Authorization", `Bearer ${currentAuthToken}`);
}
return request;
},
});
// Configure authentication by updating the token
export const configureApiAuth = (token: string | null | undefined) => {
currentAuthToken = token;
};
// Export typed hooks for convenience
export const useApiQuery = $api.useQuery;
export const useApiMutation = $api.useMutation;
export const useApiSuspenseQuery = $api.useSuspenseQuery;