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

Commit

Permalink
docs(data-fetching): fix and simplify cookie proxy example (#5770)
Browse files Browse the repository at this point in the history
  • Loading branch information
mod7ex committed Aug 15, 2022
1 parent 3920065 commit e2745f6
Showing 1 changed file with 8 additions and 12 deletions.
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

0 comments on commit e2745f6

Please sign in to comment.