Next.js Discord

Discord Forum

Sign-in redirect URL not working from server NextAuth

Answered
Standard Chinchilla posted this in #help-forum
Open in Discord
Standard ChinchillaOP
I have a server component where I check the for the users session. If it exists it returns the react view. If the session is not authenticated then the route will redirect to /api/auth/signin using next/navigation router. The problem is that when the user logs in, nextauth redirects to the dashboard not the page that they came from. Code below:

import { getAuthSession } from "@/utils/auth";
import { redirect } from "next/navigation";

export default async function Home() {
  const session = await getAuthSession();

  if (!(session && session.account)) return redirect("/api/auth/signin");
  
  return (
    <>Page</>
}
Answered by Standard Chinchilla
found the solution:
return redirect(
      `/api/auth/signin?${new URLSearchParams({
        callbackUrl: process.env.NEXTAUTH_URL! + "/pageToCallbackTo",
      })}`
    );
View full answer

1 Reply

Standard ChinchillaOP
found the solution:
return redirect(
      `/api/auth/signin?${new URLSearchParams({
        callbackUrl: process.env.NEXTAUTH_URL! + "/pageToCallbackTo",
      })}`
    );
Answer