supabase icon indicating copy to clipboard operation
supabase copied to clipboard

Auth middleware example from docs does not work

Open StefanVDWeide opened this issue 3 years ago • 22 comments

Version

@nuxtjs/supabase: 0.3.0 nuxt: 3.0.0

Steps to reproduce

Create an auth.ts file in the middleware folder as described here: https://supabase.nuxtjs.org/usage/composables/use-supabase-user#auth-middleware

What is Expected?

For a user to be redirected to the correct page after logging in.

What is actually happening?

When a user logs in, no redirect happens because the user object doesn't exist when using theuseSupabaseUser() in the auth.ts file. This means the check is is always false and the user is redirect to the /login page.

StefanVDWeide avatar Dec 10 '22 22:12 StefanVDWeide

We're running into problems with this too having updated to supabase v2.

Previously when using supabase v1 our middleware worked as per the example in docs. However having upgraded to supabase v2 If we log the value from useSupabaseUser() we can see it is as expected in the terminal logs / SSR but on the client it's logged as undefined?

For further context - I've noticed if I switch to a different browser tab and back useSupabaseUser() then becomes populated with the expected data

timdiacon avatar Dec 14 '22 20:12 timdiacon

I noticed that when we call the supabase login function it creates a session in the local storage and only after a lot of time it creates the cookie session and the the user object gets populated.

deixadilson avatar Dec 18 '22 19:12 deixadilson

I can not reproduce in local. On which platform are you experiencing this ? Can you please create a reproduction ?

larbish avatar Dec 30 '22 14:12 larbish

Mine is hosted on netlify https://stalwart-marshmallow-429f9d.netlify.app/

This is the repository: https://github.com/JeffValadares/CoEnergie

deixadilson avatar Dec 31 '22 00:12 deixadilson

Closing in favor of #101

larbish avatar Dec 31 '22 20:12 larbish

This also happens on my localhost.

The session is set only in local storage and the user is not redirected. Only after a long wait the session is stored in the cookie and then the user is redirected.

On netlify the user s never redirected.

deixadilson avatar Jan 01 '23 16:01 deixadilson

I am facing a similar issue even on local development, when I signing with a password and am redirected to the auth page, the user cookies are not set, till I switched to another tab and come back

Here is how I am login in

async function loginUser() {
  try {
    await auth.signInWithPassword({
      email: email.value,
      password: password.value,
    });
    return navigateTo("/dashboard");
  } catch (error) {
    console.log({ error });
  }
}

Aybee5 avatar Jan 01 '23 20:01 Aybee5

I fixed it by using useSupabaseAuthClient() instead of useSupabaseClient() to sign in and out.

Wafje avatar Jan 03 '23 18:01 Wafje

Wow it works, but that's strange, I also looked inside the package and saw the implementation should work correctly but since it's not working I thought something must be causing that.

If we are not supposed to use the useSupabaseClient, then I believe it should be communicated or the auth inside should be removed for the v2

On Tue, 3 Jan 2023, 7:27 pm Sander Lesage, @.***> wrote:

I fixed it by using useSupabaseAuthClient() instead of useSupabaseClient() to sign in and out.

— Reply to this email directly, view it on GitHub https://github.com/nuxt-modules/supabase/issues/129#issuecomment-1370092115, or unsubscribe https://github.com/notifications/unsubscribe-auth/AKBGJOCG7PQDQ6N7Q6DPXQDWQRVP5ANCNFSM6AAAAAAS2QZJZA . You are receiving this because you commented.Message ID: @.***>

Aybee5 avatar Jan 03 '23 20:01 Aybee5

I fixed it by using useSupabaseAuthClient() instead of useSupabaseClient() to sign in and out.

It works! Thank you!

deixadilson avatar Jan 04 '23 13:01 deixadilson

Strangly enough this does not solve the issue for me locally. I tried creating a minimal example but you can't really do this without running Supabase itself, otherwise there is nothing to login to.

My setup is really simple and I fail to see what it incorrect. My login component looks like:

