Skip to content

Commit 04656fc

Browse files
committed
fix: api-client new instance
1 parent c3a228a commit 04656fc

File tree

1 file changed

+22
-9
lines changed

1 file changed

+22
-9
lines changed

src/lib/api-client.ts

Lines changed: 22 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -15,15 +15,26 @@
1515

1616
import { headers as nextHeaders } from "next/headers";
1717
import { redirect } from "next/navigation";
18-
import { client } from "@/generated/client.gen";
18+
import { createClient, createConfig } from "@/generated/client";
1919
import * as apiServices from "@/generated/sdk.gen";
2020
import { auth } from "./auth/auth";
2121
import { getValidOidcToken } from "./auth/token";
2222

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+
2331
/**
2432
* Gets an authenticated API client with OIDC access token.
2533
* Automatically refreshes the token if expired.
2634
*
35+
* Creates a new client instance per request to avoid race conditions
36+
* when handling multiple concurrent requests with different tokens.
37+
*
2738
* Use this in server actions and server components to make authenticated API calls.
2839
*
2940
* @param accessToken - Optional access token to use instead of fetching from session
@@ -63,13 +74,15 @@ export async function getAuthenticatedClient(accessToken?: string) {
6374
}
6475
}
6576

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+
);
7386

74-
return { ...apiServices, client };
87+
return { ...apiServices, client: authenticatedClient };
7588
}

0 commit comments

Comments
 (0)