Middleware Protected Routes not Detecting Authentication?

13 views Asked by At

My routes in middleware keep redirecting me to the login page despite the user being authenticated. Upon logging in, the user should be redirected to /pages/myprofile. However, it seems that the user is then redirected back to the login page. This also goes for /page/create. Why is the user being redirected back to the login page even after being authenticated?

Middleware.ts



export default withAuth({
    pages: {
      signIn: '/pages/login',
    }
  })

export const config = { 
  matcher: [
    "/pages/create",
    "/pages/myprofile",
  ]
};

Login Page

    const onSubmit = async() => {
        handleUserVisibility()
        if (registerStatus === 'Register') {
            setIsLoading(true);
            try {
                console.log(regData)
                const response = await fetch(`/api/register`,{
                    method: "POST",
                    headers:{
                        "Content-Type":"application/json"
                    },
                    body:JSON.stringify(regData)
                });
                signIn('credentials', regData)

                setIsLoading(false)
                toast.success('Registering you');

                
            } catch(error: any) {
                console.log(error.response.data)
                toast.error(error.response.data)
            }

        } else if (registerStatus ==='Login') {
            
            console.log(logData)
            setIsLoading(true)
            signIn('credentials', {
                ...logData,
                redirect: false
            })
            .then((callback) => {
                if (callback?.error) {
                    toast.error('Invalid credentials');
                }

                if (callback?.ok && !callback?.error) {
                    toast.success('Logged in');
                    console.log(session?.status)
                    window.location.href=`/pages/myprofile`
                }
            })

            .finally(() => setIsLoading(false));
        }

    }
    useEffect(() => {

        console.log(session?.status)

        if (session?.status==='authenticated') {
            console.log('Authenticated')
            window.location.href=`/pages/myprofile`
        }
    }, [session?.status])
0

There are 0 answers