1- import { useFetch , createError } from '#app'
1+ import { useFetch , createError , useRequestHeaders , useNuxtApp , useRuntimeConfig } from '#app'
22import { nanoid } from 'nanoid'
33import { Ref , ref } from 'vue'
44import type { Session , SupportedSessionApiMethods } from '../../types'
5- import { useRuntimeConfig } from '#imports'
65
76type SessionData = Record < string , any >
87
8+ // Key for the session value in the nuxt payload
9+ const SESSION_VALUE_KEY = 'nuxt-session:session-value'
10+
911declare interface ComposableOptions {
1012 fetchSessionOnInitialization : boolean
1113}
@@ -26,15 +28,19 @@ export default async (options: ComposableOptions = {
2628 throw createError ( { message, statusCode : 500 } )
2729 }
2830
31+ const nuxt = useNuxtApp ( )
32+
2933 // Return the fetch so that it is executed in the component context + to allow further introspection by the user if desired
3034 return useFetch ( config . api . basePath , {
35+ // Pass the cookie from the current request to the session-api
36+ headers : {
37+ cookie : useRequestHeaders ( [ 'cookie' ] ) . cookie ?? ''
38+ } ,
39+
3140 // Method must be capitalized for HTTP-request to work
3241 method : method . toUpperCase ( ) ,
3342 body,
3443
35- // Do not fetch on server, as the cookie is stored and sent by the client
36- server : false ,
37-
3844 // Never cache
3945 key : nanoid ( ) ,
4046
@@ -43,6 +49,12 @@ export default async (options: ComposableOptions = {
4349 const data = response . _data
4450
4551 session . value = data
52+
53+ // If we are on the server, store session value in nuxt payload to avoid hydration issues
54+ if ( process . server ) {
55+ nuxt . payload . state [ SESSION_VALUE_KEY ] = data
56+ }
57+
4658 return data
4759 }
4860 } )
@@ -75,7 +87,13 @@ export default async (options: ComposableOptions = {
7587
7688 // Initialize session object
7789 if ( options . fetchSessionOnInitialization ) {
78- await refresh ( )
90+ const nuxt = useNuxtApp ( )
91+
92+ if ( nuxt . isHydrating ) {
93+ session . value = nuxt . payload . state [ SESSION_VALUE_KEY ]
94+ } else {
95+ await refresh ( )
96+ }
7997 }
8098
8199 return {
0 commit comments