Skip to content
This repository was archived by the owner on Dec 12, 2023. It is now read-only.

Commit 6ce369d

Browse files
feat: Add session to SSR (#73)
Co-authored-by: Zoey <[email protected]>
1 parent 812d44f commit 6ce369d

File tree

1 file changed

+24
-6
lines changed

1 file changed

+24
-6
lines changed

src/runtime/composables/useSession.ts

Lines changed: 24 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,13 @@
1-
import { useFetch, createError } from '#app'
1+
import { useFetch, createError, useRequestHeaders, useNuxtApp, useRuntimeConfig } from '#app'
22
import { nanoid } from 'nanoid'
33
import { Ref, ref } from 'vue'
44
import type { Session, SupportedSessionApiMethods } from '../../types'
5-
import { useRuntimeConfig } from '#imports'
65

76
type 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+
911
declare 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

Comments
 (0)