Experimenting with new tools, I encountered an issue when trying to utilize the auth() function to access user data stored within it. TypeScript is indicating that the user does not exist in Session even though I have declared it. Here is my auth.ts file:
import NextAuth from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";
import { authConfig } from "./authconfig";
import { connectDb } from "./lib/utils";
import { User } from "./lib/models";
import bcrypt from "bcrypt";
import { UserType } from "./lib/types";
declare module "next-auth" {
interface Session {
user?: UserType;
}
}
declare module "next-auth" {
interface User {
username: string;
img: string;
}
}
const login = async (credentials: Partial<Record<string, unknown>>) => {
try {
connectDb();
const user = await User.findOne({ username: credentials.username });
if (!user) throw new Error("Invalid credentials");
const isPasswordCorrect = await bcrypt.compare(
credentials.password as string,
user.password
);
if (!isPasswordCorrect) throw new Error("Invalid credentials");
return user;
} catch (error) {
console.log(error);
throw new Error("Login failed");
}
};
export const { signIn, signOut, auth } = NextAuth({
...authConfig,
providers: [
CredentialsProvider({
async authorize(credentials) {
try {
const user = await login(credentials);
return user;
} catch (error) {
return null;
}
},
}),
],
callbacks: {
async session({ session, user }) {
if (session.user) {
session.user.username = user.username;
session.user.img = user.img;
}
return session;
},
},
});
And here is where the auth() function is executed:
import { MdLogout } from "react-icons/md";
import styles from "./sidebar.module.scss";
import MenuLink from "./menuLink/menuLink";
import Image from "next/image";
import { MENU_ITEMS } from "@/app/data/menuItems";
import { auth, signOut } from "@/app/auth";
import { authProvider } from "./authProvider";
const Sidebar = async () => {
const { user } = await auth();
return (
<div className={styles.container}>
<div className={styles.user}>
<Image
className={styles.userImage}
priority
src={user?.img || "/noavatar.png"}
alt=""
width="50"
height="50"
/>
<div className={styles.userDetail}>
<span className={styles.username}>{user?.username}</span>
<span className={styles.userTitle}>Administrator</span>
</div>
</div>
<ul className={styles.list}>
{MENU_ITEMS.map((category) => (
<li key={category.title}>
<span className={styles.category}>{category.title}</span>
{category.list.map((item) => (
<MenuLink item={item} key={item.title} />
))}
</li>
))}
</ul>
<form
action={async () => {
"use server";
await signOut();
}}
>
<button className={styles.logout}>
<MdLogout />
Log out
</button>
</form>
</div>
);
};
export default Sidebar;
Despite declaring the user object in Session, TypeScript still raises an error stating: Property 'user' does not exist on type 'Session | null'. Can anyone advise on how to resolve this issue?