Where would I initialize a 3rd party API to use in TRPC routes?

I am currently initializing this client in server/client.ts similar to the global definition of prisma. I then import
client
in my TRPC router. Does this make sense or would it be smarter to do that somewhere else.

interface Client {
  $ad: typeof api.$ad;
  $ads: api.Ads;
  $geo: api.Geo;
}

const globalForClient = globalThis as unknown as {
  immoledo: Client | undefined;
  abortController: AbortController | undefined;
};

const initClient = async () => {
  if (globalForClient.abortController) {
    globalForClient.abortController.abort();
  }

  globalForClient.abortController = new AbortController();
  const { signal } = globalForClient.abortController;

  api.init(env.API_URL);

  api.$global.net.errors.onUnauthorized = () =>
    console.warn("Client unauthorized");

  try {
    const success = await api.$anonymousUser.profile.login(
      env.API_CLIENT_ID,
      env.API_CLIENT_SECRET,
      true,
      signal
    );
    console.log(`🏠 Client login ${success ? "✅" : "❌"}`);
  } catch (error) {
    console.error("🏚️ Client login error:\n", error);
  }

  return api;
};

export const client = await initClient();


Best reards and thank you in advance 🙂
Was this page helpful?