Skip to content

Commit

Permalink
fix(session): server sync
Browse files Browse the repository at this point in the history
  • Loading branch information
larbish committed Mar 29, 2024
1 parent 07eb081 commit 9dee37e
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 6 deletions.
11 changes: 10 additions & 1 deletion playground/pages/protected.vue
Original file line number Diff line number Diff line change
@@ -1,3 +1,12 @@
<template>
<div>This page is protected. You should only be able to access it, if you are logged in.</div>
<div>
<span>This page is protected. You should only be able to access it, if you are logged in:</span>
<pre>
{{ session.access_token }}
</pre>
</div>
</template>

<script setup lang="ts">
const session = useSupabaseSession()
</script>
11 changes: 8 additions & 3 deletions src/runtime/plugins/supabase.client.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
import { createClient } from '@supabase/supabase-js'
import { useSupabaseUser } from '../composables/useSupabaseUser'
import { useSupabaseSession } from '../composables/useSupabaseSession'
import { defineNuxtPlugin, useRuntimeConfig, useCookie } from '#imports'

export default defineNuxtPlugin({
name: 'supabase',
enforce: 'pre',
async setup () {
const user = useSupabaseUser()
const currentSession = useSupabaseSession()
const config = useRuntimeConfig().public.supabase
const { url, key, cookieName, cookieOptions, clientOptions } = config

Expand All @@ -19,10 +21,13 @@ export default defineNuxtPlugin({

// Handle auth event client side
supabaseClient.auth.onAuthStateChange((event, session) => {
// Update user based on received session
// Update states based on received session
if (session) {
if (JSON.stringify(user.value) !== JSON.stringify(session.user)) {
user.value = session.user
if (JSON.stringify(currentSession) !== JSON.stringify(session)) {
currentSession.value = session
if (JSON.stringify(user.value) !== JSON.stringify(session.user)) {
user.value = session.user
}
}
} else {
user.value = null
Expand Down
8 changes: 6 additions & 2 deletions src/runtime/plugins/supabase.server.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { defu } from 'defu'
import { createClient } from '@supabase/supabase-js'
import { useSupabaseUser } from '../composables/useSupabaseUser'
import { useSupabaseSession } from '../composables/useSupabaseSession'
import { defineNuxtPlugin, useRuntimeConfig, useCookie } from '#imports'

export default defineNuxtPlugin({
Expand Down Expand Up @@ -28,8 +29,11 @@ export default defineNuxtPlugin({
refresh_token: refreshToken,
access_token: accessToken
})
if (data?.user) {
useSupabaseUser().value = data.user
if (data) {
useSupabaseSession().value = data.session
if (data?.user) {
useSupabaseUser().value = data.user
}
}
}

Expand Down

0 comments on commit 9dee37e

Please sign in to comment.