main.tsx 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import { trpc } from "@/lib/trpc";
  2. import { UNAUTHED_ERR_MSG } from '@shared/const';
  3. import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
  4. import { httpBatchLink, TRPCClientError } from "@trpc/client";
  5. import { createRoot } from "react-dom/client";
  6. import superjson from "superjson";
  7. import App from "./App";
  8. import { getLoginUrl } from "./const";
  9. import "./index.css";
  10. const queryClient = new QueryClient();
  11. const redirectToLoginIfUnauthorized = (error: unknown) => {
  12. if (!(error instanceof TRPCClientError)) return;
  13. if (typeof window === "undefined") return;
  14. const isUnauthorized = error.message === UNAUTHED_ERR_MSG;
  15. if (!isUnauthorized) return;
  16. // Redirect to our custom login page instead of OAuth
  17. const currentPath = window.location.pathname;
  18. window.location.href = `${import.meta.env.BASE_URL}login?returnTo=${encodeURIComponent(currentPath)}`;
  19. };
  20. queryClient.getQueryCache().subscribe(event => {
  21. if (event.type === "updated" && event.action.type === "error") {
  22. const error = event.query.state.error;
  23. redirectToLoginIfUnauthorized(error);
  24. console.error("[API Query Error]", error);
  25. }
  26. });
  27. queryClient.getMutationCache().subscribe(event => {
  28. if (event.type === "updated" && event.action.type === "error") {
  29. const error = event.mutation.state.error;
  30. redirectToLoginIfUnauthorized(error);
  31. console.error("[API Mutation Error]", error);
  32. }
  33. });
  34. const trpcClient = trpc.createClient({
  35. links: [
  36. httpBatchLink({
  37. url: `${import.meta.env.BASE_URL}api/trpc`,
  38. transformer: superjson,
  39. fetch(input, init) {
  40. return globalThis.fetch(input, {
  41. ...(init ?? {}),
  42. credentials: "include",
  43. });
  44. },
  45. }),
  46. ],
  47. });
  48. createRoot(document.getElementById("root")!).render(
  49. <trpc.Provider client={trpcClient} queryClient={queryClient}>
  50. <QueryClientProvider client={queryClient}>
  51. <App />
  52. </QueryClientProvider>
  53. </trpc.Provider>
  54. );