Improve user session handling in middleware

The changes add user session handling directly in the middleware. This ensures the user data is fetched at the start of a request and then passed on to route handlers, reducing repeated data fetching. Also, these improvements include adjustments for how sign-out and auth-change events are managed, particularly when the user session state changes. Additionally, it corrects the error response from useUser hook to return `undefined` instead of `null`.
This commit is contained in:
giancarlo
2024-04-28 13:20:25 +07:00
parent 3efbf6029f
commit 51a90bde83
4 changed files with 31 additions and 11 deletions

View File

@@ -34,7 +34,7 @@ export function useAuthChangeListener({
useEffect(() => {
// keep this running for the whole session unless the component was unmounted
const listener = client.auth.onAuthStateChange((_, user) => {
const listener = client.auth.onAuthStateChange((event, user) => {
// log user out if user is falsy
// and if the current path is a private route
const shouldRedirectUser =
@@ -47,6 +47,10 @@ export function useAuthChangeListener({
return;
}
if (event === 'SIGNED_OUT') {
return router.refresh();
}
if (accessToken) {
const isOutOfSync = user?.access_token !== accessToken;

View File

@@ -1,15 +1,13 @@
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { useMutation } from '@tanstack/react-query';
import { useSupabase } from './use-supabase';
export function useSignOut() {
const client = useSupabase();
const queryClient = useQueryClient();
return useMutation({
mutationFn: async () => {
await client.auth.signOut();
await queryClient.invalidateQueries();
},
});
}

View File

@@ -14,7 +14,7 @@ export function useUser(initialData?: User | null) {
// this is most likely a session error or the user is not logged in
if (response.error) {
return null;
return undefined;
}
if (response.data?.user) {
@@ -28,6 +28,7 @@ export function useUser(initialData?: User | null) {
queryFn,
queryKey,
initialData,
refetchOnMount: false,
refetchOnWindowFocus: false,
});
}