Next.js Discord

Discord Forum

NextAuth - Redirect to the original requested page after successful login

Unanswered
Australian Freshwater Crocodile posted this in #help-forum
Open in Discord
Australian Freshwater CrocodileOP
Hi,

I have an AppRouter project and i've protected all my pages with the OktaProvider and Next-auth. I have a middleware which redirects the user if he's not logged in to the sign in page. I would like to redirect the user back to the originally requested page. But i can't find an example on how to do that. Any advice?

This is my sign in page

export default function Signin() {
  const router = useRouter();
  const { status } = useSession();

  useEffect(() => {
    if (status === "unauthenticated") {
      console.info("No JWT");
      signIn("okta", {});
    } else if (status === "authenticated") {
      console.info("authenticated");
    }
  }, [router, status]);

  // This should be barely visible
  return (
    <PageLayout>
      <div>Sign in...</div>
    </PageLayout>
  );
}

and this is my Middleware
import { withAuth } from "next-auth/middleware";

export default withAuth({
  pages: {
    signIn: "/auth/signin", // this is to force okta auth without showing the button
  },
});

export const config = { matcher: ["/:path*"] };

0 Replies