feat: expo getCookie helper

This commit is contained in:
Bereket Engida
2024-11-15 14:44:48 +03:00
parent 958befd841
commit 4e1ed7c65b
2 changed files with 40 additions and 25 deletions

View File

@@ -295,24 +295,16 @@ $fetch('/api/secure-endpoint', {
#### Option 2: Adding the Cookie to Request Headers
If you prefer using your own fetch client, you can retrieve the session cookie stored in `SecureStore` and add it to your request headers manually.
By default, the cookie is stored in `SecureStore` with the key `better-auth_cookie`. You can change this key by setting a custom `storagePrefix` in the client configuration. If you do, ensure you retrieve the cookie using the new prefix (e.g., `myapp_cookie`).
If you prefer using your own fetch client, you can retrieve the session cookie stored in the device using `authClient.getCookie` and manually add it to your request headers.
```tsx
import * as SecureStore from 'expo-secure-store';
const getCookies = async () => {
const cookieName = 'better-auth_cookie'; // Update if using a custom prefix
return await SecureStore.getItemAsync(cookieName);
};
import { authClient } from '@/lib/auth-client';
const makeAuthenticatedRequest = async () => {
const cookies = await getCookies();
const cookies = authClient.getCookie(); // [!code highlight]
const headers = {
'Cookie': cookies,
'Cookie': cookies, // [!code highlight]
};
const response = await fetch('http://localhost:8081/api/secure-endpoint', { headers });
const data = await response.json();
return data;
@@ -322,7 +314,9 @@ const makeAuthenticatedRequest = async () => {
**Exampe: Usage With TRPC**
```tsx title="lib/trpc-provider.tsx"
import { createTRPCReact } from "@trpc/react-query";
//...other imports
import { authClient } from "@/lib/auth-client"; // [!code highlight]
export const api = createTRPCReact<AppRouter>();
export function TRPCProvider(props: { children: React.ReactNode }) {
@@ -334,7 +328,7 @@ export function TRPCProvider(props: { children: React.ReactNode }) {
//...your other options
headers() {
const headers = new Map<string, string>(); // [!code highlight]
const cookies = SecureStore.getItemAsync ("better-auth_cookie"); // [!code highlight]
const cookies = authClient.getCookie(); // [!code highlight]
if (cookies) { // [!code highlight]
headers.set("Cookie", cookies); // [!code highlight]
} // [!code highlight]

View File

@@ -71,7 +71,7 @@ function getSetCookie(header: string) {
return JSON.stringify(toSetCookie);
}
function getCookie(cookie: string) {
export function getCookie(cookie: string) {
let parsed = {} as Record<string, StoredCookie>;
try {
parsed = JSON.parse(cookie) as Record<string, StoredCookie>;
@@ -105,16 +105,37 @@ export const expoClient = (opts?: ExpoClientOptions) => {
return {
id: "expo",
getActions(_, $store) {
if (Platform.OS === "web") return {};
store = $store;
const localSession = storage.getItem(cookieName);
localSession &&
$store.atoms.session.set({
data: JSON.parse(localSession),
error: null,
isPending: false,
});
return {};
if (Platform.OS !== "web") {
store = $store;
const localSession = storage.getItem(cookieName);
localSession &&
$store.atoms.session.set({
data: JSON.parse(localSession),
error: null,
isPending: false,
});
}
return {
/**
* Get the stored cookie.
*
* You can use this to get the cookie stored in the device and use it in your fetch
* requests.
*
* @example
* ```ts
* const cookie = client.getCookie();
* fetch("https://api.example.com", {
* headers: {
* cookie,
* },
* });
*/
getCookie: () => {
const cookie = storage.getItem(cookieName);
return getCookie(cookie || "{}");
},
};
},
fetchPlugins: [
{