|
15 | 15 |
|
16 | 16 | import { headers as nextHeaders } from "next/headers"; |
17 | 17 | import { redirect } from "next/navigation"; |
18 | | -import { client } from "@/generated/client.gen"; |
| 18 | +import { createClient, createConfig } from "@/generated/client"; |
19 | 19 | import * as apiServices from "@/generated/sdk.gen"; |
20 | 20 | import { auth } from "./auth/auth"; |
21 | 21 | import { getValidOidcToken } from "./auth/token"; |
22 | 22 |
|
| 23 | +// Validate required environment variables at module load time (fail-fast) |
| 24 | +const API_BASE_URL = process.env.API_BASE_URL; |
| 25 | +if (!API_BASE_URL) { |
| 26 | + throw new Error( |
| 27 | + "API_BASE_URL environment variable is required but not set. Please configure it in your .env file.", |
| 28 | + ); |
| 29 | +} |
| 30 | + |
23 | 31 | /** |
24 | 32 | * Gets an authenticated API client with OIDC access token. |
25 | 33 | * Automatically refreshes the token if expired. |
26 | 34 | * |
| 35 | + * Creates a new client instance per request to avoid race conditions |
| 36 | + * when handling multiple concurrent requests with different tokens. |
| 37 | + * |
27 | 38 | * Use this in server actions and server components to make authenticated API calls. |
28 | 39 | * |
29 | 40 | * @param accessToken - Optional access token to use instead of fetching from session |
@@ -63,13 +74,15 @@ export async function getAuthenticatedClient(accessToken?: string) { |
63 | 74 | } |
64 | 75 | } |
65 | 76 |
|
66 | | - // Configure client with authentication |
67 | | - client.setConfig({ |
68 | | - baseUrl: process.env.API_BASE_URL || "", |
69 | | - headers: { |
70 | | - Authorization: `Bearer ${accessToken}`, |
71 | | - }, |
72 | | - }); |
| 77 | + // Create a new client instance per request to avoid race conditions |
| 78 | + const authenticatedClient = createClient( |
| 79 | + createConfig({ |
| 80 | + baseUrl: API_BASE_URL, |
| 81 | + headers: { |
| 82 | + Authorization: `Bearer ${accessToken}`, |
| 83 | + }, |
| 84 | + }), |
| 85 | + ); |
73 | 86 |
|
74 | | - return { ...apiServices, client }; |
| 87 | + return { ...apiServices, client: authenticatedClient }; |
75 | 88 | } |
0 commit comments