useNuxtApp in composables
According to the documentation this logic sounds like a composable , but it uses useNuxtApp()
const { $supabase } = useNuxtApp()
export const signIn = async () => {
const { data, error } = await $supabase.auth.signInWithOAuth({
provider: 'github'
})
if (error) {
console.error('Login error:', error);
}else{
return data;
}
}
So I will get the nuxt 500 error:
A composable that requires access to the Nuxt instance was called outside of a plugin, Nuxt hook, Nuxt middleware, or Vue setup function. This is probably not a Nuxt bug.Does anyone know how should I structure this kind of authentication logic?
2 Replies
useNuxtApp()
is a composable and must be called in the nuxt contextyour error is that you are trying to declare const { $supabase } = useNuxtApp()
outside the function, this causes it to try to declare $supabase when the file is read, but you must declare it when it is used, as in this example:
export const signIn = async () => {
const { $supabase } = useNuxtApp();
const { data, error } = await $supabase.auth.signInWithOAuth({
provider: 'github'
})
if (error) {
console.error('Login error:', error);
}else{
return data;
}
}