I'm trying to access the user credentials from the JWT & Session using callbacks
import NextAuth from "next-auth/next";
import CredentialsProvider from "next-auth/providers/credentials";
import User from "../../../models/user";
import dbConnect from "../../../config/dbConnect";
export default NextAuth({
session: {
strategy: "jwt",
},
providers: [
CredentialsProvider({
async authorize(credentials) {
dbConnect()
const { email, password } = credentials;
//check if email and password is entered
if(!email || !password) {
throw new Error('Please enter email or password');
}
//Find user in the database
const user = await User.findOne({ email }).select('+password')
if(!user) {
throw new Error('Invalid email or password')
}
//Check if password is correct or not
const isPasswordMatched = await user.comparePassword(password);
if(!isPasswordMatched) {
throw new Error('Invalid email or password')
}
return Promise.resolve(user)
}
})
],
callbacks: {
async jwt({ token, user }) {
// Persist the OAuth access_token to the token right after signin
if (user) {
token.accessToken = user.access_token
}
return token
},
session: async (session, user) => {
session.user = user.user
return Promise.resolve(session)
}
}
})
then I try accessing the details in the callback using getSession() method
import catchAsyncErrors from './catchAsyncErrors'
import ErrorHandler from '../utils/errorHandler'
import { getSession } from 'next-auth/react';
const isAuthenticatedUser = catchAsyncErrors(async (req, res, next) => {
let session = await getSession({ req });
console.log(session)
if (!session) {
return next(new ErrorHandler('Login first to access this resource', 401));
}
req.user = session.user;
next();
})
export {
isAuthenticatedUser
}
I then use the use()and handler methods from next connect to pass in the middleware
import nc from 'next-connect';
import dbConnect from '../../config/dbConnect';
import { currentUserProfile } from '../../controllers/authControllers'
import onError from '../../middlewares/errors';
import { isAuthenticatedUser } from '../../middlewares/auth'
const handler = nc({onError});
dbConnect();
handler.use(isAuthenticatedUser).get(currentUserProfile);
export default handler;
However, this is the error I get after trying to access the user credentials using the /api/me route: "Cannot read properties of undefined (reading 'user')"