11import { resolveApiUrlPath } from './url'
22import { ERROR_PREFIX } from './logger'
3- import { useRuntimeConfig } from '#imports'
3+ import { useRequestEvent , useRuntimeConfig } from '#imports'
44import type { useNuxtApp } from '#imports'
55import { 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