File size: 1,625 Bytes
fecff63
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import { createTRPCReact, httpBatchLink } from "@trpc/react-query";
import type { inferRouterInputs, inferRouterOutputs } from "@trpc/server";
import type { AppRouter } from "@micprotocol/api";

export const trpc = createTRPCReact<AppRouter>();

export function getTrpcClient() {
  return trpc.createClient({
    links: [
      httpBatchLink({
        url: "/trpc",
        headers() {
          const headers: Record<string, string> = {};
          // Dev-only: bypass auth via x-user-id header when DEV_AUTH_BYPASS_ENABLED=true
          if (process.env.NODE_ENV !== "production") {
            const devUserId =
              typeof localStorage !== "undefined"
                ? localStorage.getItem("micprotocol_admin_user_id")
                : null;
            if (devUserId) headers["x-user-id"] = devUserId;
            const workspaceId =
              typeof localStorage !== "undefined"
                ? localStorage.getItem("micprotocol_admin_workspace_id")
                : null;
            if (workspaceId) headers["x-workspace-id"] = workspaceId;
          }
          if (typeof document !== "undefined") {
            const match = document.cookie
              .split("; ")
              .find((c) => c.startsWith("csrf-token="));
            if (match) headers["x-csrf-token"] = match.split("=")[1];
          }
          return headers;
        },
        fetch(url, options) {
          return fetch(url, { ...options, credentials: "include" });
        },
      }),
    ],
  });
}

export type RouterInputs = inferRouterInputs<AppRouter>;
export type RouterOutputs = inferRouterOutputs<AppRouter>;