diff --git a/docs/content/3.docs/1.usage/1.data-fetching.md b/docs/content/3.docs/1.usage/1.data-fetching.md index 19a8c2c0fa..7fa4b563bd 100644 --- a/docs/content/3.docs/1.usage/1.data-fetching.md +++ b/docs/content/3.docs/1.usage/1.data-fetching.md @@ -165,13 +165,12 @@ watch(posts, (newPosts) => { ## Isomorphic fetch -When we call `fetch` in the browser, user headers like `cookie` will be directly sent to the API. -But during server-side-rendering, since the `fetch` request is originating from the server, it doesn't include the user's browser cookies. +When we call `fetch` in the browser, user headers like `cookie` will be directly sent to the API. But during server-side-rendering, since the `fetch` request takes place 'internally' within the server, it doesn't include the user's browser cookies, nor does it pass on cookies from the fetch response. + +### Example: Bypass API headers to client We can use [`useRequestHeaders`](/docs/usage/ssr) to access and proxy cookies to the API from server-side. -**Example:** - The example below adds the request headers to an isomorphic `fetch` call to ensure that the API endpoint has access to the same `cookie` header originally sent by the user. ```vue @@ -183,8 +182,10 @@ const { data } = useFetch('/api/me', { ``` ::alert{type="warning"} -Be very careful before proxy headers to an external API and include headers that you need. +Be very careful before proxying headers to an external API and just include headers that you need. + Not all headers are safe to be bypassed and might introduce unwanted behavior. + Here is a list of common headers that are NOT to be proxied: * `host`, `accept` @@ -193,6 +194,33 @@ Here is a list of common headers that are NOT to be proxied: * `cf-connecting-ip`, `cf-ray` :: +### Example: Pass on cookies from server-side API calls on SSR response + + If you want to pass on/proxy cookies in the other direction, from an internal request back to the client, you will need to handle this yourself. + +```ts [composables/fetch.ts] +export const fetchWithCookie = async (url: string, cookieName: string) => { + const response = await $fetch.raw(url) + if (process.server) { + const cookies = Object.fromEntries( + response.headers.get('set-cookie')?.split(',').map((a) => a.split('=')) + ) + if (cookieName in cookies) { + useCookie(cookieName).value = cookies[cookieName] + } + } + return response._data +} +``` + +```vue + +``` + ## Best practices The data returned by these composables will be stored inside the page payload. This means that every key returned that is not used in your component will be added to the payload.