manchenkoff / nuxt-auth-sanctum

Nuxt module for Laravel Sanctum authentication
https://manchenkoff.gitbook.io/nuxt-auth-sanctum/
MIT License
153 stars 18 forks source link

User is requested on every page #69

Closed iamlasse closed 5 months ago

iamlasse commented 5 months ago

When not authenticated the user path is still being requested on every page load in the nuxt app. Is there a way to only fetch the user when explicitly calling the usesanctumuser() ?

manchenkoff commented 5 months ago

Hey @iamlasse, it is done like that because of the middleware. The reason is to refresh the user when it was logged out on the backend side but frontend still has it in memory. It allows us to redirect users to the login page even if they keep the tab open for hours or days without refreshing.

manchenkoff commented 5 months ago

Hmm, I think I'm wrong actually 😄 I've just checked how navigation works and there is just one request on the initial page load, once I go to another page it doesn't request it from the API, so only complete refreshing triggers the request.

In your case, the request is triggered by plugin initialization on both SSR / CSR sides if there is no user, we are not sure if it is because we have no cookies or it is unauthenticated, so we have to propagate it to validate later in the middleware. Still, it should happen only once.

Feel free to propose an alternative solution

manchenkoff commented 5 months ago

In the meantime I realized that there was another bug, you can find more details in #70, you can also try to upgrade to version 0.2.1, maybe your issue was related to that.

iamlasse commented 5 months ago

I think, it should only request the user if the page requires a user, eg, authenticated pages, and not on every page.

manchenkoff commented 5 months ago

I think, it should only request the user if the page requires a user, eg, authenticated pages, and not on every page.

It doesn't work like that because there is no way (afaik) to check if we need a user for the specific page or not.

Yes, we can check it in the middleware since we have access to the requested page meta, but in other cases when page doesn't have any middleware (e.g. available for both states but with additional content for authenticated users) we will lose functionality since any Vue component might use useSanctumUser or useSanctumClient in nested levels and we must initialize user before that call.

If you have ideas regarding how we can check it for sure and initialize the user on demand after plugin initialization, feel free to share.

Anyway, as I mentioned previously, that happens only in SSR mode and does not affect navigation on the website since user is requested once.

manchenkoff commented 5 months ago

Closed due to inactivity, to reduce the amount of requests #77 was introduced