Redirect to login page from a server component
Answered
Spectacled Caiman posted this in #help-forum
Spectacled CaimanOP
Hey guys, so I have the following snippet of a simple test page, using NextAuth:
So, this doesn't work since signIn() has to be invoked client side. My idea is to redirect the user to the login page of the credentials provider, without having to convert this to a client component and without having to use useEffect (since the idea of NextJs is to try to avoid client components)
Any idea how I can redirect the user? Sounds like a simple task but I can't work it out through the documentation.
export default async function Home() {
const session = await getServerSession(authOptions)
console.log("Session: ", session)
if (session?.error === "RefreshAccessTokenError") {
signIn(); // Force sign in to hopefully resolve error
}So, this doesn't work since signIn() has to be invoked client side. My idea is to redirect the user to the login page of the credentials provider, without having to convert this to a client component and without having to use useEffect (since the idea of NextJs is to try to avoid client components)
Any idea how I can redirect the user? Sounds like a simple task but I can't work it out through the documentation.
Answered by Spectacled Caiman
The solution was a plain old redirect:
export default async function Home() {
const session = await getServerSession(authOptions)
console.log("Session: ", session)
if (session?.error === "RefreshAccessTokenError" || !session?.user.accessToken) {
return redirect("api/auth/signin")
}2 Replies
Spectacled CaimanOP
Also, I am setting this error inside the JWT callback, so if I am able to redirect from there to the login page - it's still a valid option for me
Spectacled CaimanOP
The solution was a plain old redirect:
export default async function Home() {
const session = await getServerSession(authOptions)
console.log("Session: ", session)
if (session?.error === "RefreshAccessTokenError" || !session?.user.accessToken) {
return redirect("api/auth/signin")
}Answer