From 95d905b9b1f54a3aa15b3e4e583151cfcf00878f Mon Sep 17 00:00:00 2001 From: Thimo Sietsma Date: Fri, 11 Oct 2024 09:25:28 +0200 Subject: [PATCH] fix(session): ssr getSession warning (#418) --- src/runtime/composables/useSupabaseSession.ts | 2 +- src/runtime/plugins/supabase.server.ts | 15 ++++++++------- .../server/services/serverSupabaseSession.ts | 4 +++- 3 files changed, 12 insertions(+), 9 deletions(-) diff --git a/src/runtime/composables/useSupabaseSession.ts b/src/runtime/composables/useSupabaseSession.ts index b45804b7..19aa3416 100644 --- a/src/runtime/composables/useSupabaseSession.ts +++ b/src/runtime/composables/useSupabaseSession.ts @@ -5,4 +5,4 @@ import { useState, type Ref } from '#imports' * Reactive `Session` state from Supabase. This is initialized in both client and server plugin * and, on the client, also updated through `onAuthStateChange` events. */ -export const useSupabaseSession = (): Ref => useState('supabase_session', () => null) +export const useSupabaseSession = (): Ref | null> => useState | null>('supabase_session', () => null) diff --git a/src/runtime/plugins/supabase.server.ts b/src/runtime/plugins/supabase.server.ts index b987be23..929ab182 100644 --- a/src/runtime/plugins/supabase.server.ts +++ b/src/runtime/plugins/supabase.server.ts @@ -1,6 +1,7 @@ import { createServerClient, parseCookieHeader } from '@supabase/ssr' import { getHeader, setCookie } from 'h3' import { fetchWithRetry } from '../utils/fetch-retry' +import { serverSupabaseUser, serverSupabaseSession } from '../server/services' import { defineNuxtPlugin, useRequestEvent, useRuntimeConfig, useSupabaseSession, useSupabaseUser } from '#imports' import type { CookieOptions } from '#app' @@ -33,13 +34,13 @@ export default defineNuxtPlugin({ // Initialize user and session states const [ - { - data: { session }, - }, - { - data: { user }, - }, - ] = await Promise.all([client.auth.getSession(), client.auth.getUser()]) + session, + user, + ] = await Promise.all([ + serverSupabaseSession(event).catch(() => null), + serverSupabaseUser(event).catch(() => null), + ]) + useSupabaseSession().value = session useSupabaseUser().value = user diff --git a/src/runtime/server/services/serverSupabaseSession.ts b/src/runtime/server/services/serverSupabaseSession.ts index 676dcf65..c2f873eb 100644 --- a/src/runtime/server/services/serverSupabaseSession.ts +++ b/src/runtime/server/services/serverSupabaseSession.ts @@ -3,7 +3,7 @@ import type { H3Event } from 'h3' import { createError } from 'h3' import { serverSupabaseClient } from '../services/serverSupabaseClient' -export const serverSupabaseSession = async (event: H3Event): Promise => { +export const serverSupabaseSession = async (event: H3Event): Promise | null> => { const client = await serverSupabaseClient(event) const { data: { session }, error } = await client.auth.getSession() @@ -11,5 +11,7 @@ export const serverSupabaseSession = async (event: H3Event): Promise