I’m using Next-Auth 4 in NextJS 14 App Router.
I would like to display the entire user info on frontend such as: email, name.
However the useSession() hook only returns email.
Do you have any idea how to solve it?
Here is my code:
/app/api/auth/[...nextauth]/route.ts
import NextAuth from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";
import bcrypt from "bcrypt";
import jwt from "jsonwebtoken";
import { PrismaClient } from "@prisma/client";
const prisma = new PrismaClient();
const handler = NextAuth({
session: {
strategy: "jwt",
},
secret: process.env.NEXTAUTH_SECRET,
//debug: process.env.NODE_ENV === 'development',
callbacks: {},
pages: {
signIn: "/account/login",
},
// Configure one or more authentication providers
providers: [
CredentialsProvider({
// The name to display on the sign in form (e.g. "Sign in with...")
name: "Credentials",
// `credentials` is used to generate a form on the sign in page.
// You can specify which fields should be submitted, by adding keys to the `credentials` object.
// e.g. domain, username, password, 2FA token, etc.
// You can pass any HTML attribute to the <input> tag through the object.
credentials: {
username: { label: "Username", type: "text" },
password: { label: "Password", type: "password" },
},
async authorize(credentials: any) {
const { username, password } = credentials;
try {
// Look up user by email
const user = await prisma.user.findUnique({
where: {
email: username || "",
},
});
// If user not found or password does not match, return null
if (
!user ||
!(await bcrypt.compare(password, user.password))
) {
return null;
}
// Generate JWT token
const token = jwt.sign(
{
id: user.id,
email: user.email,
firstName: user.firstName,
lastName: user.lastName,
role: user.roleId,
}, // Payload
"secret", // JWT secret
{ expiresIn: "30d" } // Token expiration time
);
// Return user data along with token
return {
id: user.id,
email: user.email,
firstName: user.firstName,
lastName: user.lastName,
role: user.roleId,
token,
};
} catch (error) {
console.error("Login error:", error);
return null;
} finally {
await prisma.$disconnect();
}
},
callbacks: {
async jwt({ token, user }: { token: any; user: any }) {
// Persist the OAuth access_token to the token right after signin
console.log('jwt user',user);
if (user) {
token.firstName = user.firstName;
}
return token;
},
async session({
session,
token,
user,
}: {
session: any;
token: any;
user: any;
}) {
// Send properties to the client, like an access_token from a provider.
console.log('session user',user);
session.firstName = token.firstName;
return session;
},
},
}),
],
});
export { handler as GET, handler as POST };
Furthermore, I have a Type error in the authorize() function as well
Type '(credentials: any) => Promise<{ id: number; email: string; firstName: string; lastName: string; role: number; token: string; } | null>' is not assignable to type '(credentials: Record<"username" | "password", string> | undefined, req: Pick<RequestInternal, "query" | "body" | "headers" | "method">) => Awaitable<...>'.
Type 'Promise<{ id: number; email: string; firstName: string; lastName: string; role: number; token: string; } | null>' is not assignable to type 'Awaitable<User | null>'.
Type 'Promise<{ id: number; email: string; firstName: string; lastName: string; role: number; token: string; } | null>' is not assignable to type 'PromiseLike<User | null>'.
Types of property 'then' are incompatible.
Type '<TResult1 = { id: number; email: string; firstName: string; lastName: string; role: number; token: string; } | null, TResult2 = never>(onfulfilled?: ((value: { id: number; email: string; firstName: string; lastName: string; role: number; token: string; } | null) => TResult1 | PromiseLike<...>) | null | undefined, on...' is not assignable to type '<TResult1 = User | null, TResult2 = never>(onfulfilled?: ((value: User | null) => TResult1 | PromiseLike<TResult1>) | null | undefined, onrejected?: ((reason: any) => TResult2 | PromiseLike<...>) | null | undefined) => PromiseLike<...>'.
Types of parameters 'onfulfilled' and 'onfulfilled' are incompatible.
Types of parameters 'value' and 'value' are incompatible.
Type '{ id: number; email: string; firstName: string; lastName: string; role: number; token: string; } | null' is not assignable to type 'User | null'.
Type '{ id: number; email: string; firstName: string; lastName: string; role: number; token: string; }' is not assignable to type 'User'.
Types of property 'id' are incompatible.
Type 'number' is not assignable to type 'string'.ts(2322)
I did follow this topic I need help sending custom information to session.user object using next-auth but it does not solve my issue.