docs: add note about proxying cookies back to client (#3218)

This commit is contained in:
Daniel Roe 2022-03-03 19:30:01 +00:00 committed by GitHub
parent 66605971a8
commit 8b5e52f2a9
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 33 additions and 5 deletions

View File

@ -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
<script setup lang="ts">
// This composable will automatically pass on a cookie of our choice.
const result = await fetchWithCookie("/api/with-cookie", "test")
onMounted(() => console.log(document.cookie))
</script>
```
## 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.