'In NextJs, After logout, when I open dashboard direct url it open and after checking auth it redirect to login page very slow?

Please help me for next.js authorization with best practice.

In Next.Js, After logout, when I open dashboard direct url it open and after checking auth it redirect to login page very slow?

watch the video , what exactly the issue is this.

File => hooks/auth.js

import useSWR from 'swr'
import axios from '@/lib/axios'
import { useEffect } from 'react'
import { useRouter } from 'next/router'

export const useAuth = ({ middleware, redirectIfAuthenticated } = {}) => {
    const router = useRouter()

    const { data: user, error, revalidate } = useSWR('/api/user', () =>
        axios
            .get('/api/user')
            .then(res => res.data)
            .catch(error => {
                if (error.response.status != 409) throw error

                router.push('/verify-email')
            }),
    )

    const csrf = () => axios.get('/sanctum/csrf-cookie')

    const register = async ({ setErrors, ...props }) => {
        await csrf()

        setErrors([])

        axios
            .post('/register', props)
            .then(() => revalidate())
            .catch(error => {
                if (error.response.status != 422) throw error

                setErrors(Object.values(error.response.data.errors).flat())
            })
    }

    const login = async ({ setErrors, setStatus, ...props }) => {
        await csrf()

        setErrors([])
        setStatus(null)

        axios
            .post('/login', props)
            .then(() => revalidate())
            .catch(error => {
                if (error.response.status != 422) throw error

                setErrors(Object.values(error.response.data.errors).flat())
            })
    }
       

    const logout = async () => {
        if (! error) {
            await axios.post('/logout')

            revalidate()
        }

        window.location.pathname = '/login'
    }

    useEffect(() => {
        if (middleware == 'guest' && redirectIfAuthenticated && user) router.push(redirectIfAuthenticated)
        if (middleware == 'auth' && error) logout()
    }, [user, error])

    return {
        user,
        register,
        login,
        logout,
    }
}

you can watch this issue what exactly it is click here



Solution 1:[1]

I guess you are checking the logic in component, thats why you see dashboard page and then redirecting to login. Checking the logic can take some time until redirect is processing. In my case i have done in different way.

Create a hoc ( High Order Component ) with 2 functions and wrap pages to this hoc's depends what you want.

import { useRouter } from 'next/router';
import { getCookieByName } from '@/utils/cookie.utils';

export const accessDeniedWithToken = (WrappedComponent) => {
  return (props) => {
    if (typeof window !== 'undefined') {
      const router = useRouter();

      const token = getCookieByName('auth-token');
      const user = token ? JSON.parse(token) : {};

      if (user.accessToken) {
        router.replace('/');
        return null;
      }
      return <WrappedComponent {...props} />;
    }
    return null;
  };
};

export const allowedOnlyWithToken = (WrappedComponent) => {
  return (props) => {
    if (typeof window !== 'undefined') {
      const router = useRouter();

      const token = getCookieByName('auth-token');
      const user = token ? JSON.parse(token) : {};

      if (!user.accessToken) {
        router.replace('/auth/login');
        return null;
      }
      return <WrappedComponent {...props} />;
    }
    return null;
  };
};

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1