Skip to content
This repository has been archived by the owner on Apr 6, 2023. It is now read-only.

docs(data-fetching): fix and simplify cookie proxy example #5770

Merged
merged 3 commits into from
Aug 15, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
20 changes: 8 additions & 12 deletions docs/content/2.guide/2.features/5.data-fetching.md
Original file line number Diff line number Diff line change
Expand Up @@ -212,24 +212,20 @@ Here is a list of common headers that are NOT to be proxied:
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]
}
export const fetchWithCookie = async (url: string) => {
const res = await $fetch.raw(url)
const cookies = (res.headers.get('set-cookie') || '').split(',')
for (const cookie of cookies) {
appendHeader(useRequestEvent(), 'set-cookie', cookie)
}
return response._data
return res._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")
// This composable will automatically pass cookies to the client
const result = await fetchWithCookie("/api/with-cookie")
onMounted(() => console.log(document.cookie))
</script>
```
Expand Down