- Add callback in api/auth/[...nextauth]/routes.js/ts
callbacks: {
jwt: async ({ token, user }) => {
user && (token.user = user);
return token;
},
session: async ({ session, token }) => {
session.user = token.user;
return session;
},
},
- Looks like when you use useSession Hook in frontend side
Profile page
"use client";
import { useSession } from "next-auth/react";
import { useRouter } from "next/navigation";
import React from "react";
import toast from "react-hot-toast";
const ProfilePage = () => {
const router = useRouter();
const { data: session, status }: any = useSession({
required: true,
onUnauthenticated() {
handleOnUnauthenticated();
},
});
function handleOnUnauthenticated() {
toast.error("Unauthenticated user, Please login with your credentials.");
}
console.log("session", { session, status });
if (session === null || undefined) {
return router.push("/auth/login");
}
return (
<div>
{status === "authenticated" ? (
<div>
<h1 className="text-3xl text-bold">
Profile login as: {session?.user?.role} <br />
<br />
{JSON.stringify(session?.user)}
</h1>
</div>
) : (
"Loading"
)}
</div>
);
};
export default ProfilePage;
Top comments (0)