Theo's Typesafe CultTTC
Theo's Typesafe Cult3y ago
3 replies
Sz

Adding Custom Headers in trpc using local storage

Hey all, I'm trying to get add custom headers on the client side api of trpc, but have been struggling to do so.

Right now the setup currently looks like this

export function TRPCReactProvider(props: {
  children: React.ReactNode;
  cookies: string;
}) {
  const [queryClient] = useState(() => new QueryClient());
  const [header, setHeader] = useState<string>("");
  console.log("trpc react => api key: ", apiKey);

  const [trpcClient] = useState(() =>
    api.createClient({
      transformer,
      links: [
        loggerLink({
          enabled: (op) =>
            process.env.NODE_ENV === "development" ||
            (op.direction === "down" && op.result instanceof Error),
        }),
        unstable_httpBatchStreamLink({
          url: getUrl(),
          headers() {
            return {
              cookie: props.cookies,
              "x-trpc-source": "react",
              "x-header-key": header,
            };
          },
        }),
      ],
    })
  );

  useEffect(() => {
    setHeader(localStorage.getItem("header-item"));

    const fetchHeaderItem = () => {
      setApiKey(localStorage.getItem("header-item"));
    }

    window.addEventListener("header-item-storage-event", fetchHeaderItem);

    return () => {
      window.removeEventListener("header-item-storage-event", fetchHeaderItem);
    }
  }, []);


This doesn't work since the trpcClient gets initialized before the header does in useEffect and there doesn't seem to be a way to update the headers via the trpcClient.

Any advice would be apprecited!
Was this page helpful?