this is my next js index file. Here i have used next-auth version 4 library.
import React from 'react'
import { useRouter } from 'next/router'
import { useSession } from 'next-auth/react'
import { Login } from '@/components/Login/Login'
export default function Home() {
const router = useRouter()
const callbackUrl = (router.query?.callbackUrl as string) ?? '/dashboard'
const { data: session, status } = useSession()
const loading = status === 'loading'
if (!loading && !session) {
return <Login />
}
if (session) {
router.push(callbackUrl)
}
}
I have passed a custom login page for the sigin. It was achieved by setting the page inside […nextauth].ts file
pages: {
signIn: '/'
}
Above custom login page contain below button with an onclick event for the sign in.
<Button
onClick={(e) => {
e.preventDefault()
signIn('cognito', { redirect: false })
}}
appearance={appearance}
style={{ fontWeight: 'bold' }}
>
But after the sign in, it’s correctly redirected to the requested page, but there is an error in the console:
Error: Abort fetching component for route: "/settings"
How to fix this issue?
2
Answers
This happens when calling
router.push()
from the main rendering flow as you are doing here :I see you are trying to check if the session is loading but this is not the right approach to do so
What you need to do is create a wrapper component that handles session loading and decides whether to return its children or a custom component (loading) while the session is loading.
Here is an answer where this is explained in detail.
it’s because router.push() runs multiple times before it finishes loading the earlier router.push(). I think below is a better answer. it has some worked out solutions.
Here is an answer where this is explained in detail.