Dynamic Intelligence commited on
Commit
24755ba
·
1 Parent(s): 46f3967

Fix 401 error: Add authenticated API proxy for private datasets

Browse files
Files changed (1) hide show
  1. src/utils/apiHelpers.ts +64 -0
src/utils/apiHelpers.ts ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * Helper functions for API calls
3
+ * Handles both server-side and client-side URL construction
4
+ */
5
+
6
+ import { headers } from 'next/headers';
7
+
8
+ /**
9
+ * Get the base URL for API calls
10
+ * For server-side, we need absolute URLs
11
+ * For client-side, we can use relative URLs
12
+ */
13
+ export async function getApiBaseUrl(): Promise<string> {
14
+ // Server-side: need absolute URL
15
+ if (typeof window === 'undefined') {
16
+ try {
17
+ // Use Next.js headers to get the host
18
+ const headersList = await headers();
19
+ const host = headersList.get('host');
20
+ const protocol = headersList.get('x-forwarded-proto') || 'https';
21
+
22
+ if (host) {
23
+ return `${protocol}://${host}`;
24
+ }
25
+ } catch (error) {
26
+ // headers() might not be available in all contexts
27
+ // Fall through to environment variables
28
+ }
29
+
30
+ // Fallback: try environment variables
31
+ const spaceUrl =
32
+ process.env.SPACE_URL ||
33
+ process.env.NEXT_PUBLIC_APP_URL ||
34
+ process.env.VERCEL_URL ||
35
+ process.env.HF_SPACE_URL;
36
+
37
+ if (spaceUrl) {
38
+ // Ensure it has protocol
39
+ if (spaceUrl.startsWith('http://') || spaceUrl.startsWith('https://')) {
40
+ // Remove trailing slash
41
+ return spaceUrl.endsWith('/') ? spaceUrl.slice(0, -1) : spaceUrl;
42
+ }
43
+ return `https://${spaceUrl}`;
44
+ }
45
+
46
+ // Last resort: use relative URL (Next.js should handle this for same-origin)
47
+ return '';
48
+ }
49
+
50
+ // Client-side: use relative URL (empty string)
51
+ return '';
52
+ }
53
+
54
+ /**
55
+ * Build proxy URL for Hugging Face requests
56
+ * Automatically handles server-side vs client-side
57
+ * Note: This is async because getApiBaseUrl() is async (needed for server-side)
58
+ */
59
+ export async function buildProxyUrl(targetUrl: string): Promise<string> {
60
+ const apiBase = await getApiBaseUrl();
61
+ const encodedUrl = encodeURIComponent(targetUrl);
62
+ return `${apiBase}/api/hf-proxy?url=${encodedUrl}`;
63
+ }
64
+