2026-02-20 18:21:24 +05:30
|
|
|
import type { Client } from '@hey-api/client-fetch';
|
|
|
|
|
|
2025-09-09 14:37:32 +05:30
|
|
|
import type { CreateClientConfig } from '@/client/client.gen';
|
|
|
|
|
|
|
|
|
|
export const createClientConfig: CreateClientConfig = (config) => {
|
|
|
|
|
// Use different URLs for server-side vs client-side
|
|
|
|
|
const isServer = typeof window === 'undefined';
|
2025-11-20 21:33:05 +05:30
|
|
|
let baseUrl: string;
|
|
|
|
|
|
|
|
|
|
if (isServer) {
|
|
|
|
|
// for server-side rendering, still use environment variable as fallback
|
|
|
|
|
baseUrl = process.env.BACKEND_URL || 'http://api:8000';
|
|
|
|
|
} else {
|
2026-02-20 18:21:24 +05:30
|
|
|
// Client-side API calls are proxied through Next.js rewrites.
|
|
|
|
|
// AppConfigContext may update this later with the fetched backend URL.
|
|
|
|
|
baseUrl = window.location.origin;
|
2025-11-20 21:33:05 +05:30
|
|
|
}
|
2025-09-09 14:37:32 +05:30
|
|
|
|
|
|
|
|
return {
|
|
|
|
|
...config,
|
|
|
|
|
baseUrl,
|
|
|
|
|
};
|
|
|
|
|
};
|
2026-02-18 13:16:49 +05:30
|
|
|
|
|
|
|
|
let interceptorRegistered = false;
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Register a request interceptor that attaches a fresh access token
|
|
|
|
|
* to every outgoing SDK request. Idempotent — safe for React strict mode.
|
|
|
|
|
*/
|
2026-02-20 18:21:24 +05:30
|
|
|
export function setupAuthInterceptor(apiClient: Client, getAccessToken: () => Promise<string>) {
|
2026-02-18 13:16:49 +05:30
|
|
|
if (interceptorRegistered) return;
|
|
|
|
|
interceptorRegistered = true;
|
|
|
|
|
|
2026-02-20 18:21:24 +05:30
|
|
|
apiClient.interceptors.request.use(async (request) => {
|
2026-02-18 13:16:49 +05:30
|
|
|
if (request.headers.get('Authorization')) {
|
|
|
|
|
return request;
|
|
|
|
|
}
|
|
|
|
|
try {
|
|
|
|
|
const token = await getAccessToken();
|
|
|
|
|
request.headers.set('Authorization', `Bearer ${token}`);
|
|
|
|
|
} catch {
|
|
|
|
|
// If token retrieval fails, let the request proceed without auth
|
|
|
|
|
}
|
|
|
|
|
return request;
|
|
|
|
|
});
|
|
|
|
|
}
|