Skip to content

Commit feda2a4

Browse files
authored
feat: add proxyCookies option for _fetch (#1041)
1 parent 45fd69c commit feda2a4

File tree

2 files changed

+38
-6
lines changed

2 files changed

+38
-6
lines changed

src/runtime/composables/local/useAuth.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ import { formatToken } from './utils/token'
1010
import { useAuthState } from './useAuthState'
1111
// @ts-expect-error - #auth not defined
1212
import type { SessionData } from '#auth'
13-
import { navigateTo, nextTick, useNuxtApp, useRequestHeaders, useRoute, useRuntimeConfig } from '#imports'
13+
import { navigateTo, nextTick, useNuxtApp, useRoute, useRuntimeConfig } from '#imports'
1414

1515
interface Credentials extends Record<string, any> {
1616
username?: string
@@ -180,14 +180,14 @@ export function useAuth(): UseAuthReturn {
180180
return
181181
}
182182

183-
const headers = new Headers(useRequestHeaders(['cookie']))
183+
const headers = new Headers()
184184
if (tokenValue) {
185185
headers.append(config.token.headerName, tokenValue)
186186
}
187187

188188
loading.value = true
189189
try {
190-
const result = await _fetch<any>(nuxt, path, { method, headers })
190+
const result = await _fetch<any>(nuxt, path, { method, headers }, true)
191191
const { dataResponsePointer: sessionDataResponsePointer } = config.session
192192
data.value = jsonPointerGet<SessionData>(result, sessionDataResponsePointer)
193193
}

src/runtime/utils/fetch.ts

Lines changed: 35 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,16 @@
11
import { resolveApiUrlPath } from './url'
22
import { ERROR_PREFIX } from './logger'
3-
import { useRuntimeConfig } from '#imports'
3+
import { useRequestEvent, useRuntimeConfig } from '#imports'
44
import type { useNuxtApp } from '#imports'
55
import { callWithNuxt } from '#app/nuxt'
6+
import type { H3Event } from 'h3'
67

7-
export async function _fetch<T>(nuxt: ReturnType<typeof useNuxtApp>, path: string, fetchOptions?: Parameters<typeof $fetch>[1]): Promise<T> {
8+
export async function _fetch<T>(
9+
nuxt: ReturnType<typeof useNuxtApp>,
10+
path: string,
11+
fetchOptions?: Parameters<typeof $fetch>[1],
12+
proxyCookies = false
13+
): Promise<T> {
814
// This fixes https://github.com/sidebase/nuxt-auth/issues/927
915
const runtimeConfigOrPromise = callWithNuxt(nuxt, useRuntimeConfig)
1016
const runtimeConfig = 'public' in runtimeConfigOrPromise
@@ -22,8 +28,34 @@ export async function _fetch<T>(nuxt: ReturnType<typeof useNuxtApp>, path: strin
2228
}
2329
}
2430

31+
// Add browser cookies to the request on server when `proxyCookies` param is set
32+
let event: H3Event | undefined
33+
if (import.meta.server && proxyCookies) {
34+
const fetchOptionsHeaders = new Headers(fetchOptions?.headers ?? {})
35+
36+
event = await callWithNuxt(nuxt, useRequestEvent)
37+
38+
// Only set when headers were not set already
39+
if (event && fetchOptionsHeaders.get('cookie') === null) {
40+
const cookies = event.node.req.headers.cookie
41+
if (cookies) {
42+
fetchOptionsHeaders.set('cookie', cookies)
43+
fetchOptions ??= {}
44+
fetchOptions.headers = fetchOptionsHeaders
45+
}
46+
}
47+
}
48+
2549
try {
26-
return $fetch(joinedPath, fetchOptions)
50+
// Adapted from https://nuxt.com/docs/getting-started/data-fetching#pass-cookies-from-server-side-api-calls-on-ssr-response
51+
const res = await $fetch.raw(joinedPath, fetchOptions)
52+
53+
if (import.meta.server && proxyCookies && event) {
54+
const cookies = res.headers.getSetCookie()
55+
event.node.res.appendHeader('set-cookie', cookies)
56+
}
57+
58+
return res._data as T
2759
}
2860
catch (error) {
2961
let errorMessage = `${ERROR_PREFIX} Error while requesting ${joinedPath}.`

0 commit comments

Comments
 (0)