DEV Community

San
San

Posted on

Return object after login successfull using nextauth.js

  1. 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;
    },
  },
Enter fullscreen mode Exit fullscreen mode
  1. Looks like when you use useSession Hook in frontend side

Image description

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;

Enter fullscreen mode Exit fullscreen mode

Top comments (0)