From eae924e4b4ee40825a5ca40111e6b1fd8c167241 Mon Sep 17 00:00:00 2001 From: Willy Douhard Date: Fri, 10 Jan 2025 11:36:12 +0100 Subject: [PATCH] fix: only use credentials include for chainlit requestsC --- frontend/src/hooks/useFetch.tsx | 43 ++++++++++++++++++++------------- 1 file changed, 26 insertions(+), 17 deletions(-) diff --git a/frontend/src/hooks/useFetch.tsx b/frontend/src/hooks/useFetch.tsx index b07219cfb6..4069323e6f 100644 --- a/frontend/src/hooks/useFetch.tsx +++ b/frontend/src/hooks/useFetch.tsx @@ -1,23 +1,32 @@ +import { useContext } from 'react'; import useSWR, { SWRResponse } from 'swr'; -const fetcher = async (url: string): Promise => { - const response = await fetch(url, { credentials: 'include' }); - - if (!response.ok) { - throw new Error('Network response was not ok'); - } - - // Check if the response is JSON - const contentType = response.headers.get('content-type'); - if (contentType && contentType.includes('application/json')) { - return response.json(); - } else { - // If it's not JSON, return the raw response body - return response.text(); - } -}; +import { ChainlitContext } from '@chainlit/react-client'; + +const fetcher = + (isChainlitRequest: boolean) => + async (url: string): Promise => { + const fetchOptions: RequestInit = { + ...(isChainlitRequest && { credentials: 'include' }) + }; + + const response = await fetch(url, fetchOptions); + + if (!response.ok) { + throw new Error('Network response was not ok'); + } + + const contentType = response.headers.get('content-type'); + return contentType?.includes('application/json') + ? response.json() + : response.text(); + }; const useFetch = (endpoint: string | null): SWRResponse => { - return useSWR(endpoint, fetcher); + const apiClient = useContext(ChainlitContext); + const isChainlitRequest = endpoint?.startsWith(apiClient.httpEndpoint); + + return useSWR(endpoint, fetcher(!!isChainlitRequest)); }; + export { useFetch };