Skip to content

Instantly share code, notes, and snippets.

@ammuench
Created November 8, 2023 01:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ammuench/b499caf602182559290a26eba9cb3b7a to your computer and use it in GitHub Desktop.
Save ammuench/b499caf602182559290a26eba9cb3b7a to your computer and use it in GitHub Desktop.
Nuxt Supabase Cookie Management Script
<script setup lang="ts">
// Copied from https://github.com/nuxt-modules/supabase/issues/300#issuecomment-1793667652
/**
* Handle Auth Cookies
*/
const supabase = useSupabaseClient()
// get cookie options
const config = useRuntimeConfig().public.supabase;
const { cookieOptions } = config;
const accessToken = useCookie('sb-access-token', {
maxAge: cookieOptions.maxAge,
path: "/",
sameSite: <boolean | "lax" | "strict" | "none" | undefined>cookieOptions.sameSite,
// secure: cookieOptions.secure // if this is enabled it doesn't work anymore
})
const refreshToken = useCookie('sb-refresh-token', {
maxAge: cookieOptions.maxAge,
path: "/",
sameSite: <boolean | "lax" | "strict" | "none" | undefined>cookieOptions.sameSite,
})
// listen for auth changes, set/delete cookies
supabase.auth.onAuthStateChange((event, session) => {
if (event === 'SIGNED_OUT') {
// delete cookies on sign out
accessToken.value = null
refreshToken.value = null
} else if (event === 'SIGNED_IN' || event === 'TOKEN_REFRESHED') {
// set cookies on sign in
accessToken.value = session?.access_token
refreshToken.value = session?.refresh_token
}
})
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment