Added auth interceptor to fetch
Browse filesX-Lovable-Edit-ID: edt-a45f60f0-c32e-4a69-8470-1f2eba431711
src/integrations/supabase/server-fn-fetch.ts
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Attaches the current Supabase access token to every TanStack server-fn request.
|
| 2 |
+
// Server functions are protected by `requireSupabaseAuth`, which expects a
|
| 3 |
+
// `Authorization: Bearer <jwt>` header. The default useServerFn fetch does
|
| 4 |
+
// not forward auth, so we patch window.fetch once on the client.
|
| 5 |
+
import { supabase } from "./client";
|
| 6 |
+
|
| 7 |
+
let installed = false;
|
| 8 |
+
|
| 9 |
+
export function installServerFnAuthFetch() {
|
| 10 |
+
if (installed || typeof window === "undefined") return;
|
| 11 |
+
installed = true;
|
| 12 |
+
|
| 13 |
+
const originalFetch = window.fetch.bind(window);
|
| 14 |
+
|
| 15 |
+
window.fetch = async (input: RequestInfo | URL, init?: RequestInit) => {
|
| 16 |
+
try {
|
| 17 |
+
const url =
|
| 18 |
+
typeof input === "string"
|
| 19 |
+
? input
|
| 20 |
+
: input instanceof URL
|
| 21 |
+
? input.href
|
| 22 |
+
: input.url;
|
| 23 |
+
|
| 24 |
+
if (url && url.includes("/_serverFn/")) {
|
| 25 |
+
const { data } = await supabase.auth.getSession();
|
| 26 |
+
const token = data.session?.access_token;
|
| 27 |
+
if (token) {
|
| 28 |
+
const headers = new Headers(init?.headers ?? (input instanceof Request ? input.headers : undefined));
|
| 29 |
+
if (!headers.has("authorization")) {
|
| 30 |
+
headers.set("authorization", `Bearer ${token}`);
|
| 31 |
+
}
|
| 32 |
+
return originalFetch(input, { ...init, headers });
|
| 33 |
+
}
|
| 34 |
+
}
|
| 35 |
+
} catch {
|
| 36 |
+
// fall through to original fetch
|
| 37 |
+
}
|
| 38 |
+
return originalFetch(input, init);
|
| 39 |
+
};
|
| 40 |
+
}
|
src/routes/__root.tsx
CHANGED
|
@@ -1,6 +1,11 @@
|
|
| 1 |
import { Outlet, Link, createRootRoute, HeadContent, Scripts } from "@tanstack/react-router";
|
| 2 |
import { Toaster } from "@/components/ui/sonner";
|
| 3 |
import appCss from "../styles.css?url";
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
|
| 5 |
function NotFoundComponent() {
|
| 6 |
return (
|
|
|
|
| 1 |
import { Outlet, Link, createRootRoute, HeadContent, Scripts } from "@tanstack/react-router";
|
| 2 |
import { Toaster } from "@/components/ui/sonner";
|
| 3 |
import appCss from "../styles.css?url";
|
| 4 |
+
import { installServerFnAuthFetch } from "@/integrations/supabase/server-fn-fetch";
|
| 5 |
+
|
| 6 |
+
if (typeof window !== "undefined") {
|
| 7 |
+
installServerFnAuthFetch();
|
| 8 |
+
}
|
| 9 |
|
| 10 |
function NotFoundComponent() {
|
| 11 |
return (
|