const authClient = useSupabaseAuthClient();
const router = useRouter();

// Local state
const userEmailLogin = ref("");
const userPasswordLogin = ref("");

// Methods
// Login method using email
const login = async () => {
    const { error } = await authClient.auth.signInWithPassword({
        email: userEmailLogin.value,
        password: userPasswordLogin.value
    })
    if (error) {
        return alert('Something went wrong during login!')
    }
    router.push("/dashboard");
}

And the middleware file is exactly the same as in the official example in the docs:

export default defineNuxtRouteMiddleware((_to, _from) => {
    const user = useSupabaseUser();

    if (!user.value) {
        return navigateTo("/login");
    }
})

I don't think we should close this issue just yet. Any ideas what this could be?

Thanks!

StefanVDWeide avatar Jan 04 '23 16:01 StefanVDWeide

Use useSupabaseAuthClient fix the problem but one more problem that when I refresh the page useSupabaseUser() return null

const user = useSupabaseUser()
console.log(user.value) // returns null

tungquach avatar Jan 04 '23 16:01 tungquach

@StefanVDWeide

can you try this instead of router.push?

const user = useSupabaseUser();
watchEffect(async () => {
  if (user.value) {
    navigateTo("/dashboard");
  }
});

That is how it is working on my end.

Wafje avatar Jan 04 '23 18:01 Wafje

Same here, I'm using the useSupabaseAuthClient to login and logout, and it works locally. But on Netlify it doesn't.

ahku avatar Jan 06 '23 11:01 ahku

You can try to set the cookie manually with the code below:

      const { data: response, error } = await supabase.auth.signInWithPassword(formData);
      const accessToken = useCookie('sb-access-token');
      const refreshToken = useCookie('sb-refresh-token');
      accessToken.value = response.session?.access_token ?? null;
      refreshToken.value = response.session?.refresh_token ?? null;

deixadilson avatar Jan 06 '23 12:01 deixadilson

https://github.com/brandondtaylor01/nuxt3-supabase-bad-sessions Here's a small repo that I created demoing the issue that I am seeing. Several weird things happening:

  1. sb-access and sb-refresh aren't created until the window is minimized / tabbed out and back in.
  2. auth.ts middleware doesn't know about the user after successful signin (the SIGNED_IN event has fired, and only then navigation occurs)
  3. Signing out via the signOut method does not remove the sb-access and sb-refresh cookies. This causes the middleware to "remember" the user, despite not being currently signed in, and the local storage is cleared. Deleting these cookies manually fixes that.

I would love to have a solution to this. At this point, I suppose I'll just use useSupabaseAuthClient

BrandonTaylorDev avatar Jan 10 '23 05:01 BrandonTaylorDev

@brandondtaylor01 For authentification purpose (client.auth methods) , you should use the useSupabaseAuthClient. Then you can fetch your data with the useSupabaseClient.

larbish avatar Jan 10 '23 08:01 larbish

@brandondtaylor01 For authentification purpose (client.auth methods) , you should use the useSupabaseAuthClient. Then you can fetch your data with the useSupabaseClient.

I did also notice that, even when using that composable, the middleware still did not receive the data of the user until those cookies were created. And that still required a tab-out and tab-in to accomplish. I managed to get it to work by altering the middleware to this:

export default defineNuxtRouteMiddleware(async (to) => {
  const client = useSupabaseAuthClient();

  if(!(await client.auth.getUser()).data.user) {
    return navigateTo('/sign-in/');
  }

  // no need to redirect, continue.
  // ...
});

It may not be optimal, but it works.

BrandonTaylorDev avatar Jan 10 '23 12:01 BrandonTaylorDev

I am also experiencing this issue. It does not occur when testing locally, only when hosted on Vercel.

KeoneSomers avatar Jan 11 '23 09:01 KeoneSomers

Just to add we're also experiencing no problems locally but useSupabaseUser is null when deployed both on Netlify and Vercel

timdiacon avatar Jan 16 '23 21:01 timdiacon