fix: use expoClient getCookie() for API requests per Better Auth docs
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -1,32 +1,29 @@
|
||||
import * as SecureStore from "expo-secure-store";
|
||||
import { router } from "expo-router";
|
||||
import { env } from "@haushaltsApp/env/native";
|
||||
import { useAuthStore } from "../stores/auth.store";
|
||||
import { authClient } from "./auth-client";
|
||||
|
||||
const BASE_URL = env.EXPO_PUBLIC_SERVER_URL;
|
||||
// expoClient plugin stores session token under "<storagePrefix>.session_token"
|
||||
const TOKEN_KEY = "haushaltsapp.session_token";
|
||||
|
||||
export async function apiRequest<T>(
|
||||
path: string,
|
||||
options: RequestInit = {},
|
||||
): Promise<T> {
|
||||
const householdId = useAuthStore.getState().activeHouseholdId;
|
||||
const token = await SecureStore.getItemAsync(TOKEN_KEY);
|
||||
const cookies = authClient.getCookie();
|
||||
|
||||
const response = await fetch(`${BASE_URL}${path}`, {
|
||||
...options,
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
...(token ? { Authorization: `Bearer ${token}` } : {}),
|
||||
...(cookies ? { Cookie: cookies } : {}),
|
||||
...(householdId ? { "x-household-id": householdId } : {}),
|
||||
...options.headers,
|
||||
},
|
||||
credentials: "include",
|
||||
credentials: "omit",
|
||||
});
|
||||
|
||||
if (response.status === 401) {
|
||||
await SecureStore.deleteItemAsync(TOKEN_KEY);
|
||||
useAuthStore.getState().clearSession();
|
||||
router.replace("/(auth)/login");
|
||||
throw new Error("Unauthorized");
|
||||
|
||||
@@ -4,23 +4,8 @@ import { expoClient } from "@better-auth/expo/client";
|
||||
import * as SecureStore from "expo-secure-store";
|
||||
import { env } from "@haushaltsApp/env/native";
|
||||
|
||||
// expoClient plugin stores session token under "<storagePrefix>.session_token"
|
||||
const TOKEN_KEY = "haushaltsapp.session_token";
|
||||
|
||||
export const authClient = createAuthClient({
|
||||
baseURL: env.EXPO_PUBLIC_SERVER_URL,
|
||||
fetchOptions: {
|
||||
onSuccess: (ctx) => {
|
||||
const token = ctx.response.headers.get("set-auth-token");
|
||||
if (token) {
|
||||
SecureStore.setItemAsync(TOKEN_KEY, token);
|
||||
}
|
||||
},
|
||||
auth: {
|
||||
type: "Bearer",
|
||||
token: async () => (await SecureStore.getItemAsync(TOKEN_KEY)) ?? "",
|
||||
},
|
||||
},
|
||||
plugins: [
|
||||
expoClient({
|
||||
scheme: "haushaltsApp",
|
||||
|
||||
Reference in New Issue
Block a user