Cyril Muchemi
Cyril Muchemi

Reputation: 1

User credentials are null when using getSession() in middleware, next-auth

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')"

Upvotes: 0

Views: 753

Answers (1)

Yilmaz
Yilmaz

Reputation: 49671

I think the issue is here:

  session: async (session, user) => {

        session.user = user.user
        return Promise.resolve(session)
    }        

From the docs:

When using database sessions, the User object is passed as an argument. When using JSON Web Tokens for sessions, the JWT payload is provided instead.

so you are passing wrong arg. you have to destructure it:

   session: async ({session, user}) => {
        session.user = user.user
        return Promise.resolve(session)
    }       

this is example from the docs. pay attention to the arg

callbacks: {
  async session({ session, token, user }) {
    // Send properties to the client, like an access_token from a provider.
    session.accessToken = token.accessToken
    return session
  }
}

Upvotes: 0

Related Questions